bgzf.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. /* The MIT License
  2. Copyright (c) 2008 Broad Institute / Massachusetts Institute of Technology
  3. 2011 Attractive Chaos <attractor@live.co.uk>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. #include "config.h"
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <errno.h>
  25. #include <unistd.h>
  26. #include <assert.h>
  27. #include <pthread.h>
  28. #include <sys/types.h>
  29. #include <inttypes.h>
  30. #include "htslib/hts.h"
  31. #include "htslib/bgzf.h"
  32. #include "htslib/hfile.h"
  33. #define BLOCK_HEADER_LENGTH 18
  34. #define BLOCK_FOOTER_LENGTH 8
  35. /* BGZF/GZIP header (speciallized from RFC 1952; little endian):
  36. +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  37. | 31|139| 8| 4| 0| 0|255| 6| 66| 67| 2|BLK_LEN|
  38. +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  39. BGZF extension:
  40. ^ ^ ^ ^
  41. | | | |
  42. FLG.EXTRA XLEN B C
  43. BGZF format is compatible with GZIP. It limits the size of each compressed
  44. block to 2^16 bytes and adds and an extra "BC" field in the gzip header which
  45. records the size.
  46. */
  47. static const uint8_t g_magic[19] = "\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\0\0";
  48. #ifdef BGZF_CACHE
  49. typedef struct {
  50. int size;
  51. uint8_t *block;
  52. int64_t end_offset;
  53. } cache_t;
  54. #include "htslib/khash.h"
  55. KHASH_MAP_INIT_INT64(cache, cache_t)
  56. #endif
  57. typedef struct
  58. {
  59. uint64_t uaddr; // offset w.r.t. uncompressed data
  60. uint64_t caddr; // offset w.r.t. compressed data
  61. }
  62. bgzidx1_t;
  63. struct __bgzidx_t
  64. {
  65. int noffs, moffs; // the size of the index, n:used, m:allocated
  66. bgzidx1_t *offs; // offsets
  67. uint64_t ublock_addr; // offset of the current block (uncompressed data)
  68. };
  69. void bgzf_index_destroy(BGZF *fp);
  70. int bgzf_index_add_block(BGZF *fp);
  71. static inline void packInt16(uint8_t *buffer, uint16_t value)
  72. {
  73. buffer[0] = value;
  74. buffer[1] = value >> 8;
  75. }
  76. static inline int unpackInt16(const uint8_t *buffer)
  77. {
  78. return buffer[0] | buffer[1] << 8;
  79. }
  80. static inline void packInt32(uint8_t *buffer, uint32_t value)
  81. {
  82. buffer[0] = value;
  83. buffer[1] = value >> 8;
  84. buffer[2] = value >> 16;
  85. buffer[3] = value >> 24;
  86. }
  87. static BGZF *bgzf_read_init(hFILE *hfpr)
  88. {
  89. BGZF *fp;
  90. uint8_t magic[2];
  91. ssize_t n = hpeek(hfpr, magic, 2);
  92. if (n < 0) return NULL;
  93. fp = (BGZF*)calloc(1, sizeof(BGZF));
  94. if (fp == NULL) return NULL;
  95. fp->is_write = 0;
  96. fp->is_compressed = (n==2 && magic[0]==0x1f && magic[1]==0x8b);
  97. fp->uncompressed_block = malloc(BGZF_MAX_BLOCK_SIZE);
  98. fp->compressed_block = malloc(BGZF_MAX_BLOCK_SIZE);
  99. #ifdef BGZF_CACHE
  100. fp->cache = kh_init(cache);
  101. #endif
  102. return fp;
  103. }
  104. static BGZF *bgzf_write_init(int compress_level) // compress_level==-1 for the default level, -2 plain uncompressed
  105. {
  106. BGZF *fp;
  107. fp = (BGZF*)calloc(1, sizeof(BGZF));
  108. fp->is_write = 1;
  109. if ( compress_level==-2 )
  110. {
  111. fp->is_compressed = 0;
  112. return fp;
  113. }
  114. fp->is_compressed = 1;
  115. fp->uncompressed_block = malloc(BGZF_MAX_BLOCK_SIZE);
  116. fp->compressed_block = malloc(BGZF_MAX_BLOCK_SIZE);
  117. fp->compress_level = compress_level < 0? Z_DEFAULT_COMPRESSION : compress_level; // Z_DEFAULT_COMPRESSION==-1
  118. if (fp->compress_level > 9) fp->compress_level = Z_DEFAULT_COMPRESSION;
  119. return fp;
  120. }
  121. // get the compress level from the mode string
  122. static int mode2level(const char *__restrict mode)
  123. {
  124. int i, compress_level = -1;
  125. for (i = 0; mode[i]; ++i)
  126. if (mode[i] >= '0' && mode[i] <= '9') break;
  127. if (mode[i]) compress_level = (int)mode[i] - '0';
  128. if (strchr(mode, 'u')) compress_level = -2;
  129. return compress_level;
  130. }
  131. BGZF *bgzf_open(const char *path, const char *mode)
  132. {
  133. BGZF *fp = 0;
  134. assert(compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE);
  135. if (strchr(mode, 'r')) {
  136. hFILE *fpr;
  137. if ((fpr = hopen(path, mode)) == 0) return 0;
  138. fp = bgzf_read_init(fpr);
  139. if (fp == 0) { hclose_abruptly(fpr); return NULL; }
  140. fp->fp = fpr;
  141. } else if (strchr(mode, 'w') || strchr(mode, 'a')) {
  142. hFILE *fpw;
  143. if ((fpw = hopen(path, mode)) == 0) return 0;
  144. fp = bgzf_write_init(mode2level(mode));
  145. fp->fp = fpw;
  146. }
  147. else { errno = EINVAL; return 0; }
  148. fp->is_be = ed_is_big();
  149. return fp;
  150. }
  151. BGZF *bgzf_dopen(int fd, const char *mode)
  152. {
  153. BGZF *fp = 0;
  154. assert(compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE);
  155. if (strchr(mode, 'r')) {
  156. hFILE *fpr;
  157. if ((fpr = hdopen(fd, mode)) == 0) return 0;
  158. fp = bgzf_read_init(fpr);
  159. if (fp == 0) { hclose_abruptly(fpr); return NULL; } // FIXME this closes fd
  160. fp->fp = fpr;
  161. } else if (strchr(mode, 'w') || strchr(mode, 'a')) {
  162. hFILE *fpw;
  163. if ((fpw = hdopen(fd, mode)) == 0) return 0;
  164. fp = bgzf_write_init(mode2level(mode));
  165. fp->fp = fpw;
  166. }
  167. else { errno = EINVAL; return 0; }
  168. fp->is_be = ed_is_big();
  169. return fp;
  170. }
  171. BGZF *bgzf_hopen(hFILE *hfp, const char *mode)
  172. {
  173. BGZF *fp = NULL;
  174. assert(compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE);
  175. if (strchr(mode, 'r')) {
  176. fp = bgzf_read_init(hfp);
  177. if (fp == NULL) return NULL;
  178. } else if (strchr(mode, 'w') || strchr(mode, 'a')) {
  179. fp = bgzf_write_init(mode2level(mode));
  180. }
  181. else { errno = EINVAL; return 0; }
  182. fp->fp = hfp;
  183. fp->is_be = ed_is_big();
  184. return fp;
  185. }
  186. static int bgzf_compress(void *_dst, int *dlen, void *src, int slen, int level)
  187. {
  188. uint32_t crc;
  189. z_stream zs;
  190. uint8_t *dst = (uint8_t*)_dst;
  191. // compress the body
  192. zs.zalloc = NULL; zs.zfree = NULL;
  193. zs.next_in = (Bytef*)src;
  194. zs.avail_in = slen;
  195. zs.next_out = dst + BLOCK_HEADER_LENGTH;
  196. zs.avail_out = *dlen - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH;
  197. if (deflateInit2(&zs, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) return -1; // -15 to disable zlib header/footer
  198. if (deflate(&zs, Z_FINISH) != Z_STREAM_END) return -1;
  199. if (deflateEnd(&zs) != Z_OK) return -1;
  200. *dlen = zs.total_out + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
  201. // write the header
  202. memcpy(dst, g_magic, BLOCK_HEADER_LENGTH); // the last two bytes are a place holder for the length of the block
  203. packInt16(&dst[16], *dlen - 1); // write the compressed length; -1 to fit 2 bytes
  204. // write the footer
  205. crc = crc32(crc32(0L, NULL, 0L), (Bytef*)src, slen);
  206. packInt32((uint8_t*)&dst[*dlen - 8], crc);
  207. packInt32((uint8_t*)&dst[*dlen - 4], slen);
  208. return 0;
  209. }
  210. // Deflate the block in fp->uncompressed_block into fp->compressed_block. Also adds an extra field that stores the compressed block length.
  211. static int deflate_block(BGZF *fp, int block_length)
  212. {
  213. int comp_size = BGZF_MAX_BLOCK_SIZE;
  214. if (bgzf_compress(fp->compressed_block, &comp_size, fp->uncompressed_block, block_length, fp->compress_level) != 0) {
  215. fp->errcode |= BGZF_ERR_ZLIB;
  216. return -1;
  217. }
  218. fp->block_offset = 0;
  219. return comp_size;
  220. }
  221. // Inflate the block in fp->compressed_block into fp->uncompressed_block
  222. static int inflate_block(BGZF* fp, int block_length)
  223. {
  224. z_stream zs;
  225. zs.zalloc = NULL;
  226. zs.zfree = NULL;
  227. zs.next_in = (Bytef*)fp->compressed_block + 18;
  228. zs.avail_in = block_length - 16;
  229. zs.next_out = (Bytef*)fp->uncompressed_block;
  230. zs.avail_out = BGZF_MAX_BLOCK_SIZE;
  231. if (inflateInit2(&zs, -15) != Z_OK) {
  232. fp->errcode |= BGZF_ERR_ZLIB;
  233. return -1;
  234. }
  235. if (inflate(&zs, Z_FINISH) != Z_STREAM_END) {
  236. inflateEnd(&zs);
  237. fp->errcode |= BGZF_ERR_ZLIB;
  238. return -1;
  239. }
  240. if (inflateEnd(&zs) != Z_OK) {
  241. fp->errcode |= BGZF_ERR_ZLIB;
  242. return -1;
  243. }
  244. return zs.total_out;
  245. }
  246. static int inflate_gzip_block(BGZF *fp, int cached)
  247. {
  248. int ret = Z_OK;
  249. do
  250. {
  251. if ( !cached && fp->gz_stream->avail_out!=0 )
  252. {
  253. fp->gz_stream->avail_in = hread(fp->fp, fp->compressed_block, BGZF_BLOCK_SIZE);
  254. if ( fp->gz_stream->avail_in<=0 ) return fp->gz_stream->avail_in;
  255. if ( fp->gz_stream->avail_in==0 ) break;
  256. fp->gz_stream->next_in = fp->compressed_block;
  257. }
  258. else cached = 0;
  259. do
  260. {
  261. fp->gz_stream->next_out = (Bytef*)fp->uncompressed_block + fp->block_offset;
  262. fp->gz_stream->avail_out = BGZF_MAX_BLOCK_SIZE - fp->block_offset;
  263. ret = inflate(fp->gz_stream, Z_NO_FLUSH);
  264. if ( ret==Z_BUF_ERROR ) continue; // non-critical error
  265. if ( ret<0 ) return -1;
  266. unsigned int have = BGZF_MAX_BLOCK_SIZE - fp->gz_stream->avail_out;
  267. if ( have ) return have;
  268. }
  269. while ( fp->gz_stream->avail_out == 0 );
  270. }
  271. while (ret != Z_STREAM_END);
  272. return BGZF_MAX_BLOCK_SIZE - fp->gz_stream->avail_out;
  273. }
  274. // Returns: 0 on success (BGZF header); -1 on non-BGZF GZIP header; -2 on error
  275. static int check_header(const uint8_t *header)
  276. {
  277. if ( header[0] != 31 || header[1] != 139 || header[2] != 8 ) return -2;
  278. return ((header[3] & 4) != 0
  279. && unpackInt16((uint8_t*)&header[10]) == 6
  280. && header[12] == 'B' && header[13] == 'C'
  281. && unpackInt16((uint8_t*)&header[14]) == 2) ? 0 : -1;
  282. }
  283. #ifdef BGZF_CACHE
  284. static void free_cache(BGZF *fp)
  285. {
  286. khint_t k;
  287. khash_t(cache) *h = (khash_t(cache)*)fp->cache;
  288. if (fp->is_write) return;
  289. for (k = kh_begin(h); k < kh_end(h); ++k)
  290. if (kh_exist(h, k)) free(kh_val(h, k).block);
  291. kh_destroy(cache, h);
  292. }
  293. static int load_block_from_cache(BGZF *fp, int64_t block_address)
  294. {
  295. khint_t k;
  296. cache_t *p;
  297. khash_t(cache) *h = (khash_t(cache)*)fp->cache;
  298. k = kh_get(cache, h, block_address);
  299. if (k == kh_end(h)) return 0;
  300. p = &kh_val(h, k);
  301. if (fp->block_length != 0) fp->block_offset = 0;
  302. fp->block_address = block_address;
  303. fp->block_length = p->size;
  304. memcpy(fp->uncompressed_block, p->block, BGZF_MAX_BLOCK_SIZE);
  305. if ( hseek(fp->fp, p->end_offset, SEEK_SET) < 0 )
  306. {
  307. // todo: move the error up
  308. fprintf(stderr,"Could not hseek to %"PRId64"\n", p->end_offset);
  309. exit(1);
  310. }
  311. return p->size;
  312. }
  313. static void cache_block(BGZF *fp, int size)
  314. {
  315. int ret;
  316. khint_t k;
  317. cache_t *p;
  318. khash_t(cache) *h = (khash_t(cache)*)fp->cache;
  319. if (BGZF_MAX_BLOCK_SIZE >= fp->cache_size) return;
  320. if ((kh_size(h) + 1) * BGZF_MAX_BLOCK_SIZE > (uint32_t)fp->cache_size) {
  321. /* A better way would be to remove the oldest block in the
  322. * cache, but here we remove a random one for simplicity. This
  323. * should not have a big impact on performance. */
  324. for (k = kh_begin(h); k < kh_end(h); ++k)
  325. if (kh_exist(h, k)) break;
  326. if (k < kh_end(h)) {
  327. free(kh_val(h, k).block);
  328. kh_del(cache, h, k);
  329. }
  330. }
  331. k = kh_put(cache, h, fp->block_address, &ret);
  332. if (ret == 0) return; // if this happens, a bug!
  333. p = &kh_val(h, k);
  334. p->size = fp->block_length;
  335. p->end_offset = fp->block_address + size;
  336. p->block = (uint8_t*)malloc(BGZF_MAX_BLOCK_SIZE);
  337. memcpy(kh_val(h, k).block, fp->uncompressed_block, BGZF_MAX_BLOCK_SIZE);
  338. }
  339. #else
  340. static void free_cache(BGZF *fp) {}
  341. static int load_block_from_cache(BGZF *fp, int64_t block_address) {return 0;}
  342. static void cache_block(BGZF *fp, int size) {}
  343. #endif
  344. int bgzf_read_block(BGZF *fp)
  345. {
  346. uint8_t header[BLOCK_HEADER_LENGTH], *compressed_block;
  347. int count, size = 0, block_length, remaining;
  348. // Reading an uncompressed file
  349. if ( !fp->is_compressed )
  350. {
  351. count = hread(fp->fp, fp->uncompressed_block, BGZF_MAX_BLOCK_SIZE);
  352. if ( count==0 )
  353. {
  354. fp->block_length = 0;
  355. return 0;
  356. }
  357. if (fp->block_length != 0) fp->block_offset = 0;
  358. fp->block_address += count;
  359. fp->block_length = count;
  360. return 0;
  361. }
  362. // Reading compressed file
  363. int64_t block_address;
  364. block_address = htell(fp->fp);
  365. if ( fp->is_gzip )
  366. {
  367. count = inflate_gzip_block(fp, 0);
  368. if ( count<0 )
  369. {
  370. fp->errcode |= BGZF_ERR_ZLIB;
  371. return -1;
  372. }
  373. fp->block_length = count;
  374. fp->block_address = block_address;
  375. return 0;
  376. }
  377. if (fp->cache_size && load_block_from_cache(fp, block_address)) return 0;
  378. count = hread(fp->fp, header, sizeof(header));
  379. if (count == 0) { // no data read
  380. fp->block_length = 0;
  381. return 0;
  382. }
  383. int ret;
  384. if ( count != sizeof(header) || (ret=check_header(header))==-2 )
  385. {
  386. fp->errcode |= BGZF_ERR_HEADER;
  387. return -1;
  388. }
  389. if ( ret==-1 )
  390. {
  391. // GZIP, not BGZF
  392. uint8_t *cblock = (uint8_t*)fp->compressed_block;
  393. memcpy(cblock, header, sizeof(header));
  394. count = hread(fp->fp, cblock+sizeof(header), BGZF_BLOCK_SIZE - sizeof(header)) + sizeof(header);
  395. int nskip = 10;
  396. // Check optional fields to skip: FLG.FNAME,FLG.FCOMMENT,FLG.FHCRC,FLG.FEXTRA
  397. // Note: Some of these fields are untested, I did not have appropriate data available
  398. if ( header[3] & 0x4 ) // FLG.FEXTRA
  399. {
  400. nskip += unpackInt16(&cblock[nskip]) + 2;
  401. }
  402. if ( header[3] & 0x8 ) // FLG.FNAME
  403. {
  404. while ( nskip<BGZF_BLOCK_SIZE && cblock[nskip] ) nskip++;
  405. if ( nskip==BGZF_BLOCK_SIZE )
  406. {
  407. fp->errcode |= BGZF_ERR_HEADER;
  408. return -1;
  409. }
  410. nskip++;
  411. }
  412. if ( header[3] & 0x10 ) // FLG.FCOMMENT
  413. {
  414. while ( nskip<BGZF_BLOCK_SIZE && cblock[nskip] ) nskip++;
  415. if ( nskip==BGZF_BLOCK_SIZE )
  416. {
  417. fp->errcode |= BGZF_ERR_HEADER;
  418. return -1;
  419. }
  420. nskip++;
  421. }
  422. if ( header[3] & 0x2 ) nskip += 2; // FLG.FHCRC
  423. fp->is_gzip = 1;
  424. fp->gz_stream = (z_stream*) calloc(1,sizeof(z_stream));
  425. int ret = inflateInit2(fp->gz_stream, -15);
  426. if (ret != Z_OK)
  427. {
  428. fp->errcode |= BGZF_ERR_ZLIB;
  429. return -1;
  430. }
  431. fp->gz_stream->avail_in = count - nskip;
  432. fp->gz_stream->next_in = cblock + nskip;
  433. count = inflate_gzip_block(fp, 1);
  434. if ( count<0 )
  435. {
  436. fp->errcode |= BGZF_ERR_ZLIB;
  437. return -1;
  438. }
  439. fp->block_length = count;
  440. fp->block_address = block_address;
  441. return 0;
  442. }
  443. size = count;
  444. block_length = unpackInt16((uint8_t*)&header[16]) + 1; // +1 because when writing this number, we used "-1"
  445. compressed_block = (uint8_t*)fp->compressed_block;
  446. memcpy(compressed_block, header, BLOCK_HEADER_LENGTH);
  447. remaining = block_length - BLOCK_HEADER_LENGTH;
  448. count = hread(fp->fp, &compressed_block[BLOCK_HEADER_LENGTH], remaining);
  449. if (count != remaining) {
  450. fp->errcode |= BGZF_ERR_IO;
  451. return -1;
  452. }
  453. size += count;
  454. if ((count = inflate_block(fp, block_length)) < 0) return -1;
  455. if (fp->block_length != 0) fp->block_offset = 0; // Do not reset offset if this read follows a seek.
  456. fp->block_address = block_address;
  457. fp->block_length = count;
  458. if ( fp->idx_build_otf )
  459. {
  460. bgzf_index_add_block(fp);
  461. fp->idx->ublock_addr += count;
  462. }
  463. cache_block(fp, size);
  464. return 0;
  465. }
  466. ssize_t bgzf_read(BGZF *fp, void *data, size_t length)
  467. {
  468. ssize_t bytes_read = 0;
  469. uint8_t *output = (uint8_t*)data;
  470. if (length <= 0) return 0;
  471. assert(fp->is_write == 0);
  472. while (bytes_read < length) {
  473. int copy_length, available = fp->block_length - fp->block_offset;
  474. uint8_t *buffer;
  475. if (available <= 0) {
  476. if (bgzf_read_block(fp) != 0) return -1;
  477. available = fp->block_length - fp->block_offset;
  478. if (available <= 0) break;
  479. }
  480. copy_length = length - bytes_read < available? length - bytes_read : available;
  481. buffer = (uint8_t*)fp->uncompressed_block;
  482. memcpy(output, buffer + fp->block_offset, copy_length);
  483. fp->block_offset += copy_length;
  484. output += copy_length;
  485. bytes_read += copy_length;
  486. }
  487. if (fp->block_offset == fp->block_length) {
  488. fp->block_address = htell(fp->fp);
  489. fp->block_offset = fp->block_length = 0;
  490. }
  491. fp->uncompressed_address += bytes_read;
  492. return bytes_read;
  493. }
  494. ssize_t bgzf_raw_read(BGZF *fp, void *data, size_t length)
  495. {
  496. return hread(fp->fp, data, length);
  497. }
  498. #ifdef BGZF_MT
  499. typedef struct {
  500. struct bgzf_mtaux_t *mt;
  501. void *buf;
  502. int i, errcode, toproc, compress_level;
  503. } worker_t;
  504. typedef struct bgzf_mtaux_t {
  505. int n_threads, n_blks, curr, done;
  506. volatile int proc_cnt;
  507. void **blk;
  508. int *len;
  509. worker_t *w;
  510. pthread_t *tid;
  511. pthread_mutex_t lock;
  512. pthread_cond_t cv;
  513. } mtaux_t;
  514. static int worker_aux(worker_t *w)
  515. {
  516. int i, stop = 0;
  517. // wait for condition: to process or all done
  518. pthread_mutex_lock(&w->mt->lock);
  519. while (!w->toproc && !w->mt->done)
  520. pthread_cond_wait(&w->mt->cv, &w->mt->lock);
  521. if (w->mt->done) stop = 1;
  522. w->toproc = 0;
  523. pthread_mutex_unlock(&w->mt->lock);
  524. if (stop) return 1; // to quit the thread
  525. w->errcode = 0;
  526. for (i = w->i; i < w->mt->curr; i += w->mt->n_threads) {
  527. int clen = BGZF_MAX_BLOCK_SIZE;
  528. if (bgzf_compress(w->buf, &clen, w->mt->blk[i], w->mt->len[i], w->compress_level) != 0)
  529. w->errcode |= BGZF_ERR_ZLIB;
  530. memcpy(w->mt->blk[i], w->buf, clen);
  531. w->mt->len[i] = clen;
  532. }
  533. __sync_fetch_and_add(&w->mt->proc_cnt, 1);
  534. return 0;
  535. }
  536. static void *mt_worker(void *data)
  537. {
  538. while (worker_aux((worker_t*)data) == 0);
  539. return 0;
  540. }
  541. int bgzf_mt(BGZF *fp, int n_threads, int n_sub_blks)
  542. {
  543. int i;
  544. mtaux_t *mt;
  545. pthread_attr_t attr;
  546. if (!fp->is_write || fp->mt || n_threads <= 1) return -1;
  547. mt = (mtaux_t*)calloc(1, sizeof(mtaux_t));
  548. mt->n_threads = n_threads;
  549. mt->n_blks = n_threads * n_sub_blks;
  550. mt->len = (int*)calloc(mt->n_blks, sizeof(int));
  551. mt->blk = (void**)calloc(mt->n_blks, sizeof(void*));
  552. for (i = 0; i < mt->n_blks; ++i)
  553. mt->blk[i] = malloc(BGZF_MAX_BLOCK_SIZE);
  554. mt->tid = (pthread_t*)calloc(mt->n_threads, sizeof(pthread_t)); // tid[0] is not used, as the worker 0 is launched by the master
  555. mt->w = (worker_t*)calloc(mt->n_threads, sizeof(worker_t));
  556. for (i = 0; i < mt->n_threads; ++i) {
  557. mt->w[i].i = i;
  558. mt->w[i].mt = mt;
  559. mt->w[i].compress_level = fp->compress_level;
  560. mt->w[i].buf = malloc(BGZF_MAX_BLOCK_SIZE);
  561. }
  562. pthread_attr_init(&attr);
  563. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  564. pthread_mutex_init(&mt->lock, 0);
  565. pthread_cond_init(&mt->cv, 0);
  566. for (i = 1; i < mt->n_threads; ++i) // worker 0 is effectively launched by the master thread
  567. pthread_create(&mt->tid[i], &attr, mt_worker, &mt->w[i]);
  568. fp->mt = mt;
  569. return 0;
  570. }
  571. static void mt_destroy(mtaux_t *mt)
  572. {
  573. int i;
  574. // signal all workers to quit
  575. pthread_mutex_lock(&mt->lock);
  576. mt->done = 1; mt->proc_cnt = 0;
  577. pthread_cond_broadcast(&mt->cv);
  578. pthread_mutex_unlock(&mt->lock);
  579. for (i = 1; i < mt->n_threads; ++i) pthread_join(mt->tid[i], 0); // worker 0 is effectively launched by the master thread
  580. // free other data allocated on heap
  581. for (i = 0; i < mt->n_blks; ++i) free(mt->blk[i]);
  582. for (i = 0; i < mt->n_threads; ++i) free(mt->w[i].buf);
  583. free(mt->blk); free(mt->len); free(mt->w); free(mt->tid);
  584. pthread_cond_destroy(&mt->cv);
  585. pthread_mutex_destroy(&mt->lock);
  586. free(mt);
  587. }
  588. static void mt_queue(BGZF *fp)
  589. {
  590. mtaux_t *mt = fp->mt;
  591. assert(mt->curr < mt->n_blks); // guaranteed by the caller
  592. memcpy(mt->blk[mt->curr], fp->uncompressed_block, fp->block_offset);
  593. mt->len[mt->curr] = fp->block_offset;
  594. fp->block_offset = 0;
  595. ++mt->curr;
  596. }
  597. static int mt_flush_queue(BGZF *fp)
  598. {
  599. int i;
  600. mtaux_t *mt = fp->mt;
  601. // signal all the workers to compress
  602. pthread_mutex_lock(&mt->lock);
  603. for (i = 0; i < mt->n_threads; ++i) mt->w[i].toproc = 1;
  604. mt->proc_cnt = 0;
  605. pthread_cond_broadcast(&mt->cv);
  606. pthread_mutex_unlock(&mt->lock);
  607. // worker 0 is doing things here
  608. worker_aux(&mt->w[0]);
  609. // wait for all the threads to complete
  610. while (mt->proc_cnt < mt->n_threads);
  611. // dump data to disk
  612. for (i = 0; i < mt->n_threads; ++i) fp->errcode |= mt->w[i].errcode;
  613. for (i = 0; i < mt->curr; ++i)
  614. if (hwrite(fp->fp, mt->blk[i], mt->len[i]) != mt->len[i]) {
  615. fp->errcode |= BGZF_ERR_IO;
  616. break;
  617. }
  618. mt->curr = 0;
  619. return (fp->errcode == 0)? 0 : -1;
  620. }
  621. static int lazy_flush(BGZF *fp)
  622. {
  623. if (fp->mt) {
  624. if (fp->block_offset) mt_queue(fp);
  625. return (fp->mt->curr < fp->mt->n_blks)? 0 : mt_flush_queue(fp);
  626. }
  627. else return bgzf_flush(fp);
  628. }
  629. #else // ~ #ifdef BGZF_MT
  630. int bgzf_mt(BGZF *fp, int n_threads, int n_sub_blks)
  631. {
  632. return 0;
  633. }
  634. static inline int lazy_flush(BGZF *fp)
  635. {
  636. return bgzf_flush(fp);
  637. }
  638. #endif // ~ #ifdef BGZF_MT
  639. int bgzf_flush(BGZF *fp)
  640. {
  641. if (!fp->is_write) return 0;
  642. #ifdef BGZF_MT
  643. if (fp->mt) {
  644. if (fp->block_offset) mt_queue(fp); // guaranteed that assertion does not fail
  645. return mt_flush_queue(fp);
  646. }
  647. #endif
  648. while (fp->block_offset > 0) {
  649. if ( fp->idx_build_otf )
  650. {
  651. bgzf_index_add_block(fp);
  652. fp->idx->ublock_addr += fp->block_offset;
  653. }
  654. int block_length = deflate_block(fp, fp->block_offset);
  655. if (block_length < 0) return -1;
  656. if (hwrite(fp->fp, fp->compressed_block, block_length) != block_length) {
  657. fp->errcode |= BGZF_ERR_IO; // possibly truncated file
  658. return -1;
  659. }
  660. fp->block_address += block_length;
  661. }
  662. return 0;
  663. }
  664. int bgzf_flush_try(BGZF *fp, ssize_t size)
  665. {
  666. if (fp->block_offset + size > BGZF_BLOCK_SIZE) return lazy_flush(fp);
  667. return 0;
  668. }
  669. ssize_t bgzf_write(BGZF *fp, const void *data, size_t length)
  670. {
  671. if ( !fp->is_compressed )
  672. return hwrite(fp->fp, data, length);
  673. const uint8_t *input = (const uint8_t*)data;
  674. ssize_t remaining = length;
  675. assert(fp->is_write);
  676. while (remaining > 0) {
  677. uint8_t* buffer = (uint8_t*)fp->uncompressed_block;
  678. int copy_length = BGZF_BLOCK_SIZE - fp->block_offset;
  679. if (copy_length > remaining) copy_length = remaining;
  680. memcpy(buffer + fp->block_offset, input, copy_length);
  681. fp->block_offset += copy_length;
  682. input += copy_length;
  683. remaining -= copy_length;
  684. if (fp->block_offset == BGZF_BLOCK_SIZE) {
  685. if (lazy_flush(fp) != 0) return -1;
  686. }
  687. }
  688. return length - remaining;
  689. }
  690. ssize_t bgzf_raw_write(BGZF *fp, const void *data, size_t length)
  691. {
  692. return hwrite(fp->fp, data, length);
  693. }
  694. int bgzf_close(BGZF* fp)
  695. {
  696. int ret, block_length;
  697. if (fp == 0) return -1;
  698. if (fp->is_write && fp->is_compressed) {
  699. if (bgzf_flush(fp) != 0) return -1;
  700. fp->compress_level = -1;
  701. block_length = deflate_block(fp, 0); // write an empty block
  702. if (hwrite(fp->fp, fp->compressed_block, block_length) < 0
  703. || hflush(fp->fp) != 0) {
  704. fp->errcode |= BGZF_ERR_IO;
  705. return -1;
  706. }
  707. #ifdef BGZF_MT
  708. if (fp->mt) mt_destroy(fp->mt);
  709. #endif
  710. }
  711. if ( fp->is_gzip )
  712. {
  713. (void)inflateEnd(fp->gz_stream);
  714. free(fp->gz_stream);
  715. }
  716. ret = hclose(fp->fp);
  717. if (ret != 0) return -1;
  718. bgzf_index_destroy(fp);
  719. free(fp->uncompressed_block);
  720. free(fp->compressed_block);
  721. free_cache(fp);
  722. free(fp);
  723. return 0;
  724. }
  725. void bgzf_set_cache_size(BGZF *fp, int cache_size)
  726. {
  727. if (fp) fp->cache_size = cache_size;
  728. }
  729. int bgzf_check_EOF(BGZF *fp)
  730. {
  731. uint8_t buf[28];
  732. off_t offset = htell(fp->fp);
  733. if (hseek(fp->fp, -28, SEEK_END) < 0) {
  734. if (errno == ESPIPE) { hclearerr(fp->fp); return 2; }
  735. else return -1;
  736. }
  737. if ( hread(fp->fp, buf, 28) != 28 ) return -1;
  738. if ( hseek(fp->fp, offset, SEEK_SET) < 0 ) return -1;
  739. return (memcmp("\037\213\010\4\0\0\0\0\0\377\6\0\102\103\2\0\033\0\3\0\0\0\0\0\0\0\0\0", buf, 28) == 0)? 1 : 0;
  740. }
  741. int64_t bgzf_seek(BGZF* fp, int64_t pos, int where)
  742. {
  743. int block_offset;
  744. int64_t block_address;
  745. if (fp->is_write || where != SEEK_SET) {
  746. fp->errcode |= BGZF_ERR_MISUSE;
  747. return -1;
  748. }
  749. block_offset = pos & 0xFFFF;
  750. block_address = pos >> 16;
  751. if (hseek(fp->fp, block_address, SEEK_SET) < 0) {
  752. fp->errcode |= BGZF_ERR_IO;
  753. return -1;
  754. }
  755. fp->block_length = 0; // indicates current block has not been loaded
  756. fp->block_address = block_address << 16;
  757. fp->block_offset = block_offset;
  758. return 0;
  759. }
  760. int bgzf_is_bgzf(const char *fn)
  761. {
  762. uint8_t buf[16];
  763. int n;
  764. hFILE *fp;
  765. if ((fp = hopen(fn, "r")) == 0) return 0;
  766. n = hread(fp, buf, 16);
  767. if ( hclose(fp) < 0 ) return -1;
  768. if (n != 16) return 0;
  769. return memcmp(g_magic, buf, 16) == 0? 1 : 0;
  770. }
  771. int bgzf_getc(BGZF *fp)
  772. {
  773. int c;
  774. if (fp->block_offset >= fp->block_length) {
  775. if (bgzf_read_block(fp) != 0) return -2; /* error */
  776. if (fp->block_length == 0) return -1; /* end-of-file */
  777. }
  778. c = ((unsigned char*)fp->uncompressed_block)[fp->block_offset++];
  779. if (fp->block_offset == fp->block_length) {
  780. fp->block_address = htell(fp->fp);
  781. fp->block_offset = 0;
  782. fp->block_length = 0;
  783. }
  784. fp->uncompressed_address++;
  785. return c;
  786. }
  787. #ifndef kroundup32
  788. #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))
  789. #endif
  790. int bgzf_getline(BGZF *fp, int delim, kstring_t *str)
  791. {
  792. int l, state = 0;
  793. unsigned char *buf = (unsigned char*)fp->uncompressed_block;
  794. str->l = 0;
  795. do {
  796. if (fp->block_offset >= fp->block_length) {
  797. if (bgzf_read_block(fp) != 0) { state = -2; break; }
  798. if (fp->block_length == 0) { state = -1; break; }
  799. }
  800. for (l = fp->block_offset; l < fp->block_length && buf[l] != delim; ++l);
  801. if (l < fp->block_length) state = 1;
  802. l -= fp->block_offset;
  803. if (str->l + l + 1 >= str->m) {
  804. str->m = str->l + l + 2;
  805. kroundup32(str->m);
  806. str->s = (char*)realloc(str->s, str->m);
  807. }
  808. memcpy(str->s + str->l, buf + fp->block_offset, l);
  809. str->l += l;
  810. fp->block_offset += l + 1;
  811. if (fp->block_offset >= fp->block_length) {
  812. fp->block_address = htell(fp->fp);
  813. fp->block_offset = 0;
  814. fp->block_length = 0;
  815. }
  816. } while (state == 0);
  817. if (str->l == 0 && state < 0) return state;
  818. fp->uncompressed_address += str->l;
  819. str->s[str->l] = 0;
  820. return str->l;
  821. }
  822. void bgzf_index_destroy(BGZF *fp)
  823. {
  824. if ( !fp->idx ) return;
  825. free(fp->idx->offs);
  826. free(fp->idx);
  827. fp->idx = NULL;
  828. fp->idx_build_otf = 0;
  829. }
  830. int bgzf_index_build_init(BGZF *fp)
  831. {
  832. bgzf_index_destroy(fp);
  833. fp->idx = (bgzidx_t*) calloc(1,sizeof(bgzidx_t));
  834. if ( !fp->idx ) return -1;
  835. fp->idx_build_otf = 1; // build index on the fly
  836. return 0;
  837. }
  838. int bgzf_index_add_block(BGZF *fp)
  839. {
  840. fp->idx->noffs++;
  841. if ( fp->idx->noffs > fp->idx->moffs )
  842. {
  843. fp->idx->moffs = fp->idx->noffs;
  844. kroundup32(fp->idx->moffs);
  845. fp->idx->offs = (bgzidx1_t*) realloc(fp->idx->offs, fp->idx->moffs*sizeof(bgzidx1_t));
  846. if ( !fp->idx->offs ) return -1;
  847. }
  848. fp->idx->offs[ fp->idx->noffs-1 ].uaddr = fp->idx->ublock_addr;
  849. fp->idx->offs[ fp->idx->noffs-1 ].caddr = fp->block_address;
  850. return 0;
  851. }
  852. int bgzf_index_dump(BGZF *fp, const char *bname, const char *suffix)
  853. {
  854. if (bgzf_flush(fp) != 0) return -1;
  855. assert(fp->idx);
  856. char *tmp = NULL;
  857. if ( suffix )
  858. {
  859. int blen = strlen(bname);
  860. int slen = strlen(suffix);
  861. tmp = (char*) malloc(blen + slen + 1);
  862. if ( !tmp ) return -1;
  863. memcpy(tmp,bname,blen);
  864. memcpy(tmp+blen,suffix,slen+1);
  865. }
  866. FILE *idx = fopen(tmp?tmp:bname,"wb");
  867. if ( tmp ) free(tmp);
  868. if ( !idx ) return -1;
  869. // Note that the index contains one extra record when indexing files opened
  870. // for reading. The terminating record is not present when opened for writing.
  871. // This is not a bug.
  872. int i;
  873. if ( fp->is_be )
  874. {
  875. uint64_t x = fp->idx->noffs - 1;
  876. fwrite(ed_swap_8p(&x), 1, sizeof(x), idx);
  877. for (i=1; i<fp->idx->noffs; i++)
  878. {
  879. x = fp->idx->offs[i].caddr; fwrite(ed_swap_8p(&x), 1, sizeof(x), idx);
  880. x = fp->idx->offs[i].uaddr; fwrite(ed_swap_8p(&x), 1, sizeof(x), idx);
  881. }
  882. }
  883. else
  884. {
  885. uint64_t x = fp->idx->noffs - 1;
  886. fwrite(&x, 1, sizeof(x), idx);
  887. for (i=1; i<fp->idx->noffs; i++)
  888. {
  889. fwrite(&fp->idx->offs[i].caddr, 1, sizeof(fp->idx->offs[i].caddr), idx);
  890. fwrite(&fp->idx->offs[i].uaddr, 1, sizeof(fp->idx->offs[i].uaddr), idx);
  891. }
  892. }
  893. fclose(idx);
  894. return 0;
  895. }
  896. int bgzf_index_load(BGZF *fp, const char *bname, const char *suffix)
  897. {
  898. char *tmp = NULL;
  899. if ( suffix )
  900. {
  901. int blen = strlen(bname);
  902. int slen = strlen(suffix);
  903. tmp = (char*) malloc(blen + slen + 1);
  904. if ( !tmp ) return -1;
  905. memcpy(tmp,bname,blen);
  906. memcpy(tmp+blen,suffix,slen+1);
  907. }
  908. FILE *idx = fopen(tmp?tmp:bname,"rb");
  909. if ( tmp ) free(tmp);
  910. if ( !idx ) return -1;
  911. fp->idx = (bgzidx_t*) calloc(1,sizeof(bgzidx_t));
  912. uint64_t x;
  913. if ( fread(&x, 1, sizeof(x), idx) != sizeof(x) ) return -1;
  914. fp->idx->noffs = fp->idx->moffs = 1 + (fp->is_be ? ed_swap_8(x) : x);
  915. fp->idx->offs = (bgzidx1_t*) malloc(fp->idx->moffs*sizeof(bgzidx1_t));
  916. fp->idx->offs[0].caddr = fp->idx->offs[0].uaddr = 0;
  917. int i;
  918. if ( fp->is_be )
  919. {
  920. int ret = 0;
  921. for (i=1; i<fp->idx->noffs; i++)
  922. {
  923. ret += fread(&x, 1, sizeof(x), idx); fp->idx->offs[i].caddr = ed_swap_8(x);
  924. ret += fread(&x, 1, sizeof(x), idx); fp->idx->offs[i].uaddr = ed_swap_8(x);
  925. }
  926. if ( ret != sizeof(x)*2*(fp->idx->noffs-1) ) return -1;
  927. }
  928. else
  929. {
  930. int ret = 0;
  931. for (i=1; i<fp->idx->noffs; i++)
  932. {
  933. ret += fread(&x, 1, sizeof(x), idx); fp->idx->offs[i].caddr = x;
  934. ret += fread(&x, 1, sizeof(x), idx); fp->idx->offs[i].uaddr = x;
  935. }
  936. if ( ret != sizeof(x)*2*(fp->idx->noffs-1) ) return -1;
  937. }
  938. fclose(idx);
  939. return 0;
  940. }
  941. int bgzf_useek(BGZF *fp, long uoffset, int where)
  942. {
  943. if ( !fp->is_compressed )
  944. {
  945. if (hseek(fp->fp, uoffset, SEEK_SET) < 0)
  946. {
  947. fp->errcode |= BGZF_ERR_IO;
  948. return -1;
  949. }
  950. fp->block_length = 0; // indicates current block has not been loaded
  951. fp->block_address = uoffset;
  952. fp->block_offset = 0;
  953. bgzf_read_block(fp);
  954. fp->uncompressed_address = uoffset;
  955. return 0;
  956. }
  957. if ( !fp->idx )
  958. {
  959. fp->errcode |= BGZF_ERR_IO;
  960. return -1;
  961. }
  962. // binary search
  963. int ilo = 0, ihi = fp->idx->noffs - 1;
  964. while ( ilo<=ihi )
  965. {
  966. int i = (ilo+ihi)*0.5;
  967. if ( uoffset < fp->idx->offs[i].uaddr ) ihi = i - 1;
  968. else if ( uoffset >= fp->idx->offs[i].uaddr ) ilo = i + 1;
  969. else break;
  970. }
  971. int i = ilo-1;
  972. if (hseek(fp->fp, fp->idx->offs[i].caddr, SEEK_SET) < 0)
  973. {
  974. fp->errcode |= BGZF_ERR_IO;
  975. return -1;
  976. }
  977. fp->block_length = 0; // indicates current block has not been loaded
  978. fp->block_address = fp->idx->offs[i].caddr;
  979. fp->block_offset = 0;
  980. if ( bgzf_read_block(fp) < 0 ) return -1;
  981. if ( uoffset - fp->idx->offs[i].uaddr > 0 )
  982. {
  983. fp->block_offset = uoffset - fp->idx->offs[i].uaddr;
  984. assert( fp->block_offset <= fp->block_length ); // todo: skipped, unindexed, blocks
  985. }
  986. fp->uncompressed_address = uoffset;
  987. return 0;
  988. }
  989. long bgzf_utell(BGZF *fp)
  990. {
  991. return fp->uncompressed_address; // currently maintained only when reading
  992. }