1 /// @file htslib/cram.h
2 /// CRAM format-specific API functions.
3 /*
4     Copyright (C) 2015, 2016, 2018-2020 Genome Research Ltd.
5 
6     Author: James Bonfield <jkb@sanger.ac.uk>
7 
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14 
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17 
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE.  */
25 
26 /** @file
27  * Consider using the higher level hts_*() API for programs that wish to
28  * be file format agnostic (see htslib/hts.h).
29  *
30  * This API should be used for CRAM specific code. The specifics of the
31  * public API are implemented in cram_io.h, cram_encode.h and cram_decode.h
32  * although these should not be included directly (use this file instead).
33  */
34 
35 #ifndef HTSLIB_CRAM_H
36 #define HTSLIB_CRAM_H
37 
38 #include <stdarg.h>
39 #include <stdint.h>
40 #include <sys/types.h>
41 
42 #include "hts_defs.h"
43 #include "hts.h"
44 #include "sam.h"
45 
46 #ifdef __cplusplus
47 extern "C" {
48 #endif
49 
50 // see cram/cram_structs.h for an internal more complete copy of this enum
51 
52 // Htslib 1.11 had these listed without any hts prefix, and included
53 // some internal values such as RANS1 and GZIP_RLE (which shouldn't have ever
54 // been public).
55 //
56 // We can't find evidence of these being used and the data type occurs
57 // nowhere in functions or structures meaning using it would be pointless.
58 // However for safety, if you absolute need the API to not change then
59 // define HTS_COMPAT to 101100 (XYYYZZ for X.Y[.Z], meaning 1.11).
60 #if defined(HTS_COMPAT) && HTS_COMPAT <= 101100
61 enum cram_block_method {
62     // Public methods as defined in the CRAM spec.
63     BM_ERROR = -1,
64 
65     // CRAM 2.x and 3.0
66     RAW      = 0,
67     GZIP     = 1,
68     BZIP2    = 2,
69     LZMA     = 3,
70     RANS     = 4,
71 
72     // NB: the subsequent numbers may change.  They're simply here for
73     // compatibility with the old API, but may have no bearing on the
74     // internal way htslib works.  DO NOT USE
75     RANS0    = 4,
76     RANS1    = 10,
77     GZIP_RLE = 11,
78 };
79 #endif
80 
81 enum cram_content_type {
82     CT_ERROR           = -1,
83     FILE_HEADER        = 0,
84     COMPRESSION_HEADER = 1,
85     MAPPED_SLICE       = 2,
86     UNMAPPED_SLICE     = 3, // CRAM V1.0 only
87     EXTERNAL           = 4,
88     CORE               = 5,
89 };
90 
91 // Opaque data types, see cram_structs for the fully fledged versions.
92 typedef struct cram_file_def cram_file_def;
93 typedef struct cram_fd cram_fd;
94 typedef struct cram_container cram_container;
95 typedef struct cram_block cram_block;
96 typedef struct cram_slice cram_slice;
97 typedef struct cram_metrics cram_metrics;
98 typedef struct cram_block_slice_hdr cram_block_slice_hdr;
99 typedef struct cram_block_compression_hdr cram_block_compression_hdr;
100 typedef struct refs_t refs_t;
101 
102 struct hFILE;
103 
104 // Accessor functions
105 
106 /*
107  *-----------------------------------------------------------------------------
108  * cram_fd
109  */
110 HTSLIB_EXPORT
111 sam_hdr_t *cram_fd_get_header(cram_fd *fd);
112 
113 HTSLIB_EXPORT
114 void cram_fd_set_header(cram_fd *fd, sam_hdr_t *hdr);
115 
116 HTSLIB_EXPORT
117 int cram_fd_get_version(cram_fd *fd);
118 
119 HTSLIB_EXPORT
120 void cram_fd_set_version(cram_fd *fd, int vers);
121 
122 HTSLIB_EXPORT
123 int cram_major_vers(cram_fd *fd);
124 HTSLIB_EXPORT
125 int cram_minor_vers(cram_fd *fd);
126 
127 HTSLIB_EXPORT
128 struct hFILE *cram_fd_get_fp(cram_fd *fd);
129 HTSLIB_EXPORT
130 void cram_fd_set_fp(cram_fd *fd, struct hFILE *fp);
131 
132 
133 /*
134  *-----------------------------------------------------------------------------
135  * cram_container
136  */
137 HTSLIB_EXPORT
138 int32_t cram_container_get_length(cram_container *c);
139 HTSLIB_EXPORT
140 void cram_container_set_length(cram_container *c, int32_t length);
141 HTSLIB_EXPORT
142 int32_t cram_container_get_num_blocks(cram_container *c);
143 HTSLIB_EXPORT
144 void cram_container_set_num_blocks(cram_container *c, int32_t num_blocks);
145 HTSLIB_EXPORT
146 int32_t *cram_container_get_landmarks(cram_container *c, int32_t *num_landmarks);
147 HTSLIB_EXPORT
148 void cram_container_set_landmarks(cram_container *c, int32_t num_landmarks,
149                                   int32_t *landmarks);
150 
151 /* Returns true if the container is empty (EOF marker) */
152 HTSLIB_EXPORT
153 int cram_container_is_empty(cram_fd *fd);
154 
155 
156 /*
157  *-----------------------------------------------------------------------------
158  * cram_block
159  */
160 HTSLIB_EXPORT
161 int32_t cram_block_get_content_id(cram_block *b);
162 HTSLIB_EXPORT
163 int32_t cram_block_get_comp_size(cram_block *b);
164 HTSLIB_EXPORT
165 int32_t cram_block_get_uncomp_size(cram_block *b);
166 HTSLIB_EXPORT
167 int32_t cram_block_get_crc32(cram_block *b);
168 HTSLIB_EXPORT
169 void *  cram_block_get_data(cram_block *b);
170 
171 HTSLIB_EXPORT
172 enum cram_content_type cram_block_get_content_type(cram_block *b);
173 
174 HTSLIB_EXPORT
175 void cram_block_set_content_id(cram_block *b, int32_t id);
176 HTSLIB_EXPORT
177 void cram_block_set_comp_size(cram_block *b, int32_t size);
178 HTSLIB_EXPORT
179 void cram_block_set_uncomp_size(cram_block *b, int32_t size);
180 HTSLIB_EXPORT
181 void cram_block_set_crc32(cram_block *b, int32_t crc);
182 HTSLIB_EXPORT
183 void cram_block_set_data(cram_block *b, void *data);
184 
185 HTSLIB_EXPORT
186 int cram_block_append(cram_block *b, const void *data, int size);
187 HTSLIB_EXPORT
188 void cram_block_update_size(cram_block *b);
189 
190 // Offset is known as "size" internally, but it can be confusing.
191 HTSLIB_EXPORT
192 size_t cram_block_get_offset(cram_block *b);
193 HTSLIB_EXPORT
194 void cram_block_set_offset(cram_block *b, size_t offset);
195 
196 /*
197  * Computes the size of a cram block, including the block
198  * header itself.
199  */
200 HTSLIB_EXPORT
201 uint32_t cram_block_size(cram_block *b);
202 
203 /*
204  * Renumbers RG numbers in a cram compression header.
205  *
206  * CRAM stores RG as the Nth number in the header, rather than a
207  * string holding the ID: tag.  This is smaller in space, but means
208  * "samtools cat" to join files together that contain single but
209  * different RG lines needs a way of renumbering them.
210  *
211  * The file descriptor is expected to be immediately after the
212  * cram_container structure (ie before the cram compression header).
213  * Due to the nature of the CRAM format, this needs to read and write
214  * the blocks itself.  Note that there may be multiple slices within
215  * the container, meaning multiple compression headers to manipulate.
216  * Changing RG may change the size of the compression header and
217  * therefore the length field in the container.  Hence we rewrite all
218  * blocks just in case and also emit the adjusted container.
219  *
220  * The current implementation can only cope with renumbering a single
221  * RG (and only then if it is using HUFFMAN or BETA codecs).  In
222  * theory it *may* be possible to renumber multiple RGs if they use
223  * HUFFMAN to the CORE block or use an external block unshared by any
224  * other data series.  So we have an API that can be upgraded to
225  * support this, but do not implement it for now.  An example
226  * implementation of RG as an EXTERNAL block would be to find that
227  * block and rewrite it, returning the number of blocks consumed.
228  *
229  * Returns 0 on success;
230  *        -1 if unable to edit;
231  *        -2 on other errors (eg I/O).
232  */
233 HTSLIB_EXPORT
234 int cram_transcode_rg(cram_fd *in, cram_fd *out,
235                       cram_container *c,
236                       int nrg, int *in_rg, int *out_rg);
237 
238 /*
239  * Copies the blocks representing the next num_slice slices from a
240  * container from 'in' to 'out'.  It is expected that the file pointer
241  * is just after the read of the cram_container and cram compression
242  * header.
243  *
244  * Returns 0 on success
245  *        -1 on failure
246  */
247 HTSLIB_EXPORT
248 int cram_copy_slice(cram_fd *in, cram_fd *out, int32_t num_slice);
249 
250 /*
251  *-----------------------------------------------------------------------------
252  * cram_io basics
253  */
254 
255 /**@{ ----------------------------------------------------------------------
256  * CRAM blocks - the dynamically growable data block. We have code to
257  * create, update, (un)compress and read/write.
258  *
259  * These are derived from the deflate_interlaced.c blocks, but with the
260  * CRAM extension of content types and IDs.
261  */
262 
263 /*! Allocates a new cram_block structure with a specified content_type and
264  * id.
265  *
266  * @return
267  * Returns block pointer on success;
268  *         NULL on failure
269  *
270  * The cram_block struct returned by a successful call should be freed
271  * via cram_free_block() when it is no longer needed.
272  */
273 HTSLIB_EXPORT
274 cram_block *cram_new_block(enum cram_content_type content_type,
275                            int content_id);
276 
277 /*! Reads a block from a cram file.
278  *
279  * @return
280  * Returns cram_block pointer on success;
281  *         NULL on failure
282  *
283  * The cram_block struct returned by a successful call should be freed
284  * via cram_free_block() when it is no longer needed.
285  */
286 HTSLIB_EXPORT
287 cram_block *cram_read_block(cram_fd *fd);
288 
289 /*! Writes a CRAM block.
290  *
291  * @return
292  * Returns 0 on success;
293  *        -1 on failure
294  */
295 HTSLIB_EXPORT
296 int cram_write_block(cram_fd *fd, cram_block *b);
297 
298 /*! Frees a CRAM block, deallocating internal data too.
299  */
300 HTSLIB_EXPORT
301 void cram_free_block(cram_block *b);
302 
303 /*! Uncompresses a CRAM block, if compressed.
304  *
305  * @return
306  * Returns 0 on success;
307  *        -1 on failure
308  */
309 HTSLIB_EXPORT
310 int cram_uncompress_block(cram_block *b);
311 
312 /*! Compresses a block.
313  *
314  * Compresses a block using one of two different zlib strategies. If we only
315  * want one choice set strat2 to be -1.
316  *
317  * The logic here is that sometimes Z_RLE does a better job than Z_FILTERED
318  * or Z_DEFAULT_STRATEGY on quality data. If so, we'd rather use it as it is
319  * significantly faster.
320  *
321  * @return
322  * Returns 0 on success;
323  *        -1 on failure
324  */
325 HTSLIB_EXPORT
326 int cram_compress_block(cram_fd *fd, cram_block *b, cram_metrics *metrics,
327                         int method, int level);
328 int cram_compress_block2(cram_fd *fd, cram_slice *s,
329                          cram_block *b, cram_metrics *metrics,
330                          int method, int level);
331 
332 /**@}*/
333 /**@{ ----------------------------------------------------------------------
334  * Containers
335  */
336 
337 /*! Creates a new container, specifying the maximum number of slices
338  * and records permitted.
339  *
340  * @return
341  * Returns cram_container ptr on success;
342  *         NULL on failure
343  *
344  * The cram_container struct returned by a successful call should be freed
345  * via cram_free_container() when it is no longer needed.
346  */
347 HTSLIB_EXPORT
348 cram_container *cram_new_container(int nrec, int nslice);
349 HTSLIB_EXPORT
350 void cram_free_container(cram_container *c);
351 
352 /*! Reads a container header.
353  *
354  * @return
355  * Returns cram_container on success;
356  *         NULL on failure or no container left (fd->err == 0).
357  *
358  * The cram_container struct returned by a successful call should be freed
359  * via cram_free_container() when it is no longer needed.
360  */
361 HTSLIB_EXPORT
362 cram_container *cram_read_container(cram_fd *fd);
363 
364 /*! Writes a container structure.
365  *
366  * @return
367  * Returns 0 on success;
368  *        -1 on failure
369  */
370 HTSLIB_EXPORT
371 int cram_write_container(cram_fd *fd, cram_container *h);
372 
373 /*
374  * Stores the container structure in dat and returns *size as the
375  * number of bytes written to dat[].  The input size of dat is also
376  * held in *size and should be initialised to cram_container_size(c).
377  *
378  * Returns 0 on success;
379  *        -1 on failure
380  */
381 HTSLIB_EXPORT
382 int cram_store_container(cram_fd *fd, cram_container *c, char *dat, int *size);
383 
384 HTSLIB_EXPORT
385 int cram_container_size(cram_container *c);
386 
387 /**@}*/
388 /**@{ ----------------------------------------------------------------------
389  * The top-level cram opening, closing and option handling
390  */
391 
392 /*! Opens a CRAM file for read (mode "rb") or write ("wb").
393  *
394  * The filename may be "-" to indicate stdin or stdout.
395  *
396  * @return
397  * Returns file handle on success;
398  *         NULL on failure.
399  */
400 HTSLIB_EXPORT
401 cram_fd *cram_open(const char *filename, const char *mode);
402 
403 /*! Opens an existing stream for reading or writing.
404  *
405  * @return
406  * Returns file handle on success;
407  *         NULL on failure.
408  */
409 HTSLIB_EXPORT
410 cram_fd *cram_dopen(struct hFILE *fp, const char *filename, const char *mode);
411 
412 /*! Closes a CRAM file.
413  *
414  * @return
415  * Returns 0 on success;
416  *        -1 on failure
417  */
418 HTSLIB_EXPORT
419 int cram_close(cram_fd *fd);
420 
421 /*
422  * Seek within a CRAM file.
423  *
424  * Returns 0 on success
425  *        -1 on failure
426  */
427 HTSLIB_EXPORT
428 int cram_seek(cram_fd *fd, off_t offset, int whence);
429 
430 /*
431  * Flushes a CRAM file.
432  * Useful for when writing to stdout without wishing to close the stream.
433  *
434  * Returns 0 on success
435  *        -1 on failure
436  */
437 HTSLIB_EXPORT
438 int cram_flush(cram_fd *fd);
439 
440 /*! Checks for end of file on a cram_fd stream.
441  *
442  * @return
443  * Returns 0 if not at end of file
444  *         1 if we hit an expected EOF (end of range or EOF block)
445  *         2 for other EOF (end of stream without EOF block)
446  */
447 HTSLIB_EXPORT
448 int cram_eof(cram_fd *fd);
449 
450 /*! Sets options on the cram_fd.
451  *
452  * See CRAM_OPT_* definitions in hts.h.
453  * Use this immediately after opening.
454  *
455  * @return
456  * Returns 0 on success;
457  *        -1 on failure
458  */
459 HTSLIB_EXPORT
460 int cram_set_option(cram_fd *fd, enum hts_fmt_option opt, ...);
461 
462 /*! Sets options on the cram_fd.
463  *
464  * See CRAM_OPT_* definitions in hts.h.
465  * Use this immediately after opening.
466  *
467  * @return
468  * Returns 0 on success;
469  *        -1 on failure
470  */
471 HTSLIB_EXPORT
472 int cram_set_voption(cram_fd *fd, enum hts_fmt_option opt, va_list args);
473 
474 /*!
475  * Attaches a header to a cram_fd.
476  *
477  * This should be used when creating a new cram_fd for writing where
478  * we have an SAM_hdr already constructed (eg from a file we've read
479  * in).
480  *
481  * @return
482  * Returns 0 on success;
483  *        -1 on failure
484  */
485 HTSLIB_EXPORT
486 int cram_set_header(cram_fd *fd, sam_hdr_t *hdr);
487 
488 /*! Check if this file has a proper EOF block
489  *
490  * @return
491  * Returns 3 if the file is a version of CRAM that does not contain EOF blocks
492  *         2 if the file is a stream and thus unseekable
493  *         1 if the file contains an EOF block
494  *         0 if the file does not contain an EOF block
495  *        -1 if an error occurred whilst reading the file or we could not seek back to where we were
496  *
497  */
498 HTSLIB_EXPORT
499 int cram_check_EOF(cram_fd *fd);
500 
501 /* As int32_decoded/encode, but from/to blocks instead of cram_fd */
502 HTSLIB_EXPORT
503 int int32_put_blk(cram_block *b, int32_t val);
504 
505 /**@}*/
506 /**@{ -------------------------------------------------------------------
507  * Old typedef and function names for compatibility with existing code.
508  * Header functionality is now provided by sam.h's sam_hdr_t functions.
509  */
510 
511 typedef sam_hdr_t SAM_hdr;
512 
513 /*! Tokenises a SAM header into a hash table.
514  *
515  * Also extracts a few bits on specific data types, such as @RG lines.
516  *
517  * @return
518  * Returns a SAM_hdr struct on success (free with sam_hdr_free());
519  *         NULL on failure
520  */
sam_hdr_parse_(const char * hdr,size_t len)521 static inline SAM_hdr *sam_hdr_parse_(const char *hdr, size_t len) { return sam_hdr_parse(len, hdr); }
522 
523 /*! Deallocates all storage used by a SAM_hdr struct.
524  *
525  * This also decrements the header reference count. If after decrementing
526  * it is still non-zero then the header is assumed to be in use by another
527  * caller and the free is not done.
528  */
sam_hdr_free(SAM_hdr * hdr)529 static inline void sam_hdr_free(SAM_hdr *hdr) { sam_hdr_destroy(hdr); }
530 
531 /* sam_hdr_length() and sam_hdr_str() are now provided by sam.h. */
532 
533 /*! Add an @PG line.
534  *
535  * If we wish complete control over this use sam_hdr_add_line() directly. This
536  * function uses that, but attempts to do a lot of tedious house work for
537  * you too.
538  *
539  * - It will generate a suitable ID if the supplied one clashes.
540  * - It will generate multiple @PG records if we have multiple PG chains.
541  *
542  * Call it as per sam_hdr_add_line() with a series of key,value pairs ending
543  * in NULL.
544  *
545  * @return
546  * Returns 0 on success;
547  *        -1 on failure
548  */
549 #define sam_hdr_add_PG sam_hdr_add_pg
550 
551 /**@{ -------------------------------------------------------------------*/
552 
553 /*!
554  * Returns the refs_t structure used by a cram file handle.
555  *
556  * This may be used in conjunction with option CRAM_OPT_SHARED_REF to
557  * share reference memory between multiple file handles.
558  *
559  * @return
560  * Returns NULL if none exists or the file handle is not a CRAM file.
561  */
562 HTSLIB_EXPORT
563 refs_t *cram_get_refs(htsFile *fd);
564 
565 /**@}*/
566 
567 #ifdef __cplusplus
568 }
569 #endif
570 
571 #endif
572