Debian Codegraph @

samtools/bam_reheader.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_reheader.c -- reheader subcommand.
4
5 Copyright (C) 2010 Broad Institute.
6 Copyright (C) 2012-2019 Genome Research Ltd.
7
8 Author: Heng Li <[email protected]>
9
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
16
17 The above copyright notice and this permission notice shall be included in
18 all copies or substantial portions of the Software.
19
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26 DEALINGS IN THE SOFTWARE. */
27
28 #include <config.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <assert.h>
33 #include <getopt.h>
34 #include <unistd.h>
35
36 #include "htslib/bgzf.h"
37 #include "htslib/sam.h"
38 #include "htslib/hfile.h"
39 #include "htslib/cram.h"
40 #include "samtools.h"
41
42 #define BUF_SIZE 0x10000
43
44 /*
45 * Reads a file and outputs a new BAM file to fd with 'h' replaced as
46 * the header. No checks are made to the validity.
47 */
48 int bam_reheader(BGZF *in, sam_hdr_t *h, int fd,
49 const char *arg_list, int no_pg, int skip_header)
50 {
51 BGZF *fp = NULL;
52 ssize_t len;
53 uint8_t *buf = NULL;
54 sam_hdr_t *tmp;
55 if (!h)
56 return -1;
57
58 if (in->is_write) return -1;
59 buf = malloc(BUF_SIZE);
60 if (!buf) {
61 fprintf(samtools_stderr, "Out of memory\n");
62 return -1;
63 }
64
65 if (!skip_header) {
66 if ((tmp = bam_hdr_read(in)) == NULL) {
67 fprintf(samtools_stderr, "Couldn't read header\n");
68 goto fail;
69 }
70 sam_hdr_destroy(tmp);
71 }
72
73 fp = bgzf_fdopen(fd, "w");
74 if (!fp) {
75 print_error_errno("reheader", "Couldn't open output file");
76 goto fail;
77 }
78
79 if (!no_pg && sam_hdr_add_pg(h, "samtools",
80 "VN", samtools_version(),
81 arg_list ? "CL": NULL,
82 arg_list ? arg_list : NULL,
83 NULL) != 0)
84 goto fail;
85
86 if (bam_hdr_write(fp, h) < 0) {
87 print_error_errno("reheader", "Couldn't write header");
88 goto fail;
89 }
90 if (in->block_offset < in->block_length) {
91 if (bgzf_write(fp, (char *)in->uncompressed_block + in->block_offset, in->block_length - in->block_offset) < 0) goto write_fail;
92 if (bgzf_flush(fp) < 0) goto write_fail;
93 }
94 while ((len = bgzf_raw_read(in, buf, BUF_SIZE)) > 0) {
95 if (bgzf_raw_write(fp, buf, len) < 0) goto write_fail;
96 }
97 if (len < 0) {
98 fprintf(samtools_stderr, "[%s] Error reading input file\n", __func__);
99 goto fail;
100 }
101 free(buf);
102 fp->block_offset = in->block_offset = 0;
103 if (bgzf_close(fp) < 0) {
104 fprintf(samtools_stderr, "[%s] Error closing output file\n", __func__);
105 return -1;
106 }
107 return 0;
108
109 write_fail:
110 print_error_errno("reheader", "Error writing to output file");
111 fail:
112 bgzf_close(fp);
113 free(buf);
114 return -1;
115 }
116
117 /*
118 * Reads a file and outputs a new CRAM file to samtools_stdout with 'h'
119 * replaced as the header. No checks are made to the validity.
120 *
121 * FIXME: error checking
122 */
123 int cram_reheader(cram_fd *in, sam_hdr_t *h, const char *arg_list, int no_pg)
124 {
125 htsFile *h_out = hts_open("-", "wc");
126 cram_fd *out = h_out->fp.cram;
127 cram_container *c = NULL;
128 int ret = -1;
129 if (!h)
130 return ret;
131
132 // Match output version number with input file.
133 char vers[99];
134 sprintf(vers, "%d.%d", cram_major_vers(in), cram_minor_vers(in));
135 cram_set_option(out, CRAM_OPT_VERSION, vers);
136
137 // Attempt to fill out a cram->refs[] array from @SQ headers
138 sam_hdr_t *cram_h = sam_hdr_dup(h);
139 if (!cram_h)
140 return -1;
141 cram_fd_set_header(out, cram_h);
142 if (!no_pg && sam_hdr_add_pg(cram_fd_get_header(out), "samtools",
143 "VN", samtools_version(),
144 arg_list ? "CL": NULL,
145 arg_list ? arg_list : NULL,
146 NULL))
147 goto err;
148
149 if (sam_hdr_write(h_out, cram_h) != 0)
150 goto err;
151 cram_set_option(out, CRAM_OPT_REFERENCE, NULL);
152
153 while ((c = cram_read_container(in))) {
154 int32_t i, num_blocks = cram_container_get_num_blocks(c);
155 if (cram_write_container(out, c) != 0)
156 goto err;
157
158 for (i = 0; i < num_blocks; i++) {
159 cram_block *blk = cram_read_block(in);
160 if (!blk || cram_write_block(out, blk) != 0) {
161 if (blk) cram_free_block(blk);
162 goto err;
163 }
164 cram_free_block(blk);
165 }
166 cram_free_container(c);
167 }
168
169 ret = 0;
170
171 err:
172 if (hts_close(h_out) != 0)
173 ret = -1;
174
175 return ret;
176 }
177
178
179
180 /*
181 * Reads a version 2 CRAM file and replaces the header in-place,
182 * provided the header is small enough to fit without growing the
183 * entire file.
184 *
185 * Version 2 format has an uncompressed SAM header with multiple nul
186 * termination bytes to permit inline header editing.
187 *
188 * Returns 0 on success;
189 * -1 on general failure;
190 * -2 on failure due to insufficient size
191 */
192 int cram_reheader_inplace2(cram_fd *fd, sam_hdr_t *h, const char *arg_list,
193 int no_pg)
194 {
195 cram_container *c = NULL;
196 cram_block *b = NULL;
197 sam_hdr_t *cram_h = NULL;
198 off_t start;
199 int ret = -1;
200 if (!h)
201 goto err;
202
203 if (cram_major_vers(fd) < 2 ||
204 cram_major_vers(fd) > 3) {
205 fprintf(samtools_stderr, "[%s] unsupported CRAM version %d\n", __func__,
206 cram_major_vers(fd));
207 goto err;
208 }
209
210 cram_h = sam_hdr_dup(h);
211 if (!cram_h)
212 goto err;
213
214 if (!no_pg && sam_hdr_add_pg(cram_h, "samtools", "VN", samtools_version(),
215 arg_list ? "CL": NULL,
216 arg_list ? arg_list : NULL,
217 NULL))
218 goto err;
219
220 int header_len = sam_hdr_length(cram_h);
221 /* Fix M5 strings? Maybe out of scope for this tool */
222
223 // Load the existing header
224 if ((start = hseek(cram_fd_get_fp(fd), 26, SEEK_SET)) != 26)
225 goto err;
226
227 if (!(c = cram_read_container(fd)))
228 goto err;
229
230 // Version 2.1 has a single uncompressed block which is nul
231 // terminated with many nuls to permit growth.
232 //
233 // So load old block and keep all contents identical bar the
234 // header text itself
235 if (!(b = cram_read_block(fd)))
236 goto err;
237
238 if (cram_block_get_uncomp_size(b) < header_len+4) {
239 fprintf(samtools_stderr, "New header will not fit. Use non-inplace version (%d > %d)\n",
240 header_len+4, cram_block_get_uncomp_size(b));
241 ret = -2;
242 goto err;
243 }
244
245 cram_block_set_offset(b, 0); // rewind block
246 int32_put_blk(b, header_len);
247 cram_block_append(b, (void *)sam_hdr_str(cram_h), header_len);
248 // Zero the remaining block
249 memset((char *)cram_block_get_data(b)+cram_block_get_offset(b), 0,
250 cram_block_get_uncomp_size(b) - cram_block_get_offset(b));
251 // Make sure all sizes and byte-offsets are consistent after memset
252 cram_block_set_offset(b, cram_block_get_uncomp_size(b));
253 cram_block_set_comp_size(b, cram_block_get_uncomp_size(b));
254
255 if (hseek(cram_fd_get_fp(fd), start, SEEK_SET) != start)
256 goto err;
257
258 if (cram_write_container(fd, c) == -1)
259 goto err;
260
261 if (cram_write_block(fd, b) == -1)
262 goto err;
263
264 ret = 0;
265 err:
266 if (c) cram_free_container(c);
267 if (b) cram_free_block(b);
268 if (cram_h) sam_hdr_destroy(cram_h);
269
270 return ret;
271 }
272
273
274 /*
275 * Reads a version 3 CRAM file and replaces the header in-place,
276 * provided the header is small enough to fit without growing the
277 * entire file.
278 *
279 * Version 3 format has a SAM header held as an (optionally)
280 * compressed block within the header container. Additional
281 * uncompressed blocks or simply unallocated space (the difference
282 * between total block sizes and the container size) are used to
283 * provide room for growth or contraction of the compressed header.
284 *
285 * Returns 0 on success;
286 * -1 on general failure;
287 * -2 on failure due to insufficient size
288 */
289 int cram_reheader_inplace3(cram_fd *fd, sam_hdr_t *h, const char *arg_list,
290 int no_pg)
291 {
292 cram_container *c = NULL;
293 cram_block *b = NULL;
294 sam_hdr_t *cram_h = NULL;
295 off_t start, sz, end;
296 int container_sz, max_container_sz;
297 char *buf = NULL;
298 int ret = -1;
299 if (!h)
300 goto err;
301
302 if (cram_major_vers(fd) < 2 ||
303 cram_major_vers(fd) > 3) {
304 fprintf(samtools_stderr, "[%s] unsupported CRAM version %d\n", __func__,
305 cram_major_vers(fd));
306 goto err;
307 }
308
309 cram_h = sam_hdr_dup(h);
310 if (!cram_h)
311 goto err;
312
313 if (!no_pg && sam_hdr_add_pg(cram_h, "samtools", "VN", samtools_version(),
314 arg_list ? "CL": NULL,
315 arg_list ? arg_list : NULL,
316 NULL))
317 goto err;
318
319 int header_len = sam_hdr_length(cram_h);
320 /* Fix M5 strings? Maybe out of scope for this tool */
321
322 // Find current size of SAM header block
323 if ((start = hseek(cram_fd_get_fp(fd), 26, SEEK_SET)) != 26)
324 goto err;
325
326 if (!(c = cram_read_container(fd)))
327 goto err;
328
329 // +5 allows num_landmarks to increase from 0 to 1 (Cramtools)
330 max_container_sz = cram_container_size(c)+5;
331
332 sz = htell(cram_fd_get_fp(fd)) + cram_container_get_length(c) - start;
333 end = htell(cram_fd_get_fp(fd)) + cram_container_get_length(c);
334
335 // We force 1 block instead of (optionally) 2. C CRAM
336 // implementations for v3 were writing 1 compressed block followed
337 // by 1 uncompressed block. However this is tricky to deal with
338 // as changing block sizes can mean the block header also changes
339 // size due to itf8 and variable size integers.
340 //
341 // If we had 1 block, this doesn't change anything.
342 // If we had 2 blocks, the new container header will be smaller by
343 // 1+ bytes, requiring the cram_container_get_length(c) to be larger in value.
344 // However this is an int32 instead of itf8 so the container
345 // header structure stays the same size. This means we can always
346 // reduce the number of blocks without running into size problems.
347 cram_container_set_num_blocks(c, 1);
348 int32_t *landmark;
349 int32_t num_landmarks;
350 landmark = cram_container_get_landmarks(c, &num_landmarks);
351 if (num_landmarks && landmark) {
352 num_landmarks = 1;
353 landmark[0] = 0;
354 } else {
355 num_landmarks = 0;
356 }
357 cram_container_set_landmarks(c, num_landmarks, landmark);
358
359 buf = malloc(max_container_sz);
360 container_sz = max_container_sz;
361 if (cram_store_container(fd, c, buf, &container_sz) != 0)
362 goto err;
363
364 if (!buf)
365 goto err;
366
367 // Proposed new length, but changing cram_container_get_length(c) may change the
368 // container_sz and thus the remainder (cram_container_get_length(c) itself).
369 cram_container_set_length(c, sz - container_sz);
370
371 int old_container_sz = container_sz;
372 container_sz = max_container_sz;
373 if (cram_store_container(fd, c, buf, &container_sz) != 0)
374 goto err;
375
376 if (old_container_sz != container_sz) {
377 fprintf(samtools_stderr, "Quirk of fate makes this troublesome! "
378 "Please use non-inplace version.\n");
379 goto err;
380 }
381
382
383
384 // Version 3.0 supports compressed header
385 b = cram_new_block(FILE_HEADER, 0);
386 int32_put_blk(b, header_len);
387 cram_block_append(b, (void *)sam_hdr_str(cram_h), header_len);
388 cram_block_update_size(b);
389
390 cram_compress_block(fd, b, NULL, -1, 9);
391
392 if (hseek(cram_fd_get_fp(fd), 26, SEEK_SET) != 26)
393 goto err;
394
395 if (cram_block_size(b) > cram_container_get_length(c)) {
396 fprintf(samtools_stderr, "New header will not fit. Use non-inplace version"
397 " (%d > %d)\n",
398 (int)cram_block_size(b), cram_container_get_length(c));
399 ret = -2;
400 goto err;
401 }
402
403 if (cram_write_container(fd, c) == -1)
404 goto err;
405
406 if (cram_write_block(fd, b) == -1)
407 goto err;
408
409 // Blank out the remainder
410 int rsz = end - htell(cram_fd_get_fp(fd));
411 assert(rsz >= 0);
412 if (rsz) {
413 char *rem = calloc(1, rsz);
414 ret = hwrite(cram_fd_get_fp(fd), rem, rsz) == rsz ? 0 : -1;
415 free(rem);
416 }
417
418 err:
419 if (c) cram_free_container(c);
420 if (buf) free(buf);
421 if (b) cram_free_block(b);
422 if (cram_h) sam_hdr_destroy(cram_h);
423
424 return ret;
425 }
426
427 int cram_reheader_inplace(cram_fd *fd, sam_hdr_t *h, const char *arg_list,
428 int no_pg)
429 {
430 switch (cram_major_vers(fd)) {
431 case 2: return cram_reheader_inplace2(fd, h, arg_list, no_pg);
432 case 3: return cram_reheader_inplace3(fd, h, arg_list, no_pg);
433 default:
434 fprintf(samtools_stderr, "[%s] unsupported CRAM version %d\n", __func__,
435 cram_major_vers(fd));
436 return -1;
437 }
438 }
439
440 static void usage(FILE *fp, int ret) {
441 fprintf(fp,
442 "Usage: samtools reheader [-P] in.header.sam in.bam > out.bam\n"
443 " or samtools reheader [-P] -i in.header.sam file.cram\n"
444 " or samtools reheader -c CMD in.bam\n"
445 " or samtools reheader -c CMD in.cram\n"
446 "\n"
447 "Options:\n"
448 " -P, --no-PG Do not generate a @PG header line.\n"
449 " -i, --in-place Modify the CRAM file directly, if possible.\n"
450 " (Defaults to outputting to samtools_stdout.)\n"
451 " -c, --command CMD Pass the header in SAM format to external program CMD.\n");
452 samtools_exit(ret);
453 }
454
455 static sam_hdr_t* external_reheader(samFile* in, const char* external) {
456 char *command = NULL;
457 sam_hdr_t* h = NULL;
458 sam_hdr_t* ih = sam_hdr_read(in);
459 if (ih == NULL) {
460 fprintf(samtools_stderr, "[%s] failed to read the header for '%s'.\n", __func__, in->fn);
461 return NULL;
462 }
463 char tmp_fn[] = "reheaderXXXXXX";
464 int tmp_fd = mkstemp(tmp_fn);
465 if (tmp_fd < 0) {
466 print_error_errno("reheader", "fail to open temp file '%s'", tmp_fn);
467 return NULL;
468 }
469 hFILE* tmp_hf = hdopen(tmp_fd, "w");
470 if (!tmp_hf) {
471 fprintf(samtools_stderr, "[%s] failed to convert to hFILE.\n", __func__);
472 goto cleanup;
473 }
474 samFile* tmp_sf = hts_hopen(tmp_hf, tmp_fn, "w");
475 if (!tmp_sf) {
476 fprintf(samtools_stderr, "[%s] failed to convert to samFile.\n", __func__);
477 goto cleanup;
478 }
479 if (-1 == sam_hdr_write(tmp_sf, ih)) {
480 fprintf(samtools_stderr, "[%s] failed to write the header to the temp file.\n", __func__);
481 goto cleanup;
482 }
483 sam_close(tmp_sf);
484 sam_hdr_destroy(ih);
485 int comm_len = strlen(external) + strlen(tmp_fn) + 8;
486 command = calloc(comm_len, 1);
487 if (!command || snprintf(command, comm_len, "( %s ) < %s", external, tmp_fn) != comm_len - 1) {
488 fprintf(samtools_stderr, "[%s] failed to create command string.\n", __func__);
489 goto cleanup;
490 }
491 FILE* nh = popen(command, "r");
492 if (!nh) {
493 print_error_errno("reheader", "[%s] failed to run external command '%s'.\n", __func__, command);
494 goto cleanup;
495 }
496
497 int nh_fd = dup(fileno(nh));
498 if (nh_fd < 0) {
499 fprintf(samtools_stderr, "[%s] failed to get the file descriptor.\n", __func__);
500 goto cleanup;
501 }
502 hFILE* nh_hf = hdopen(nh_fd, "r");
503 if (!nh_hf) {
504 fprintf(samtools_stderr, "[%s] failed to convert to hFILE.\n", __func__);
505 goto cleanup;
506 }
507 samFile* nh_sf = hts_hopen(nh_hf, tmp_fn, "r");
508 if (!nh_sf) {
509 fprintf(samtools_stderr, "[%s] failed to convert to samFile.\n", __func__);
510 goto cleanup;
511 }
512
513 h = sam_hdr_read(nh_sf);
514 sam_close(nh_sf);
515 if (h == NULL) {
516 fprintf(samtools_stderr, "[%s] failed to read the header from the temp file.\n", __func__);
517 }
518 int res = pclose(nh);
519 if (res != 0) {
520 if (res < 0) {
521 print_error_errno("reheader",
522 "Error on closing pipe from command '%s'.\n",
523 command);
524 } else {
525 print_error("reheader",
526 "Non-zero exit code returned by command '%s'\n",
527 command);
528 }
529 if (h) sam_hdr_destroy(h);
530 h = NULL;
531 }
532 cleanup:
533 free(command);
534 if (unlink(tmp_fn) != 0) {
535 print_error_errno("reheader", "failed to remove the temp file '%s'", tmp_fn);
536 }
537
538 return h;
539 }
540
541 int main_reheader(int argc, char *argv[])
542 {
543 int inplace = 0, r, no_pg = 0, c, skip_header = 0;
544 sam_hdr_t *h;
545 samFile *in;
546 char *arg_list = NULL, *external = NULL;
547
548 static const struct option lopts[] = {
549 {"help", no_argument, NULL, 'h'},
550 {"in-place", no_argument, NULL, 'i'},
551 {"no-PG", no_argument, NULL, 'P'},
552 {"command", required_argument, NULL, 'c'},
553 {NULL, 0, NULL, 0}
554 };
555
556 while ((c = getopt_long(argc, argv, "hiPc:", lopts, NULL)) >= 0) {
557 switch (c) {
558 case 'P': no_pg = 1; break;
559 case 'i': inplace = 1; break;
560 case 'c': external = optarg; break;
561 case 'h': usage(samtools_stdout, 0); break;
562 default:
563 fprintf(samtools_stderr, "Invalid option '%c'\n", c);
564 usage(samtools_stderr, 1);
565 }
566 }
567
568 if ((argc - optind != 2 || external) && (argc - optind != 1 || !external))
569 usage(samtools_stderr, 1);
570
571 if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
572 print_error("reheader", "failed to create arg_list");
573 return 1;
574 }
575
576 if (external) {
577 skip_header = 1;
578 in = sam_open(argv[optind], inplace?"r+":"r");
579 if (in == 0) {
580 print_error_errno("reheader", "fail to open file '%s'", argv[optind]);
581 return 1;
582 }
583
584 h = external_reheader(in, external);
585 if (h == NULL) {
586 fprintf(samtools_stderr, "[%s] failed to read the header from '%s'.\n", __func__, external);
587 sam_close(in);
588 return 1;
589 }
590 } else { // read the header from a separate file
591 samFile *fph = sam_open(argv[optind], "r");
592 if (fph == 0) {
593 print_error_errno("reheader", "fail to read the header from '%s'", argv[optind]);
594 return 1;
595 }
596 h = sam_hdr_read(fph);
597 sam_close(fph);
598 if (h == NULL) {
599 fprintf(samtools_stderr, "[%s] failed to read the header for '%s'.\n",
600 __func__, argv[1]);
601 return 1;
602 }
603 in = sam_open(argv[optind+1], inplace?"r+":"r");
604 if (in == 0) {
605 print_error_errno("reheader", "fail to open file '%s'", argv[optind+1]);
606 return 1;
607 }
608 }
609
610 if (hts_get_format(in)->format == bam) {
611 if (inplace) {
612 print_error("reheader", "cannot reheader BAM '%s' in-place", argv[optind+1]);
613 r = -1;
614 } else {
615 r = bam_reheader(in->fp.bgzf, h, fileno(samtools_stdout), arg_list, no_pg, skip_header);
616 }
617 } else if (hts_get_format(in)->format == cram) {
618 if (inplace)
619 r = cram_reheader_inplace(in->fp.cram, h, arg_list, no_pg);
620 else
621 r = cram_reheader(in->fp.cram, h, arg_list, no_pg);
622 } else {
623 print_error("reheader", "input file '%s' must be BAM or CRAM", argv[optind+1]);
624 r = -1;
625 }
626
627 if (sam_close(in) != 0)
628 r = -1;
629
630 sam_hdr_destroy(h);
631
632 if (arg_list)
633 free(arg_list);
634
635 return -r;
636 }