/
cram_io.c
3652 lines (3072 loc) · 87.9 KB
/
cram_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
/*
Copyright (c) 2012-2014 Genome Research Ltd.
Author: James Bonfield <jkb@sanger.ac.uk>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the names Genome Research Ltd and Wellcome Trust Sanger
Institute nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL GENOME RESEARCH LTD OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* CRAM I/O primitives.
*
* - ITF8 encoding and decoding.
* - Block based I/O
* - Zlib inflating and deflating (memory)
* - CRAM basic data structure reading and writing
* - File opening / closing
* - Reference sequence handling
*/
/*
* TODO: BLOCK_GROW, BLOCK_RESIZE, BLOCK_APPEND and itf8_put_blk all need
* a way to return errors for when malloc fails.
*/
#ifdef HAVE_CONFIG_H
#include "io_lib_config.h"
#endif
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#ifdef HAVE_LIBBZ2
#include <bzlib.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <math.h>
#include <ctype.h>
#include "cram/cram.h"
#include "cram/os.h"
#include "cram/md5.h"
#include "cram/open_trace_file.h"
//#define REF_DEBUG
#ifdef REF_DEBUG
#include <sys/syscall.h>
#define gettid() (int)syscall(SYS_gettid)
#define RP(...) fprintf (stderr, __VA_ARGS__)
#else
#define RP(...)
#endif
#ifdef SAMTOOLS
#include "htslib/hfile.h"
#define paranoid_hclose(fp) (hclose(fp))
#else
#define hclose_abruptly(fp) (fclose(fp))
#define hflush(fp) (fflush(fp))
#define hgetc(fp) (getc(fp))
#define hputc(c, fp) (putc((c), (fp)))
#define hread(fp, buffer, nbytes) (fread((buffer), 1, (nbytes), (fp)))
#define hseek(fp, offset, whence) (fseeko((fp), (offset), (whence)))
#define hwrite(fp, buffer, nbytes) (fwrite((buffer), 1, (nbytes), (fp)))
#define paranoid_hclose(fp) (paranoid_fclose(fp))
#endif
/* ----------------------------------------------------------------------
* ITF8 encoding and decoding.
*
* Also see the itf8_get and itf8_put macros in cram_io.h
*/
/*
* Reads an integer in ITF-8 encoding from 'cp' and stores it in
* *val.
*
* Returns the number of bytes read on success
* -1 on failure
*/
int itf8_decode(cram_fd *fd, int32_t *val_p) {
static int nbytes[16] = {
0,0,0,0, 0,0,0,0, // 0000xxxx - 0111xxxx
1,1,1,1, // 1000xxxx - 1011xxxx
2,2, // 1100xxxx - 1101xxxx
3, // 1110xxxx
4, // 1111xxxx
};
static int nbits[16] = {
0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, // 0000xxxx - 0111xxxx
0x3f, 0x3f, 0x3f, 0x3f, // 1000xxxx - 1011xxxx
0x1f, 0x1f, // 1100xxxx - 1101xxxx
0x0f, // 1110xxxx
0x0f, // 1111xxxx
};
int32_t val = hgetc(fd->fp);
if (val == -1)
return -1;
int i = nbytes[val>>4];
val &= nbits[val>>4];
switch(i) {
case 0:
*val_p = val;
return 1;
case 1:
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val;
return 2;
case 2:
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val;
return 3;
case 3:
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val;
return 4;
case 4: // really 3.5 more, why make it different?
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<4) | (((unsigned char)hgetc(fd->fp)) & 0x0f);
*val_p = val;
}
return 5;
}
/*
* Encodes and writes a single integer in ITF-8 format.
* Returns 0 on success
* -1 on failure
*/
int itf8_encode(cram_fd *fd, int32_t val) {
char buf[5];
int len = itf8_put(buf, val);
return hwrite(fd->fp, buf, len) == len ? 0 : -1;
}
#ifndef ITF8_MACROS
/*
* As above, but decoding from memory
*/
int itf8_get(char *cp, int32_t *val_p) {
unsigned char *up = (unsigned char *)cp;
if (up[0] < 0x80) {
*val_p = up[0];
return 1;
} else if (up[0] < 0xc0) {
*val_p = ((up[0] <<8) | up[1]) & 0x3fff;
return 2;
} else if (up[0] < 0xe0) {
*val_p = ((up[0]<<16) | (up[1]<< 8) | up[2]) & 0x1fffff;
return 3;
} else if (up[0] < 0xf0) {
*val_p = ((up[0]<<24) | (up[1]<<16) | (up[2]<<8) | up[3]) & 0x0fffffff;
return 4;
} else {
*val_p = ((up[0] & 0x0f)<<28) | (up[1]<<20) | (up[2]<<12) | (up[3]<<4) | (up[4] & 0x0f);
return 5;
}
}
/*
* Stores a value to memory in ITF-8 format.
*
* Returns the number of bytes required to store the number.
* This is a maximum of 5 bytes.
*/
int itf8_put(char *cp, int32_t val) {
if (!(val & ~0x00000007f)) { // 1 byte
*cp = val;
return 1;
} else if (!(val & ~0x00003fff)) { // 2 byte
*cp++ = (val >> 8 ) | 0x80;
*cp = val & 0xff;
return 2;
} else if (!(val & ~0x01fffff)) { // 3 byte
*cp++ = (val >> 16) | 0xc0;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 3;
} else if (!(val & ~0x0fffffff)) { // 4 byte
*cp++ = (val >> 24) | 0xe0;
*cp++ = (val >> 16) & 0xff;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 4;
} else { // 5 byte
*cp++ = 0xf0 | ((val>>28) & 0xff);
*cp++ = (val >> 20) & 0xff;
*cp++ = (val >> 12) & 0xff;
*cp++ = (val >> 4 ) & 0xff;
*cp = val & 0x0f;
return 5;
}
}
#endif
/* 64-bit itf8 variant */
int ltf8_put(char *cp, int64_t val) {
if (!(val & ~((1LL<<7)-1))) {
*cp = val;
return 1;
} else if (!(val & ~((1LL<<(6+8))-1))) {
*cp++ = (val >> 8 ) | 0x80;
*cp = val & 0xff;
return 2;
} else if (!(val & ~((1LL<<(5+2*8))-1))) {
*cp++ = (val >> 16) | 0xc0;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 3;
} else if (!(val & ~((1LL<<(4+3*8))-1))) {
*cp++ = (val >> 24) | 0xe0;
*cp++ = (val >> 16) & 0xff;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 4;
} else if (!(val & ~((1LL<<(3+4*8))-1))) {
*cp++ = (val >> 32) | 0xf0;
*cp++ = (val >> 24) & 0xff;
*cp++ = (val >> 16) & 0xff;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 5;
} else if (!(val & ~((1LL<<(2+5*8))-1))) {
*cp++ = (val >> 40) | 0xf8;
*cp++ = (val >> 32) & 0xff;
*cp++ = (val >> 24) & 0xff;
*cp++ = (val >> 16) & 0xff;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 6;
} else if (!(val & ~((1LL<<(1+6*8))-1))) {
*cp++ = (val >> 48) | 0xfc;
*cp++ = (val >> 40) & 0xff;
*cp++ = (val >> 32) & 0xff;
*cp++ = (val >> 24) & 0xff;
*cp++ = (val >> 16) & 0xff;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 7;
} else if (!(val & ~((1LL<<(7*8))-1))) {
*cp++ = (val >> 56) | 0xfe;
*cp++ = (val >> 48) & 0xff;
*cp++ = (val >> 40) & 0xff;
*cp++ = (val >> 32) & 0xff;
*cp++ = (val >> 24) & 0xff;
*cp++ = (val >> 16) & 0xff;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 8;
} else {
*cp++ = 0xff;
*cp++ = (val >> 56) & 0xff;
*cp++ = (val >> 48) & 0xff;
*cp++ = (val >> 40) & 0xff;
*cp++ = (val >> 32) & 0xff;
*cp++ = (val >> 24) & 0xff;
*cp++ = (val >> 16) & 0xff;
*cp++ = (val >> 8 ) & 0xff;
*cp = val & 0xff;
return 9;
}
}
int ltf8_get(char *cp, int64_t *val_p) {
unsigned char *up = (unsigned char *)cp;
if (up[0] < 0x80) {
*val_p = up[0];
return 1;
} else if (up[0] < 0xc0) {
*val_p = (((uint64_t)up[0]<< 8) |
(uint64_t)up[1]) & (((1LL<<(6+8)))-1);
return 2;
} else if (up[0] < 0xe0) {
*val_p = (((uint64_t)up[0]<<16) |
((uint64_t)up[1]<< 8) |
(uint64_t)up[2]) & ((1LL<<(5+2*8))-1);
return 3;
} else if (up[0] < 0xf0) {
*val_p = (((uint64_t)up[0]<<24) |
((uint64_t)up[1]<<16) |
((uint64_t)up[2]<< 8) |
(uint64_t)up[3]) & ((1LL<<(4+3*8))-1);
return 4;
} else if (up[0] < 0xf8) {
*val_p = (((uint64_t)up[0]<<32) |
((uint64_t)up[1]<<24) |
((uint64_t)up[2]<<16) |
((uint64_t)up[3]<< 8) |
(uint64_t)up[4]) & ((1LL<<(3+4*8))-1);
return 5;
} else if (up[0] < 0xfc) {
*val_p = (((uint64_t)up[0]<<40) |
((uint64_t)up[1]<<32) |
((uint64_t)up[2]<<24) |
((uint64_t)up[3]<<16) |
((uint64_t)up[4]<< 8) |
(uint64_t)up[5]) & ((1LL<<(2+5*8))-1);
return 6;
} else if (up[0] < 0xfe) {
*val_p = (((uint64_t)up[0]<<48) |
((uint64_t)up[1]<<40) |
((uint64_t)up[2]<<32) |
((uint64_t)up[3]<<24) |
((uint64_t)up[4]<<16) |
((uint64_t)up[5]<< 8) |
(uint64_t)up[6]) & ((1LL<<(1+6*8))-1);
return 7;
} else if (up[0] < 0xff) {
*val_p = (((uint64_t)up[1]<<48) |
((uint64_t)up[2]<<40) |
((uint64_t)up[3]<<32) |
((uint64_t)up[4]<<24) |
((uint64_t)up[5]<<16) |
((uint64_t)up[6]<< 8) |
(uint64_t)up[7]) & ((1LL<<(7*8))-1);
return 8;
} else {
*val_p = (((uint64_t)up[1]<<56) |
((uint64_t)up[2]<<48) |
((uint64_t)up[3]<<40) |
((uint64_t)up[4]<<32) |
((uint64_t)up[5]<<24) |
((uint64_t)up[6]<<16) |
((uint64_t)up[7]<< 8) |
(uint64_t)up[8]);
return 9;
}
}
int ltf8_decode(cram_fd *fd, int64_t *val_p) {
int c = hgetc(fd->fp);
int64_t val = (unsigned char)c;
if (c == -1)
return -1;
if (val < 0x80) {
*val_p = val;
return 1;
} else if (val < 0xc0) {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val & (((1LL<<(6+8)))-1);
return 2;
} else if (val < 0xe0) {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val & ((1LL<<(5+2*8))-1);
return 3;
} else if (val < 0xf0) {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val & ((1LL<<(4+3*8))-1);
return 4;
} else if (val < 0xf8) {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val & ((1LL<<(3+4*8))-1);
return 5;
} else if (val < 0xfc) {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val & ((1LL<<(2+5*8))-1);
return 6;
} else if (val < 0xfe) {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val & ((1LL<<(1+6*8))-1);
return 7;
} else if (val < 0xff) {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val & ((1LL<<(7*8))-1);
return 8;
} else {
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
val = (val<<8) | (unsigned char)hgetc(fd->fp);
*val_p = val;
}
return 9;
}
/*
* Pushes a value in ITF8 format onto the end of a block.
* This shouldn't be used for high-volume data as it is not the fastest
* method.
*
* Returns the number of bytes written
*/
int itf8_put_blk(cram_block *blk, int val) {
char buf[5];
int sz;
sz = itf8_put(buf, val);
BLOCK_APPEND(blk, buf, sz);
return sz;
}
/*
* Decodes a 32-bit little endian value from fd and stores in val.
*
* Returns the number of bytes read on success
* -1 on failure
*/
int int32_decode(cram_fd *fd, int32_t *val) {
int32_t i;
if (4 != hread(fd->fp, &i, 4))
return -1;
*val = le_int4(i);
return 4;
}
/*
* Encodes a 32-bit little endian value 'val' and writes to fd.
*
* Returns the number of bytes written on success
* -1 on failure
*/
int int32_encode(cram_fd *fd, int32_t val) {
val = le_int4(val);
if (4 != hwrite(fd->fp, &val, 4))
return -1;
return 4;
}
/* As int32_decoded/encode, but from/to blocks instead of cram_fd */
int int32_get(cram_block *b, int32_t *val) {
if (b->uncomp_size - BLOCK_SIZE(b) < 4)
return -1;
*val =
b->data[b->byte ] |
(b->data[b->byte+1] << 8) |
(b->data[b->byte+2] << 16) |
(b->data[b->byte+3] << 24);
BLOCK_SIZE(b) += 4;
return 4;
}
/* As int32_decoded/encode, but from/to blocks instead of cram_fd */
int int32_put(cram_block *b, int32_t val) {
unsigned char cp[4];
cp[0] = ( val & 0xff);
cp[1] = ((val>>8) & 0xff);
cp[2] = ((val>>16) & 0xff);
cp[3] = ((val>>24) & 0xff);
BLOCK_APPEND(b, cp, 4);
return b->data ? 0 : -1;
}
/* ----------------------------------------------------------------------
* zlib compression code - from Gap5's tg_iface_g.c
* They're static here as they're only used within the cram_compress_block
* and cram_uncompress_block functions, which are the external interface.
*/
char *zlib_mem_inflate(char *cdata, size_t csize, size_t *size) {
z_stream s;
unsigned char *data = NULL; /* Uncompressed output */
int data_alloc = 0;
int err;
/* Starting point at uncompressed size, and scale after that */
data = malloc(data_alloc = csize*1.2+100);
if (!data)
return NULL;
/* Initialise zlib stream */
s.zalloc = Z_NULL; /* use default allocation functions */
s.zfree = Z_NULL;
s.opaque = Z_NULL;
s.next_in = (unsigned char *)cdata;
s.avail_in = csize;
s.total_in = 0;
s.next_out = data;
s.avail_out = data_alloc;
s.total_out = 0;
//err = inflateInit(&s);
err = inflateInit2(&s, 15 + 32);
if (err != Z_OK) {
fprintf(stderr, "zlib inflateInit error: %s\n", s.msg);
free(data);
return NULL;
}
/* Decode to 'data' array */
for (;s.avail_in;) {
unsigned char *data_tmp;
int alloc_inc;
s.next_out = &data[s.total_out];
err = inflate(&s, Z_NO_FLUSH);
if (err == Z_STREAM_END)
break;
if (err != Z_OK) {
fprintf(stderr, "zlib inflate error: %s\n", s.msg);
break;
}
/* More to come, so realloc based on growth so far */
alloc_inc = (double)s.avail_in/s.total_in * s.total_out + 100;
data = realloc((data_tmp = data), data_alloc += alloc_inc);
if (!data) {
free(data_tmp);
return NULL;
}
s.avail_out += alloc_inc;
}
inflateEnd(&s);
*size = s.total_out;
return (char *)data;
}
static char *zlib_mem_deflate(char *data, size_t size, size_t *cdata_size,
int level, int strat) {
z_stream s;
unsigned char *cdata = NULL; /* Compressed output */
int cdata_alloc = 0;
int cdata_pos = 0;
int err;
cdata = malloc(cdata_alloc = size*1.05+100);
if (!cdata)
return NULL;
cdata_pos = 0;
/* Initialise zlib stream */
s.zalloc = Z_NULL; /* use default allocation functions */
s.zfree = Z_NULL;
s.opaque = Z_NULL;
s.next_in = (unsigned char *)data;
s.avail_in = size;
s.total_in = 0;
s.next_out = cdata;
s.avail_out = cdata_alloc;
s.total_out = 0;
s.data_type = Z_BINARY;
err = deflateInit2(&s, level, Z_DEFLATED, 15|16, 9, strat);
if (err != Z_OK) {
fprintf(stderr, "zlib deflateInit2 error: %s\n", s.msg);
return NULL;
}
/* Encode to 'cdata' array */
for (;s.avail_in;) {
s.next_out = &cdata[cdata_pos];
s.avail_out = cdata_alloc - cdata_pos;
if (cdata_alloc - cdata_pos <= 0) {
fprintf(stderr, "Deflate produced larger output than expected. Abort\n");
return NULL;
}
err = deflate(&s, Z_NO_FLUSH);
cdata_pos = cdata_alloc - s.avail_out;
if (err != Z_OK) {
fprintf(stderr, "zlib deflate error: %s\n", s.msg);
break;
}
}
if (deflate(&s, Z_FINISH) != Z_STREAM_END) {
fprintf(stderr, "zlib deflate error: %s\n", s.msg);
}
*cdata_size = s.total_out;
if (deflateEnd(&s) != Z_OK) {
fprintf(stderr, "zlib deflate error: %s\n", s.msg);
}
return (char *)cdata;
}
/* ----------------------------------------------------------------------
* CRAM blocks - the dynamically growable data block. We have code to
* create, update, (un)compress and read/write.
*
* These are derived from the deflate_interlaced.c blocks, but with the
* CRAM extension of content types and IDs.
*/
/*
* Allocates a new cram_block structure with a specified content_type and
* id.
*
* Returns block pointer on success
* NULL on failure
*/
cram_block *cram_new_block(enum cram_content_type content_type,
int content_id) {
cram_block *b = malloc(sizeof(*b));
if (!b)
return NULL;
b->method = b->orig_method = RAW;
b->content_type = content_type;
b->content_id = content_id;
b->comp_size = 0;
b->uncomp_size = 0;
b->data = NULL;
b->alloc = 0;
b->byte = 0;
b->bit = 7; // MSB
return b;
}
/*
* Reads a block from a cram file.
* Returns cram_block pointer on success.
* NULL on failure
*/
cram_block *cram_read_block(cram_fd *fd) {
cram_block *b = malloc(sizeof(*b));
if (!b)
return NULL;
//fprintf(stderr, "Block at %d\n", (int)ftell(fd->fp));
if (-1 == (b->method = hgetc(fd->fp))) { free(b); return NULL; }
if (-1 == (b->content_type= hgetc(fd->fp))) { free(b); return NULL; }
if (-1 == itf8_decode(fd, &b->content_id)) { free(b); return NULL; }
if (-1 == itf8_decode(fd, &b->comp_size)) { free(b); return NULL; }
if (-1 == itf8_decode(fd, &b->uncomp_size)) { free(b); return NULL; }
// fprintf(stderr, " method %d, ctype %d, cid %d, csize %d, ucsize %d\n",
// b->method, b->content_type, b->content_id, b->comp_size, b->uncomp_size);
if (b->method == RAW) {
b->alloc = b->uncomp_size;
if (!(b->data = malloc(b->uncomp_size))){ free(b); return NULL; }
if (b->uncomp_size != hread(fd->fp, b->data, b->uncomp_size)) {
free(b->data);
free(b);
return NULL;
}
} else {
b->alloc = b->comp_size;
if (!(b->data = malloc(b->comp_size))) { free(b); return NULL; }
if (b->comp_size != hread(fd->fp, b->data, b->comp_size)) {
free(b->data);
free(b);
return NULL;
}
}
b->orig_method = b->method;
b->idx = 0;
b->byte = 0;
b->bit = 7; // MSB
return b;
}
/*
* Writes a CRAM block.
* Returns 0 on success
* -1 on failure
*/
int cram_write_block(cram_fd *fd, cram_block *b) {
assert(b->method != RAW || (b->comp_size == b->uncomp_size));
if (hputc(b->method, fd->fp) == EOF) return -1;
if (hputc(b->content_type, fd->fp) == EOF) return -1;
if (itf8_encode(fd, b->content_id) == -1) return -1;
if (itf8_encode(fd, b->comp_size) == -1) return -1;
if (itf8_encode(fd, b->uncomp_size) == -1) return -1;
if (b->method == RAW) {
if (b->uncomp_size != hwrite(fd->fp, b->data, b->uncomp_size))
return -1;
} else {
if (b->comp_size != hwrite(fd->fp, b->data, b->comp_size))
return -1;
}
return 0;
}
/*
* Frees a CRAM block, deallocating internal data too.
*/
void cram_free_block(cram_block *b) {
if (!b)
return;
if (b->data)
free(b->data);
free(b);
}
/*
* Uncompresses a CRAM block, if compressed.
*/
int cram_uncompress_block(cram_block *b) {
char *uncomp;
size_t uncomp_size = 0;
if (b->uncomp_size == 0) {
// blank block
b->method = RAW;
return 0;
}
switch (b->method) {
case RAW:
b->uncomp_size = b->comp_size;
return 0;
case GZIP:
uncomp = zlib_mem_inflate((char *)b->data, b->comp_size, &uncomp_size);
if (!uncomp)
return -1;
if ((int)uncomp_size != b->uncomp_size)
return -1;
free(b->data);
b->data = (unsigned char *)uncomp;
b->alloc = uncomp_size;
b->method = RAW;
break;
#ifdef HAVE_LIBBZ2
case BZIP2: {
unsigned int usize = b->uncomp_size;
if (!(uncomp = malloc(usize)))
return -1;
if (BZ_OK != BZ2_bzBuffToBuffDecompress(uncomp, &usize,
(char *)b->data, b->comp_size,
0, 0)) {
free(uncomp);
return -1;
}
b->data = (unsigned char *)uncomp;
b->alloc = usize;
b->method = RAW;
b->uncomp_size = usize; // Just incase it differs
break;
}
#else
case BZIP2:
fprintf(stderr, "Bzip2 compression is not compiled into this "
"version.\nPlease rebuild and try again.\n");
return -1;
#endif
case BM_ERROR:
default:
return -1;
}
return 0;
}
#ifdef HAVE_LIBBZ2
static int cram_compress_block_bzip2(cram_fd *fd, cram_block *b,
cram_metrics *metrics, int level) {
unsigned int comp_size = b->uncomp_size*1.01 + 600;
char *comp = malloc(comp_size);
char *data = (char *)b->data;
if (!comp)
return -1;
if (!data)
data = "";
if (BZ_OK != BZ2_bzBuffToBuffCompress(comp, &comp_size,
data, b->uncomp_size,
level, 0, 30)) {
free(comp);
return -1;
}
free(b->data);
b->data = (unsigned char *)comp;
b->method = BZIP2;
b->comp_size = comp_size;
if (fd->verbose)
fprintf(stderr, "Compressed block ID %d from %d to %d\n",
b->content_id, b->uncomp_size, b->comp_size);
return 0;
}
#endif
/*
* Compresses a block using one of two different zlib strategies. If we only
* want one choice set strat2 to be -1.
*
* The logic here is that sometimes Z_RLE does a better job than Z_FILTERED
* or Z_DEFAULT_STRATEGY on quality data. If so, we'd rather use it as it is
* significantly faster.
*/
int cram_compress_block(cram_fd *fd, cram_block *b, cram_metrics *metrics,
int level, int strat,
int level2, int strat2) {
char *comp = NULL;
size_t comp_size = 0;
if (level == 0) {
b->method = RAW;
b->comp_size = b->uncomp_size;
return 0;
}
if (b->method != RAW) {
fprintf(stderr, "Attempt to compress an already compressed block.\n");
return 0;
}
#ifdef HAVE_LIBBZ2
if (fd->use_bz2)
// metrics ignored for bzip2
return cram_compress_block_bzip2(fd, b, metrics, level);
#endif
pthread_mutex_lock(&fd->metrics_lock);
if (strat2 >= 0)
if (fd->verbose > 1)
fprintf(stderr, "metrics trial %d, next_trial %d, m1 %d, m2 %d\n",
metrics->trial, metrics->next_trial,
metrics->m1, metrics->m2);
if (strat2 >= 0 && (metrics->trial > 0 || --metrics->next_trial <= 0)) {
char *c1, *c2;
size_t s1, s2;
if (metrics->next_trial == 0) {
metrics->next_trial = 100;
metrics->trial = 3;
metrics->m1 = metrics->m2 = 0;
}
pthread_mutex_unlock(&fd->metrics_lock);
c1 = zlib_mem_deflate((char *)b->data, b->uncomp_size,
&s1, level, strat);
c2 = zlib_mem_deflate((char *)b->data, b->uncomp_size,
&s2, level2, strat2);
if (!c1 || !c2)
return -1;
//fprintf(stderr, "1: %6d 2: %6d %5.1f\n", s1, s2, 100.0*s1/s2);
pthread_mutex_lock(&fd->metrics_lock);
if (s1 < 0.98 * s2) { // 2nd one should be faster alternative
if (fd->verbose > 1)
fprintf(stderr, "M1 wins %d vs %d\n", (int)s1, (int)s2);
comp = c1; comp_size = s1;
free(c2);
metrics->m1++;
} else {
if (fd->verbose > 1)
fprintf(stderr, "M2 wins %d vs %d\n", (int)s1, (int)s2);
comp = c2; comp_size = s2;
free(c1);
metrics->m2++;
}
metrics->trial--;
pthread_mutex_unlock(&fd->metrics_lock);
} else if (strat2 >= 0) {
int xlevel = metrics->m1 > metrics->m2 ? level : level2;
int xstrat = metrics->m1 > metrics->m2 ? strat : strat2;
pthread_mutex_unlock(&fd->metrics_lock);
comp = zlib_mem_deflate((char *)b->data, b->uncomp_size, &comp_size,
xlevel, xstrat);
} else {
pthread_mutex_unlock(&fd->metrics_lock);
comp = zlib_mem_deflate((char *)b->data, b->uncomp_size, &comp_size,
level, strat);
}
if (!comp)
return -1;
free(b->data);
b->data = (unsigned char *)comp;
b->method = GZIP;
b->comp_size = comp_size;
if (fd->verbose)
fprintf(stderr, "Compressed block ID %d from %d to %d\n",
b->content_id, b->uncomp_size, b->comp_size);
return 0;
}
cram_metrics *cram_new_metrics(void) {
cram_metrics *m = malloc(sizeof(*m));
if (!m)
return NULL;
m->m1 = m->m2 = 0;
m->trial = 2;
m->next_trial = 100;
return m;
}
char *cram_block_method2str(enum cram_block_method m) {
switch(m) {
case RAW: return "RAW";
case GZIP: return "GZIP";
case BZIP2: return "BZIP2";
case BM_ERROR: break;
}
return "?";
}
char *cram_content_type2str(enum cram_content_type t) {
switch (t) {
case FILE_HEADER: return "FILE_HEADER";
case COMPRESSION_HEADER: return "COMPRESSION_HEADER";
case MAPPED_SLICE: return "MAPPED_SLICE";
case UNMAPPED_SLICE: return "UNMAPPED_SLICE";
case EXTERNAL: return "EXTERNAL";
case CORE: return "CORE";
case CT_ERROR: break;
}
return "?";
}
/*
* Extra error checking on fclose to really ensure data is written.
* Care needs to be taken to handle pipes vs real files.
*
* Returns 0 on success
* -1 on failure.
*/
int paranoid_fclose(FILE *fp) {
if (-1 == fflush(fp) && errno != EBADF) {