-
Notifications
You must be signed in to change notification settings - Fork 16
/
io.c
2719 lines (2280 loc) · 74 KB
/
io.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
/*******************************************************************************************
*
* A module adapted from the VGPseq library (written by me). This input module can
* read fasta, fastq, sam, bam, and cram files along with Dazzler db's and dam's.
* Given a target # of threads ITHREADS, it first finds partition points in the input file
* that split the file into the required # of parts:
*
* Input_Partition *Partition_Input(int argc, char *argv[])
*
* It can then either supply a single large training block:
*
* DATA_BLOCK *Get_First_Block(Input_Partition *parts, int64 numbp)
*
* or in a thread parallel manner read each partition and transmit it in DATA_BLOCKs to a
* given call-back routine:
*
* void Scan_All_Input(Input_Partition *parts)
*
* Author: Gene Myers
* Date: October 2020
*
*******************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdbool.h>
#include "libfastk.h"
#include "FastK.h"
#include "LIBDEFLATE/libdeflate.h"
#include "HTSLIB/htslib/hts.h"
#include "HTSLIB/htslib/hfile.h"
#include "HTSLIB/cram/cram.h"
#include <zlib.h>
#undef DEBUG_FIND
#undef DEBUG_IO
#undef DEBUG_TRAIN
#undef DEBUG_OUT
#undef DEBUG_AUTO
#undef DEBUG_BAM_IO
#undef DEBUG_BAM_RECORD
#ifdef DEBUG_OUT
#define CALL_BACK Print_Block
#else
#define CALL_BACK Distribute_Block
#endif
#define IO_BLOCK 10000000ll
#define DT_BLOCK 1000000ll
#define DT_MINIM 100000ll
#define DT_READS 10000
typedef struct libdeflate_decompressor DEPRESS;
#define INT_MAXLEN 10
#define CRAM 0
#define BAM 1
#define SAM 2
#define FASTQ 3
#define FASTA 4
#define DAZZ 5
static char *Tstring[7] = { "cram", "bam", "sam", "fastq", "fasta", "db", "dam" };
typedef struct
{ char *path; // Full path name
char *root; // Ascii root name
char *pwd; // Ascii path name
int64 fsize; // Size of file in bytes
int ftype; // Type of file
int zipd; // Is file gzip'd
int64 zsize; // Size of compression index for cram and dazz
int64 *zoffs; // zoffs[i] = offset to compressed block i
int DB_all; // Trim parameters for Dazzler DB's
int DB_cut;
} File_Object;
typedef struct
{ int64 fpos; // offset in source file of desired unit (gzip block, cram contaianer)
uint32 boff; // offset within a unit block of desired record
} Location;
#define SAMPLE 0
#define SPLIT 1
typedef struct
{ File_Object *fobj; // array of file objects
uint8 *buf; // block buffer
int fid; // fid of fobj[bidx].path
int bidx; // Scan range is [bidx:beg,eidx:end)
Location beg;
int eidx;
Location end;
int action; // sampling or splitting
int64 work; // total sizes of all files
DATA_BLOCK block; // block buffer for this thread
int thread_id; // thread index (in [0,NTHREAD-1]
void * (*output_thread)(void *); // output routine for file type
DEPRESS *decomp; // decompressor
} Thread_Arg;
static void do_nothing(Thread_Arg *parm)
{ (void) parm; }
/*******************************************************************************************
*
* Routines to open and close the sequence file types supported
*
********************************************************************************************/
// Open and get info about each input file
static int64 *genes_cram_index(char *path, int64 fsize, int64 *zsize);
static void read_DB_stub(char *path, int *cut, int *all);
static int64 *get_dazz_offsets(FILE *idx, int64 *zsize);
static void Fetch_File(char *arg, File_Object *input, int gz_ok)
{ static char *suffix[] = { ".cram", ".bam", ".sam", ".db", ".dam",
".fastq", ".fasta", ".fq", ".fa",
".fastq.gz", ".fasta.gz", ".fastq", ".fasta",
".fq.gz", ".fa.gz", ".fq", ".fa" };
static char *extend[] = { ".cram", ".bam", ".sam", ".db", ".dam",
".fastq", ".fasta", ".fq", ".fa",
".fastq.gz", ".fasta.gz", ".fastq.gz", ".fasta.gz",
".fq.gz", ".fa.gz", ".fq.gz", ".fa.gz" };
struct stat stats;
char *pwd, *root, *path, *temp;
int fid, i;
int64 fsize, zsize, *zoffs;
int ftype, zipd;
pwd = PathTo(arg);
for (i = 0; i < 17; i++)
{ root = Root(arg,suffix[i]);
fid = open(Catenate(pwd,"/",root,extend[i]),O_RDONLY);
if (fid >= 0) break;
free(root);
}
if (fid < 0)
{ fprintf(stderr,"\n%s: Cannot open %s as a .cram|[bs]am|f{ast}[aq][.gz]|db|dam file\n",
Prog_Name,arg);
Clean_Exit(1);
}
if (i == 3 || i == 4)
ftype = DAZZ;
else if (i >= 5)
ftype = FASTA - (i%2);
else
ftype = i;
zipd = (i >= 9);
path = Strdup(Catenate(pwd,"/",root,extend[i]),"Allocating full path name");
zoffs = NULL;
if (zipd)
{ if (gz_ok)
{ if (stat(path,&stats) == -1)
{ fprintf(stderr,"\n%s: Cannot get stats for %s\n",Prog_Name,path);
Clean_Exit(1);
}
fsize = stats.st_size;
zsize = (fsize-1)/IO_BLOCK+1;
}
else
{ if (VERBOSE)
fprintf(stderr," Gzipped file %s being temporarily uncompressed\n",arg);
temp = Strdup(Catenate(SORT_PATH,"/",root,extend[i]),"Allocating full path name");
temp[strlen(temp)-3] = '\0';
system(Catenate("gunzip -c ",path," >",temp));
free(path);
path = temp;
zipd = 0;
if (stat(path,&stats) == -1)
{ fprintf(stderr,"\n%s: Cannot get stats for %s\n",Prog_Name,path);
Clean_Exit(1);
}
fsize = stats.st_size;
zsize = (fsize-1)/IO_BLOCK+1;
}
}
else if (ftype == DAZZ)
{ FILE *idx;
read_DB_stub(path,&(input->DB_cut),&(input->DB_all));
free(path);
close(fid);
path = Strdup(Catenate(pwd,"/.",root,".bps"),"Allocating full path name");
fid = open(path,O_RDONLY);
if (fid < 0)
{ fprintf(stderr,"\n%s: Dazzler DB %s does not have a .bps file ! ?\n",Prog_Name,root);
Clean_Exit(1);
}
if (fstat(fid, &stats) == -1)
{ fprintf(stderr,"\n%s: Cannot get stats for %s\n",Prog_Name,arg);
Clean_Exit(1);
}
fsize = stats.st_size;
idx = fopen(Catenate(pwd,"/.",root,".idx"),"r");
if (idx == NULL)
{ fprintf(stderr,"\n%s: Dazzler DB %s does not have a .idx file ! ?\n",Prog_Name,root);
Clean_Exit(1);
}
zoffs = get_dazz_offsets(idx,&zsize);
zoffs[zsize] = fsize;
fclose(idx);
}
else
{ if (fstat(fid, &stats) == -1)
{ fprintf(stderr,"\n%s: Cannot get stats for %s\n",Prog_Name,arg);
Clean_Exit(1);
}
fsize = stats.st_size;
if (ftype == CRAM)
zoffs = genes_cram_index(path,fsize,&zsize);
else
zsize = (fsize-1)/IO_BLOCK+1;
}
#ifdef DEBUG_FIND
fprintf(stderr,"\n%s is a %s file, ftype = %d, zipd = %d, fsize = %lld\n",
arg,suffix[i],ftype,zipd,fsize);
#endif
close(fid);
input->path = path;
input->root = root;
input->pwd = pwd;
input->fsize = fsize;
input->ftype = ftype;
input->zipd = zipd;
input->zsize = zsize;
input->zoffs = zoffs;
}
static void Free_File(File_Object *input, int gz_ok)
{ if (!gz_ok && input->zipd)
unlink(input->path);
free(input->zoffs);
free(input->path);
free(input->root);
free(input->pwd);
}
static void Free_Gunzips( File_Object *input, int n)
{ int i;
for (i = 0; i < n; i++)
if (input[i].zipd)
unlink(input[i].path);
}
/*******************************************************************************************
*
* DATA_BLOCK CODE
*
********************************************************************************************/
static int homo_compress(char *seq, int len)
{ int i, x, n;
n = 0;
x = seq[n++];
for (i = 1; i < len; i++)
if (seq[i] != x)
seq[n++] = x = seq[i];
seq[n] = '\0';
return (n);
}
static int Add_Data_Block(DATA_BLOCK *dset, int len, char *seq)
{ int n, r;
int64 o;
r = 0;
n = dset->nreads;
o = dset->boff[n];
if (dset->rem > 0)
{ len = dset->rem;
seq = dset->next;
}
else if (COMPRESS)
len = homo_compress(seq,len);
if (n >= dset->maxrds)
return (1);
if (o+len >= dset->maxbps)
{ if (dset->maxbps-o > DT_MINIM)
{ r = 1;
dset->rem = len;
len = (dset->maxbps-o);
dset->rem -= (len - (KMER-1));
dset->next = seq + (len - (KMER-1));
}
else
return (1);
}
else
dset->rem = 0;
dset->nreads = ++n;
memcpy(dset->bases+o,seq,len);
o += len;
dset->bases[o] = '\0';
dset->boff[n] = o+1;
dset->totlen += len;
return (r);
}
#if defined(DEBUG_OUT) || defined(DEBUG_TRAIN)
static void Print_Block(DATA_BLOCK *dset, int tid)
{ int64 end;
int i;
char *bases;
static int tc = 0;
(void) tid;
printf("Buffer load rem = %d\n",dset->rem);
bases = dset->bases;
for (i = 0; i < dset->nreads; i++)
{ end = dset->boff[i+1]-1;
printf("%5d %8d:\n",i,tc++);
#undef ONE_LINE
#ifdef ONE_LINE
printf(" %.80s\n",bases+dset->boff[i]);
#else
{ int64 j;
for (j = dset->boff[i]; j+80 < end; j += 80)
printf(" %.80s\n",bases+j);
if (j < end)
printf(" %.*s\n",(int) (end-j),bases+j);
}
#endif
}
fflush(stdout);
}
#endif
static void Reset_Data_Block(DATA_BLOCK *dset, int roll)
{ if (roll)
{ memcpy(dset->bases,dset->bases+(dset->boff[dset->nreads]-KMER),KMER-1);
dset->totlen = KMER-1;
}
else
dset->totlen = 0;
dset->nreads = 0;
dset->boff[0] = 0;
}
/*******************************************************************************************
*
* FASTA / FASTQ SPECIFIC CODE
*
********************************************************************************************/
/*******************************************************************************************
*
* fast_nearest: Routine to find next entry given arbitray start point.
*
********************************************************************************************/
// Automata states (buffer is processed char at a time)
#define UK 0
#define FK 1
#define FK1 2
#if defined(DEBUG_AUTO)
static char *Name[] =
{ "UK", "FK", "FK1", "QHL" };
#endif
// Check blocks [beg,end) starting with the first complete entry and proceeding
// into blocks end ... if necessary to complete the last entry started in this
// range.
static void fast_nearest(Thread_Arg *data)
{ int fid = data->fid;
int64 beg = data->beg.fpos;
uint8 *buf = data->buf;
File_Object *inp = data->fobj + data->bidx;
int fastq = (inp->ftype == FASTQ);
int64 blk, off;
int slen;
int state;
int nl_1, nl_2, pl_1, alive;
int b, c;
#ifdef DEBUG_FIND
fprintf(stderr,"\nFind starting at %lld\n",beg);
#endif
blk = beg / IO_BLOCK;
off = beg % IO_BLOCK;
lseek(fid,blk*IO_BLOCK,SEEK_SET);
if (fastq)
state = UK;
else
state = FK;
nl_1 = pl_1 = nl_2 = 1;
alive = 0;
#ifdef DEBUG_FIND
fprintf(stderr,"\nFrom block %lld / offset %lld\n",blk,off);
#endif
while (blk < inp->zsize)
{
#ifdef DEBUG_FIND
fprintf(stderr," Loading block %lld: @%lld",blk,lseek(fid,0,SEEK_CUR));
#endif
slen = read(fid,buf,IO_BLOCK);
#ifdef DEBUG_FIND
fprintf(stderr," %d %d\n",slen,errno);
#endif
for (b = off; b < slen; b++)
{ c = buf[b];
#ifdef DEBUG_AUTO
fprintf(stderr," %.5s: %c\n",Name[state],c);
#endif
switch (state)
{ case UK:
if (c == '@' && alive)
{ data->beg.fpos = blk*IO_BLOCK + b;
data->beg.boff = 0;
return;
}
alive = (c == '\n' && ! (nl_2 || pl_1));
nl_2 = nl_1;
nl_1 = (c == '\n');
pl_1 = (c == '+');
#ifdef DEBUG_AUTO
fprintf(stderr," n2=%d n1=%d p1=%d a=%d\n",nl_2,nl_1,pl_1,alive);
#endif
break;
case FK:
if (c == '\n')
state = FK1;
break;
case FK1:
if (c == '>')
{ data->beg.fpos = blk*IO_BLOCK + b;
data->beg.boff = 0;
return;
}
else if (c != '\n')
state = FK;
break;
}
}
blk += 1;
off = 0;
}
data->beg.fpos = -1;
data->beg.boff = 0;
return;
}
/*******************************************************************************************
*
* Second pass thread routines prepare .seq formated output in buffers for each input block.
* Note carefully that there are separate blocks for the forward and reverse files if
* processing a pair, the reads in the blocks need to be paired.
*
********************************************************************************************/
// Automata states (buffer is processed char at a time)
#define QAT 0
#define HSKP 1
#define QSEQ 2
#define QPLS 3
#define QSKP 4
#define ASEQ 5
#define AEOL 6
#if defined(DEBUG_AUTO)
static char *Name2[] =
{ "QAT", "HEAD", "HSKP", "QSEQ", "QPLS", "QSKP", "QQVS", "ASEQ", "AEOL" };
#endif
#define DUMP(scale,notyet,dclose) \
if (action == SAMPLE) \
{ dset->ratio = ((1.*parm->work) / (totread-(notyet))) * scale; \
dset->totlen = dset->boff[dset->nreads] - dset->nreads; \
dclose(fid); \
return (NULL); \
} \
else \
{ dset->totlen = dset->boff[dset->nreads] - dset->nreads; \
CALL_BACK(dset,tid); \
if (CLOCK) \
{ cumbps += dset->totlen; \
if (cumbps >= nxtbps) \
{ fprintf(stderr,"\r %3d%%",(int) ((100.*cumbps)/estbps)); \
fflush(stderr); \
nxtbps = cumbps+pct1; \
} \
} \
} \
#define END_SEQ(notyet) \
{ line[olen++] = lastc = '\0'; \
dset->boff[++dset->nreads] = olen; \
if (olen > omax-DT_MINIM || dset->nreads >= dset->maxrds) \
{ DUMP(ratio,notyet,close) \
Reset_Data_Block(dset,0); \
olen = 0; \
} \
}
#define ADD(c) \
{ if (!COMPRESS || c != lastc) \
{ if (olen >= omax) \
{ line[olen++] = '\0'; \
dset->boff[++dset->nreads] = olen; \
dset->rem = 1; \
DUMP(ratio,slen-b,close) \
dset->rem = 0; \
Reset_Data_Block(dset,1); \
olen = KMER-1; \
} \
line[olen++] = lastc = c; \
} \
}
// Write fast records in relevant partition
static void *fast_output_thread(void *arg)
{ Thread_Arg *parm = (Thread_Arg *) arg;
File_Object *fobj = parm->fobj;
uint8 *buf = parm->buf;
int action = parm->action;
DATA_BLOCK *dset = &parm->block;
int tid = parm->thread_id;
int fastq = (fobj->ftype == FASTQ); // Is the same for all files (already checked)
File_Object *inp;
int f, fid;
gzFile gzid = NULL;
int64 blk, off;
int64 epos, eblk, eoff;
int64 totread;
double ratio;
int state, lastc;
int omax, olen;
char *line;
int64 estbps, cumbps, nxtbps, pct1;
int CLOCK;
estbps = nxtbps = pct1 = cumbps = 0;
if (VERBOSE && tid == 0 && action != SAMPLE)
{ estbps = dset->ratio / ITHREADS;
nxtbps = pct1 = estbps/100;
fprintf(stderr,"\n 0%%");
fflush(stderr);
CLOCK = 1;
}
else
CLOCK = 0;
// Do relevant section of each file assigned to this thread in sequence
omax = dset->maxbps;
line = dset->bases;
totread = 0;
olen = 0;
ratio = 1.;
for (f = parm->bidx; f <= parm->eidx; f++)
{ inp = fobj+f;
fid = open(inp->path,O_RDONLY);
if (f < parm->eidx)
epos = inp->fsize;
else
epos = parm->end.fpos;
if (f > parm->bidx)
parm->beg.fpos = 0;
#ifdef DEBUG_IO
fprintf(stderr,"Block: %12lld to %12lld --> %8lld\n",
parm->beg.fpos,epos,epos - parm->beg.fpos);
fflush(stdout);
#endif
blk = parm->beg.fpos / IO_BLOCK;
off = parm->beg.fpos % IO_BLOCK;
eblk = (epos-1) / IO_BLOCK;
eoff = (epos-1) % IO_BLOCK + 1;
if (inp->zipd)
{ gzid = gzdopen(fid,"r");
eblk = 0x7fffffffffffffffll;
}
else
lseek(fid,blk*IO_BLOCK,SEEK_SET);
state = QAT;
lastc = 0;
#ifdef DEBUG_IO
fprintf(stderr,"\nFrom block %lld / offset %lld\n",blk,off);
#endif
while (blk <= eblk)
{ int c, b, slen;
#ifdef DEBUG_IO
fprintf(stderr," Loading block %lld: @%lld",blk,lseek(fid,0,SEEK_CUR));
#endif
if (inp->zipd)
{ slen = gzread(gzid,buf,IO_BLOCK);
if (blk == 0 && slen != 0 && action == SAMPLE)
ratio = (1.*slen) / gzoffset(gzid);
}
else
slen = read(fid,buf,IO_BLOCK);
if (slen == 0)
break;
totread += slen;
#ifdef DEBUG_IO
fprintf(stderr," %d\n",slen);
#endif
if (blk == eblk && eoff < slen)
slen = eoff;
for (b = off; b < slen; b++)
{ c = buf[b];
#ifdef DEBUG_AUTO
fprintf(stderr," %.5s: %c\n",Name2[state],c);
#endif
switch (state)
{ case QAT:
state = HSKP;
break;
case HSKP:
if (c == '\n')
{ if (fastq)
state = QSEQ;
else
state = ASEQ;
}
break;
case QSEQ:
if (c != '\n')
ADD(c)
else
{ END_SEQ(slen-b)
state = QPLS;
}
break;
case QPLS:
if (c == '\n')
state = QSKP;
break;
case QSKP:
if (c == '\n')
state = QAT;
break;
case AEOL:
if (c == '>')
{ END_SEQ(slen-b)
state = HSKP;
}
else if (c != '\n')
{ ADD(c)
state = ASEQ;
}
break;
case ASEQ:
if (c == '\n')
state = AEOL;
else
ADD(c)
}
}
blk += 1;
off = 0;
}
if (state == AEOL)
END_SEQ(0)
if (inp->zipd)
gzclose_r(gzid);
else
close(fid);
}
dset->totlen = dset->boff[dset->nreads] - dset->nreads;
if (action == SAMPLE)
{ dset->ratio = ((1.*parm->work) / totread) * ratio;
return (NULL);
}
else if (dset->nreads > 0)
CALL_BACK(dset,tid);
if (CLOCK)
fprintf(stderr,"\r \r");
return (NULL);
}
/*******************************************************************************************
*
* BAM/SAM SPECIFIC CODE
*
********************************************************************************************/
#define BAM_BLOCK 0x10000
#define HEADER_LEN 36
#define SEQ_RUN 40
static int DNA[256] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1,
0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1,
};
// Get value of little endian integer of n-bytes
static inline uint32 getint(uint8 *buf, int n)
{ uint32 val;
int k;
val = 0;
for (k = n-1; k >= 0; k--)
val = (val << 8) | buf[k];
return (val);
}
// Next len chars are printable and last is zero?
static inline int valid_name(char *name, int len)
{ int i;
if (len < 1)
return (0);
len -= 1;
for (i = 0; i < len; i++)
if ( ! isprint(name[i]))
return (0);
return (name[len] == 0);
}
// Next len ints are plausible cigar codes
static inline int valid_cigar(int32 *cigar, int len, int range)
{ int i, c;
for (i = 0; i < len; i++)
{ c = cigar[i];
if ((c & 0xf) > 8)
return (0);
c >>= 4;
if (c < 0 || c > range)
return (0);
}
return (1);
}
/*******************************************************************************************
*
* Routines to manage a BAM_FILE stream object
*
********************************************************************************************/
// Open BAM stream where compressed block start is known. Compressed BAM blocks are buffered
// in a very big IO buffer and the current uncompressed block is in a 64Kbp array.
typedef struct
{ int fid; // file descriptor
int last; // last block of data in file has been read
uint8 *buf; // IO buffer (of IO_BLOCK bytes, supplied by caller)
int blen; // # of bytes currently in IO buffer
int bptr; // start of next BAM block in IO buffer
uint8 bam[BAM_BLOCK+1]; // uncompressed bam block
uint32 bsize; // length of compressed bam block
uint32 ssize; // length of uncompressed bam block
Location loc; // current location in bam file
DEPRESS *decomp;
} BAM_FILE;
// Load next len bytes of uncompressed BAM data into array data
static void bam_get(BAM_FILE *file, uint8 *data, int len)
{ int chk, off;
uint8 *bam = file->bam;
int boff = file->loc.boff;
off = 0;
chk = file->ssize - boff;
while (len >= chk)
{ int bptr, blen, bsize;
uint8 *block, *buf;
uint32 ssize;
size_t tsize;
#ifdef DEBUG_BAM_IO
printf("Move %d bytes to data+%d from bam+%d\n",chk,off,boff);
#endif
if (data != NULL)
memcpy(data+off,bam+boff,chk);
off += chk;
len -= chk;
file->loc.fpos += file->bsize;
#ifdef DEBUG_BAM_IO
printf("File pos %lld\n",file->fpos);
#endif
if (chk == 0 && len == 0)
{ file->loc.boff = 0;
return;
}
buf = file->buf;
bptr = file->bptr;
blen = file->blen;
block = buf+bptr;
#ifdef DEBUG_BAM_IO
printf("Block at buffer %d\n",bptr);
#endif
while (bptr + 18 > blen || bptr + (bsize = getint(block+16,2) + 1) > blen)
{ chk = blen-bptr;
if (file->last)
{ fprintf(stderr,"\n%s: Corrupted BAM file\n",Prog_Name);
Clean_Exit(1);
}
memmove(buf,block,chk);
blen = chk + read(file->fid,buf+chk,IO_BLOCK-chk);
#ifdef DEBUG_BAM_IO
printf("Loaded %d to buf+%d for a total of %d\n",IO_BLOCK-chk,chk,blen);
#endif
if (blen < IO_BLOCK)
file->last = 1;
file->blen = blen;
bptr = 0;
block = buf;
}
// Fetch and uncompress next Bam block
if (libdeflate_gzip_decompress(file->decomp,block,bsize,bam,BAM_BLOCK,&tsize) != 0)
{ fprintf(stderr,"\n%s: Bad gzip block\n",Prog_Name);
Clean_Exit(1);
}
ssize = tsize;
boff = 0;
#ifdef DEBUG_BAM_IO
printf("Loaded gzip block of size %d into %d\n",bsize,ssize);
#endif
file->bsize = bsize;
file->ssize = ssize;
file->bptr = bptr + bsize;
chk = ssize;
}
#ifdef DEBUG_BAM_IO
printf("Xfer %d bytes to data+%d from bam+%d\n",len,off,boff);
#endif
if (data != NULL)
memcpy(data+off,bam+boff,len);
file->loc.boff = boff+len;
}
// Startup a bam stream, the location must be valid.
static void bam_start(BAM_FILE *file, int fid, uint8 *buf, Location *loc)
{ file->fid = fid;
file->ssize = 0;
file->bsize = 0;
file->buf = buf;
file->bptr = 0;
file->blen = 0;
file->last = 0;
lseek(fid,loc->fpos,SEEK_SET);
file->loc.fpos = loc->fpos;
file->loc.boff = 0;
bam_get(file,NULL,loc->boff);
}
static int bam_eof(BAM_FILE *file)
{ return (file->loc.boff == file->ssize && file->bptr == file->blen && file->last); }
/*******************************************************************************************
*
* Routines to manage a SAM stream, but as a BAM_FILE (only select fields are used)
*
********************************************************************************************/
// Get next line of SAM input if possible
static uint8 *sam_getline(BAM_FILE *file)
{ int rem;
int blen = file->blen;
int bptr = file->bptr;
uint8 *buf = file->buf;
uint8 *b, *d;
b = buf + bptr;
rem = blen-bptr;
if (rem == 0)
d = NULL;
else
d = memchr(b,'\n',rem);
if (d == NULL)
{ if (file->last)
{ fprintf(stderr,"\n%s: Corrupted SAM file",Prog_Name);
Clean_Exit(1);
}
memmove(buf,buf+bptr,rem);
blen = rem + read(file->fid,buf+rem,IO_BLOCK-rem);
if (blen < IO_BLOCK)
file->last = 1;
file->blen = blen;
bptr = 0;
b = buf;
d = memchr(b,'\n',blen);
if (d == NULL)
{ if (blen < IO_BLOCK)
fprintf(stderr,"\n%s: Corrupted SAM file",Prog_Name);
else
fprintf(stderr,"\n%s: SAM-line is longer than max %lld\n",Prog_Name,IO_BLOCK);
Clean_Exit(1);
}