Debian Codegraph @

samtools/bam_cat.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /* bam_cat.c -- efficiently concatenates bam files.
4
5 Copyright (C) 2008-2009, 2011-2013, 2015-2017, 2019, 2021,
6 2023-2024 Genome Research Ltd.
7 Modified SAMtools work copyright (C) 2010 Illumina, Inc.
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notices and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE. */
26
27 /*
28 bam_cat can be used to concatenate BAM files. Under special
29 circumstances, it can be used as an alternative to 'samtools merge' to
30 concatenate multiple sorted files into a single sorted file. For this
31 to work each file must be sorted, and the sorted files must be given
32 as command line arguments in order such that the final read in file i
33 is less than or equal to the first read in file i+1.
34
35 This code is derived from the bam_reheader function in samtools 0.1.8
36 and modified to perform concatenation by Chris Saunders on behalf of
37 Illumina.
38 */
39
40 #include <config.h>
41
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45 #include <string.h>
46 #include <strings.h>
47
48 #include "htslib/bgzf.h"
49 #include "htslib/sam.h"
50 #include "htslib/cram.h"
51 #include "htslib/kstring.h"
52 #include "htslib/hfile.h"
53 #include "samtools.h"
54 #include "sam_opts.h"
55
56 /// cat_check_merge_hdr - check compatibility and merge RG hearders merges RGon both CRAM and BAM.
57 /** @param firstfile - pointer to the 1sr file opened in caller
58 * @param nfn - number of files to be processed, including the firstfile
59 * @param fn - array of file paths to be processed
60 * @param h - sam header pointer which contains explicitly given header
61 * @param vers_maj_p - cram major version set and send out for output creation
62 * @param vers_min_p - cram min version set and send out for output creation
63 * @param out_h - pointer to sam header pointer, outputs the merged header
64 * returns array of opened samFile pointers on success and NULL on failure
65 * This method has the merged header processing for cram and bam.
66 * RG lines are merged for both cram and bam. For cram, version match for each
67 * file and order match of RG lines are compared as well.
68 * Note: it is a simple merge of RG lines alone.
69 */
70 static samFile** cat_check_merge_hdr(samFile * const firstfile, int nfn, char * const *fn, const sam_hdr_t *h,
71 int *vers_maj_p, int *vers_min_p, sam_hdr_t **out_h) {
72 int i, vers_maj = -1, vers_min = -1;
73 sam_hdr_t *new_h = NULL, *old_h = NULL;
74 samFile *in = NULL;
75 kstring_t ks = KS_INITIALIZE;
76 samFile **files = calloc(nfn, sizeof(samFile *));
77 if(!files) {
78 fprintf(samtools_stderr, "[%s] ERROR: failed to allocate space for file handles.\n", __func__);
79 return NULL;
80 }
81 if (!out_h || !firstfile) {
82 fprintf(samtools_stderr, "[%s] ERROR: header check failed.\n", __func__);
83 goto fail;
84 }
85 if (*out_h) { //use header if one is already present
86 new_h = *out_h;
87 }
88 else {
89 if (h) { //use the explicit header given
90 new_h = sam_hdr_dup(h);
91 if (!new_h) {
92 fprintf(samtools_stderr, "[%s] ERROR: header duplication failed.\n",
93 __func__);
94 goto fail;
95 }
96 }
97 }
98
99 for (i = 0; i < nfn; ++i) {
100 int ki;
101 //1st file is already open and passed, rest open locally
102 files[i] = in = i ? sam_open(fn[i], "r") : firstfile;
103 if (in == 0) {
104 print_error_errno("cat", "fail to open file '%s'", fn[i]);
105 goto fail;
106 }
107 if (firstfile->format.format != in->format.format) {
108 print_error("cat", "File %s is of different format!", fn[i]);
109 goto fail;
110 }
111 if (firstfile->format.format == cram) { //version check for cram
112 cram_fd *in_c;
113 in_c = in->fp.cram;
114
115 int vmaj = cram_major_vers(in_c);
116 int vmin = cram_minor_vers(in_c);
117 if ((vers_maj != -1 && vers_maj != vmaj) ||
118 (vers_min != -1 && vers_min != vmin)) {
119 fprintf(samtools_stderr, "[%s] ERROR: input files have differing version numbers.\n",
120 __func__);
121 goto fail;
122 }
123 vers_maj = vmaj;
124 vers_min = vmin;
125 }
126
127 old_h = sam_hdr_read(in);
128 if (!old_h) {
129 fprintf(samtools_stderr, "[%s] ERROR: header reading for file '%s' filed.\n",
130 __func__, fn[i]);
131 goto fail;
132 }
133
134 if (!new_h) {
135 new_h = sam_hdr_dup(old_h);
136 if (!new_h) {
137 fprintf(samtools_stderr, "[%s] ERROR: header duplication for file '%s' failed.\n",
138 __func__, fn[i]);
139 goto fail;
140 }
141 sam_hdr_destroy(old_h);
142 old_h = NULL;
143 continue;
144 }
145 //merge RG lines
146 int old_count = sam_hdr_count_lines(old_h, "RG");
147 for (ki = 0; ki < old_count; ki++) {
148 const char *old_name = sam_hdr_line_name(old_h, "RG", ki);
149 if (old_name) {
150 int new_i = sam_hdr_line_index(new_h, "RG", old_name);
151 if (-1 == new_i) { // line does not exist in the new header
152 if (sam_hdr_find_line_pos(old_h, "RG", ki, &ks) ||
153 !ks.s || sam_hdr_add_lines(new_h, ks.s, ks.l)) {
154 fprintf(samtools_stderr, "[%s] ERROR: failed to add @RG line 'ID:%s' from file '%s'\n",
155 __func__, old_name, fn[i]);
156 goto fail;
157 }
158 ks_free(&ks);
159 }
160 } else {
161 fprintf(samtools_stderr, "[%s] ERROR: failed to read %d @RG line from file '%s'\n",
162 __func__, ki, fn[i]);
163 goto fail;
164 }
165 }
166
167 if (firstfile->format.format == cram && old_count > 1 && sam_hdr_count_lines(new_h, "RG") == old_count) {
168 //RG order check for cram
169 for (ki = 0; ki < old_count; ki++) {
170 const char *old_name = sam_hdr_line_name(old_h, "RG", ki);
171 const char *new_name = sam_hdr_line_name(new_h, "RG", ki);
172 if (!old_name || !new_name || strcmp(old_name, new_name)) {
173 fprintf(samtools_stderr, "[%s] ERROR: Same size @RG lists but differing order / contents\n",
174 __func__);
175 goto fail;
176 }
177 }
178 }
179
180 sam_hdr_destroy(old_h); old_h = NULL;
181 }
182
183 ks_free(&ks);
184
185 if (vers_maj_p) {
186 *vers_maj_p = vers_maj;
187 }
188 if (vers_min_p) {
189 *vers_min_p = vers_min;
190 }
191 *out_h = new_h;
192 return files;
193
194 fail:
195 ks_free(&ks);
196 if (old_h) sam_hdr_destroy(old_h);
197 if (new_h) sam_hdr_destroy(new_h);
198 *out_h = NULL;
199 for (i = 1; i < nfn; ++i) { //close files other than the firstfile
200 if (files[i]) {
201 sam_close(files[i]);
202 }
203 }
204 free(files);
205
206 return NULL;
207 }
208
209
210 /* ----------------------------------------------------------------------
211 * CRAM cat
212 */
213
214 // Reports the number of CRAM containers spanning a specified region if
215 // specified, or the entire file if not.
216 // This is the implements the "samtools cat -q [-r reg]" functionality.
217 //
218 // Returns 0 on success, <0 on error.
219 static int cram_query_ncont(int nfn, char * const *fn, char *reg) {
220 int i;
221 hts_idx_t *idx = NULL;
222 sam_hdr_t *hdr = NULL;
223 hts_itr_t *iter = NULL;
224 samFile *in = NULL;
225
226 for (i = 0; i < nfn; i++) {
227 in = sam_open(fn[i], "r");
228 if (!in) {
229 print_error_errno("cat", "Couldn't open file %s", fn[i]);
230 return -1;
231 }
232 idx = sam_index_load(in, fn[i]);
233 if (!idx) {
234 print_error("cat", "No index found");
235 goto err;
236 }
237
238 off_t cstart = 0, cend = 0;
239 if (reg) {
240 sam_hdr_t *hdr = sam_hdr_read(in);
241 hts_itr_t *iter = sam_itr_querys(idx, hdr, reg);
242 if (!hdr) {
243 print_error("cat", "Unable to read header");
244 goto err;
245 }
246 if (!iter) {
247 print_error("cat", "Unable to parse region");
248 goto err;
249 }
250
251 if (cram_index_extents(in->fp.cram, iter->tid, iter->beg,
252 iter->end, &cstart, &cend) < 0) {
253 print_error("cat", "Failed to query index");
254 goto err;
255 }
256
257 hts_itr_destroy(iter);
258 sam_hdr_destroy(hdr);
259 }
260
261 int64_t first, last;
262 int64_t nc = cram_num_containers_between(in->fp.cram, cstart, cend,
263 &first, &last);
264 fprintf(samtools_stdout, "%s\t%"PRId64"\t%"PRId64"\t%"PRId64"\n",
265 fn[i], nc, first, last);
266 sam_close(in);
267 hts_idx_destroy(idx);
268 }
269
270 return 0;
271
272 err:
273 if (idx)
274 hts_idx_destroy(idx);
275 if (hdr)
276 sam_hdr_destroy(hdr);
277 if (iter)
278 hts_itr_destroy(iter);
279
280 sam_close(in);
281
282 return -1;
283 }
284
285 // Container range #:A-B or #:A.
286 // Returns 0 on success, -1 on failure.
287 static int cram_handle_cnum_region(cram_fd *fd, hts_idx_t *idx,
288 char *reg, off_t *cstart, off_t *cend) {
289 int cnum_start, cnum_end; // container versions
290 int n = sscanf(reg, "#:%d-%d", &cnum_start, &cnum_end);
291
292 if (n == 0) {
293 print_error("cat", "ERROR: Malformed region: %s", reg);
294 return -1;
295 } else if (n == 1) {
296 cnum_end = cnum_start;
297 }
298
299 int64_t nc = cram_num_containers(fd);
300 if (cnum_end >= nc) {
301 print_error("cat", "Too many containers. "
302 "The end range should be < %"PRId64, nc);
303 return -1;
304 }
305
306 // Container number to offset
307 *cstart = cram_container_num2offset(fd, cnum_start);
308 *cend = cram_container_num2offset(fd, cnum_end);
309 if (*cstart < 0 || *cend < 0)
310 return -1;
311
312 // Seek manually
313 return cram_seek(fd, *cstart, SEEK_SET);
314 }
315
316 // Normal range chr:start-end.
317 // Returns an hts iterator on success, NULL on failure.
318 static hts_itr_t *cram_handle_region(cram_fd *fd, hts_idx_t *idx, sam_hdr_t *h,
319 char *reg, off_t *cstart, off_t *cend) {
320 hts_itr_t *iter;
321
322 if (!idx) {
323 fprintf(samtools_stderr, "[%s] ERROR: No index found.\n", __func__);
324 return NULL;
325 }
326
327 // This does an implicit seek and modifies the cram_fd.
328 if (!(iter = sam_itr_querys(idx, h, reg))) {
329 print_error("cat", "Unable to parse region %s", reg);
330 return NULL;
331 }
332 if (cram_index_extents(fd, iter->tid, iter->beg,
333 iter->end, cstart, cend) < 0) {
334 print_error("cat", "Failed to query index");
335 return NULL;
336 }
337
338 return iter;
339 }
340
341 // Handle the -p A/B option to subdivide our region or file into portions.
342 // Updates cstart/cend.
343 // returns 0 on success (do something),
344 // 1 on success (but nothing to do),
345 // -1 on failure.
346 static int cram_subdivide_part(cram_fd *fd, hts_idx_t *idx, char *part,
347 off_t *cstart, off_t *cend) {
348 int a, b;
349 // Part N of M
350 if (sscanf(part, "%d/%d", &a, &b) != 2) {
351 print_error("cat", "malformed region %s. Should be e.g. '1/10'", part);
352 return -1;
353 }
354
355 // Inclusive container numbers for range, 0 to NC-1
356 // Our part N/M is in container percentages as we can't have
357 // partial containers, so convert to that first.
358 int64_t cnum1, cnum2;
359 if (cstart) {
360 cnum1 = cram_container_offset2num(fd, *cstart);
361 cnum2 = cram_container_offset2num(fd, *cend);
362 } else {
363 cnum1 = 0;
364 cnum2 = cram_num_containers(fd)-1;
365 }
366
367 // Subdivide cnum1/cnum2 container numbers to new range cnum_start/end
368 int64_t nc = cnum2 - cnum1 + 1;
369 if (b > nc)
370 b = nc;
371
372 int cnum_start = (a-1)*(double)nc/b;
373 int cnum_end = a*(double)nc/b - 1;
374 if (cnum_start < 0 || cnum_end >= nc)
375 return 1;
376
377 // Then convert back to file offsets so we can seek and do htell
378 // to detect EOR/EOF.
379 *cstart = cram_container_num2offset(fd, cnum_start + cnum1);
380 *cend = cram_container_num2offset(fd, cnum_end + cnum1);
381
382 return 0;
383 }
384
385 // The main cram_cat interface.
386 // Returns 0 on success, < 0 on error.
387 int cram_cat(samFile * const firstfile, int nfn, char * const *fn,
388 const sam_hdr_t *h, const char* outcram, sam_global_args *ga,
389 char *arg_list, int no_pg, char *reg, char *part, int fast_reg)
390 {
391 samFile *out = NULL;
392 cram_fd *out_c;
393 int i, vers_maj, vers_min, ret = -1;
394 sam_hdr_t *new_h = NULL;
395 samFile **files = NULL;
396 hts_idx_t *idx = NULL;
397 hts_itr_t *iter = NULL;
398 sam_hdr_t *old_h = NULL;
399
400 // Check consistent versioning and compatible headers;
401 // merges RG lines, opens all files and returns them that multiple
402 // non-seekable stream inputs can be handled
403 if (!(files = cat_check_merge_hdr(firstfile, nfn, fn, h, &vers_maj,
404 &vers_min, &new_h)))
405 return -1;
406
407 if (!new_h) {
408 print_error_errno("cat", "failed to make output header");
409 goto closefiles;
410 }
411
412 /* Open the file with cram_vers */
413 char vers[100];
414 snprintf(vers, sizeof(vers), "%d.%d", vers_maj, vers_min);
415
416 // Can override level=1 with e.g. "--output-fmt-option level=9"
417 out = sam_open_format(outcram, "wc1", &ga->out);
418 if (out == 0) {
419 print_error_errno("cat", "fail to open output file '%s'", outcram);
420 goto closefiles;
421 }
422 out_c = out->fp.cram;
423 cram_set_option(out_c, CRAM_OPT_VERSION, vers);
424
425 if (!no_pg && sam_hdr_add_pg(new_h, "samtools",
426 "VN", samtools_version(),
427 arg_list ? "CL": NULL,
428 arg_list ? arg_list : NULL,
429 NULL))
430 goto closefiles;
431
432 if (sam_hdr_write(out, new_h) < 0) {
433 print_error_errno("cat", "Couldn't write header");
434 goto closefiles;
435 }
436 out_c = out->fp.cram;
437
438 for (i = 0; i < nfn; ++i) {
439 samFile *in;
440 cram_fd *in_c;
441 cram_container *c;
442 int new_rg = -1;
443
444 in = files[i];
445 if (in == 0) {
446 print_error_errno("cat", "fail to open file '%s'", fn[i]);
447 goto closefiles;
448 }
449 in_c = in->fp.cram;
450
451 old_h = sam_hdr_read(in);
452 if (!old_h) {
453 print_error("cat", "fail to read the header of file '%s'", fn[i]);
454 goto closefiles;
455 }
456
457 // Compute RG mapping if suitable for changing.
458 if (sam_hdr_count_lines(old_h, "RG") == 1) {
459 const char *old_name = sam_hdr_line_name(old_h, "RG", 0);
460 if (old_name) {
461 new_rg = sam_hdr_line_index(new_h, "RG", old_name);
462 if (new_rg < 0) {
463 print_error("cat", "fail to find @RG line '%s' in the new header", old_name);
464 goto closefiles;
465 }
466 } else {
467 print_error("cat", "fail to find @RG line in file '%s'", fn[i]);
468 goto closefiles;
469 }
470 } else {
471 new_rg = 0;
472 }
473
474 // We have multiple region syntax. Either the standard chr:start-end
475 // or a cat-specific #:num-num for explicit container numbers.
476 // Both of these seek to a specific file offset and also have the
477 // end offset known so we can use htell to detect when we're done.
478 // Those offsets are in cstart and cend.
479 //
480 // However for the e.g. -p 1/10 syntax we need to know the container
481 // numbers corresponding to the cstart/cend offsets as we can't
482 // start half way through a container when doing fractions.
483 // These are cnum1 and cnum2. (We could short cut this for the
484 // #:num-num, but it's simpler to just treat all regions identically.)
485 off_t cstart = 0, cend = 0;
486 int filter_by_cnum = 0;
487
488 if (reg || part) {
489 idx = sam_index_load(in, fn[i]);
490 if (!idx) {
491 print_error("cat", "failed to load index");
492 goto closefiles;
493 }
494 }
495
496 if (reg) {
497 if (strncmp(reg, "#:", 2) == 0) {
498 // Region as container numbers
499 if (cram_handle_cnum_region(in_c, idx, reg, &cstart,&cend) < 0)
500 goto closefiles;
501
502 filter_by_cnum = 1;
503 } else {
504 // Normal range chr:start-end
505 if (!(iter = cram_handle_region(in_c, idx, old_h, reg,
506 &cstart, &cend)))
507 goto closefiles;
508 }
509 }
510
511 // We can also take a range above and subdivide it into parts.
512 // Eg -r chr1 -p 1/10 (... to -p 10/10). Part only implies
513 // portions of the entire file.
514 if (part) {
515 int r = cram_subdivide_part(in_c, idx, part, &cstart, &cend);
516 if (r != 0) {
517 if (r > 0) // Not an error, just nothing to do
518 ret = 0;
519 goto closefiles;
520 }
521 }
522
523 if (cstart) // reg or part
524 if (0 != cram_seek(in_c, cstart, SEEK_SET))
525 goto closefiles;
526
527
528 // Make refid -2 ("*") come after other chromosomes, for easy sort
529 int itid = iter
530 ? (iter->tid == HTS_IDX_NOCOOR ? INT_MAX : iter->tid)
531 : 0;
532 int last_ref_id = -99;
533
534 off_t before_hdr = htell(cram_fd_get_fp(in_c));
535
536 // Copy contains and blocks within them
537 while ((c = cram_read_container(in_c))) {
538 if (cram_container_is_empty(in_c)) {
539 cram_block *blk;
540 // Container compression header
541 if (!(blk = cram_read_block(in_c)))
542 goto closefiles;
543 cram_free_block(blk);
544 cram_free_container(c);
545 continue;
546 }
547
548 int filter = 0;
549
550 // If we have just one RG key and new_rg != 0 then
551 // we need to edit the compression header. IF WE CAN.
552 if (new_rg) {
553 if (reg) {
554 print_error("cat", "Cannot specify a region while "
555 "transcoding RG lines");
556 goto closefiles;
557 }
558 int zero = 0;
559 //fprintf(samtools_stderr, "Transcode RG %d to %d\n", 0, new_rg);
560 cram_transcode_rg(in_c, out_c, c, 1, &zero, &new_rg);
561 } else {
562 int32_t num_slices;
563
564 if (reg) {
565 if (before_hdr > cend) {
566 cram_free_container(c);
567 break;
568 }
569 }
570
571 // For chr:start-end regions, do we need to filter or skip?
572 if (iter && reg) {
573 int refid;
574 hts_pos_t start, span, end;
575
576 cram_container_get_coords(c, &refid, &start, &span);
577 end = start+span;
578
579 // Make refid -1 ("*") come after other chromosomes
580 if (refid == -1)
581 refid = INT_MAX;
582
583 if (refid > itid || start > iter->end) {
584 // Beyond the requested range
585 break;
586 } else if (refid == -2) {
587 // Multi-ref containers. We only support this if
588 // the RI data series is in a container by itself.
589 filter = 3;
590 } else if (refid < itid || end < iter->beg) {
591 // Skip, in case of mixed size containers.
592 // Eg: Use "=", skip "-".
593 // ==========|======|=
594 // ---- ==|== ==|== ----
595 // ----- | ==== ----
596 filter = 2;
597 } else if (start < iter->beg || end > iter->end) {
598 // Container overlaps region.
599 // Fast mode just copies overlapping containers.
600 // Slow mode does a precise filtering by reading and
601 // filtering each record in turn so it's the same as
602 // a samtools view command.
603 filter = fast_reg ? 0 : 1;
604 }
605 // else we're in an "internal" container, so just copy
606 }
607
608 if (filter && last_ref_id == -1 && itid == INT_MAX)
609 // Multi-ref containers consisting solely of ref "*" are
610 // common, but if it's sorted then we know it's "*" from
611 // here on so we don't need to filter despite multi-ref.
612 filter = 0;
613
614 if (filter) {
615 // Filter or skip
616 cram_filter_container(in_c, out_c, c, &last_ref_id);
617 } else {
618 // Copy. Consider adding a cram_copy_container API instead.
619
620 // Container compression header
621 cram_block *blk;
622 if (!(blk = cram_read_block(in_c)))
623 goto closefiles;
624
625 // Not switching rg so do the usual read/write loop
626 if (cram_write_container(out_c, c) != 0)
627 goto closefiles;
628
629 // Contatiner compression header
630 if (cram_write_block(out_c, blk) != 0) {
631 cram_free_block(blk);
632 goto closefiles;
633 }
634
635 // Container num_blocks can be invalid, due to a bug.
636 // Instead we iterate in slice context instead.
637 (void)cram_container_get_landmarks(c, &num_slices);
638 if (cram_copy_slice(in_c, out_c, num_slices) < 0) {
639 cram_free_block(blk);
640 goto closefiles;
641 }
642 cram_free_block(blk);
643 }
644 }
645 cram_free_container(c);
646
647 // Location of next container start
648 before_hdr = htell(cram_fd_get_fp(in_c));
649 if (filter_by_cnum && before_hdr > cend)
650 break;
651 }
652 sam_hdr_destroy(old_h);
653 old_h = NULL;
654
655 if (idx) {
656 hts_idx_destroy(idx);
657 idx = NULL;
658 }
659
660 if (iter) {
661 hts_itr_destroy(iter);
662 iter = NULL;
663 }
664 }
665 ret = 0;
666
667 closefiles:
668 if (old_h)
669 sam_hdr_destroy(old_h);
670
671 if (idx)
672 hts_idx_destroy(idx);
673
674 if (iter)
675 hts_itr_destroy(iter);
676
677 if (out)
678 sam_close(out);
679
680 if (new_h)
681 sam_hdr_destroy(new_h);
682
683 for (i = 1; i < nfn; ++i) { //skip firstfile and close rest
684 if (files[i]) {
685 sam_close(files[i]);
686 }
687 }
688 free(files);
689 return ret;
690 }
691
692 /* ----------------------------------------------------------------------
693 * BAM cat
694 */
695 #define BUF_SIZE 0x10000
696
697 #define GZIPID1 31
698 #define GZIPID2 139
699
700 #define BGZF_EMPTY_BLOCK_SIZE 28
701
702 int bam_cat(samFile * const firstfile, int nfn, char * const *fn, sam_hdr_t *h, const char* outbam, char *arg_list, int no_pg)
703 {
704 BGZF *fp = NULL, *in = NULL;
705 uint8_t *buf = NULL;
706 uint8_t ebuf[BGZF_EMPTY_BLOCK_SIZE];
707 const int es=BGZF_EMPTY_BLOCK_SIZE;
708 int i;
709 samFile **files = NULL;
710 sam_hdr_t *new_h = NULL;
711
712 /* merges RG lines, opens all files and returns them that multiple non-seekable
713 stream inputs can be handled */
714 if (!(files = cat_check_merge_hdr(firstfile, nfn, fn, h, NULL, NULL, &new_h)))
715 return -1;
716 if (!new_h) {
717 print_error_errno("cat", "failed to make output header");
718 goto fail;
719 }
720 fp = strcmp(outbam, "-")? bgzf_open(outbam, "w") : bgzf_fdopen(fileno(samtools_stdout), "w");
721 if (fp == 0) {
722 print_error_errno("cat", "fail to open output file '%s'", outbam);
723 goto fail;
724 }
725
726 if (!no_pg && sam_hdr_add_pg(new_h, "samtools",
727 "VN", samtools_version(),
728 arg_list ? "CL": NULL,
729 arg_list ? arg_list : NULL,
730 NULL))
731 goto fail;
732
733 if (bam_hdr_write(fp, new_h) < 0) {
734 print_error_errno("cat", "Couldn't write header");
735 goto fail;
736 }
737
738 buf = (uint8_t*) malloc(BUF_SIZE);
739 if (!buf) {
740 fprintf(samtools_stderr, "[%s] Couldn't allocate buffer\n", __func__);
741 goto fail;
742 }
743 for(i = 0; i < nfn; ++i){
744 int len,j;
745 in = files[i]->fp.bgzf;
746 if (in == 0) {
747 print_error_errno("cat", "fail to open file '%s'", fn[i]);
748 goto fail;
749 }
750 if (in->is_write) goto fail;
751
752 if (in->block_offset < in->block_length) {
753 if (bgzf_write(fp, (char *)in->uncompressed_block + in->block_offset, in->block_length - in->block_offset) < 0) goto write_fail;
754 if (bgzf_flush(fp) != 0) goto write_fail;
755 }
756
757 j=0;
758 while ((len = bgzf_raw_read(in, buf, BUF_SIZE)) > 0) {
759 if(len<es){
760 int diff=es-len;
761 if(j==0) {
762 fprintf(samtools_stderr, "[%s] ERROR: truncated file?: '%s'.\n", __func__, fn[i]);
763 goto fail;
764 }
765 if (bgzf_raw_write(fp, ebuf, len) < 0) goto write_fail;
766
767 memcpy(ebuf,ebuf+len,diff);
768 memcpy(ebuf+diff,buf,len);
769 } else {
770 if(j!=0) {
771 if (bgzf_raw_write(fp, ebuf, es) < 0) goto write_fail;
772 }
773 len-= es;
774 memcpy(ebuf,buf+len,es);
775 if (bgzf_raw_write(fp, buf, len) < 0) goto write_fail;
776 }
777 j=1;
778 }
779
780 /* check final gzip block */
781 {
782 const uint8_t gzip1=ebuf[0];
783 const uint8_t gzip2=ebuf[1];
784 const uint32_t isize=*((uint32_t*)(ebuf+es-4));
785 if(((gzip1!=GZIPID1) || (gzip2!=GZIPID2)) || (isize!=0)) {
786 fprintf(samtools_stderr, "[%s] WARNING: Unexpected block structure in file '%s'.", __func__, fn[i]);
787 fprintf(samtools_stderr, " Possible output corruption.\n");
788 if (bgzf_raw_write(fp, ebuf, es) < 0) goto write_fail;
789 }
790 }
791 in = NULL;
792 }
793 free(buf);
794 if (bgzf_close(fp) < 0) {
795 fprintf(samtools_stderr, "[%s] Error on closing '%s'.\n", __func__, outbam);
796 goto fail;
797 }
798 for (i = 1; i < nfn; ++i) { //skip firstfile and close rest
799 if (files[i]) {
800 sam_close(files[i]);
801 }
802 }
803 free(files);
804 sam_hdr_destroy(new_h);
805 return 0;
806
807 write_fail:
808 fprintf(samtools_stderr, "[%s] Error writing to '%s'.\n", __func__, outbam);
809 fail:
810 if (new_h) {
811 sam_hdr_destroy(new_h);
812 }
813 if (fp) bgzf_close(fp);
814 free(buf);
815
816 if (files) {
817 for(i = 1; i < nfn; ++i) { //except the firstfile
818 if(files[i]) {
819 sam_close(files[i]);
820 }
821 }
822 free(files);
823 }
824 return -1;
825 }
826
827 int main_cat(int argc, char *argv[])
828 {
829 sam_hdr_t *h = 0;
830 char *outfn = 0;
831 char **infns = NULL; // files to concatenate
832 int infns_size = 0;
833 int c, ret = 0, no_pg = 0, usage = 0, query_ncont = 0, fast_mode = 0;
834 samFile *in;
835 sam_global_args ga;
836 char *reg = NULL, *part = NULL;
837
838 static const struct option lopts[] = {
839 SAM_OPT_GLOBAL_OPTIONS('-', '-', '-', 0, '-', '-'),
840 {"no-PG", no_argument, NULL, 1},
841 { NULL, 0, NULL, 0 }
842 };
843
844 char *arg_list = NULL;
845
846 sam_global_args_init(&ga);
847 while ((c = getopt_long(argc, argv, "h:o:b:r:p:qf", lopts, NULL)) >= 0) {
848 switch (c) {
849 case 'h': {
850 samFile *fph = sam_open(optarg, "r");
851 if (fph == 0) {
852 fprintf(samtools_stderr, "[%s] ERROR: fail to read the header from '%s'.\n", __func__, optarg);
853 ret = 1;
854 goto end;
855 }
856 h = sam_hdr_read(fph);
857 if (h == NULL) {
858 fprintf(samtools_stderr,
859 "[%s] ERROR: failed to read the header from '%s'.\n",
860 __func__, optarg);
861 ret = 1;
862 goto end;
863 }
864 sam_close(fph);
865 break;
866 }
867 case 'o': outfn = strdup(optarg); break;
868 case 'b': {
869 // add file names in "optarg" to the list
870 // of files to concatenate
871 int nfns;
872 char **fns_read = hts_readlines(optarg, &nfns);
873 if (fns_read) {
874 infns = realloc(infns, (infns_size + nfns) * sizeof(char*));
875 if (infns == NULL) { ret = 1; goto end; }
876 memcpy(infns+infns_size, fns_read, nfns * sizeof(char*));
877 infns_size += nfns;
878 free(fns_read);
879 } else {
880 print_error("cat", "Invalid file list \"%s\"", optarg);
881 ret = 1;
882 }
883 break;
884 }
885 case 1:
886 no_pg = 1;
887 break;
888 case 'r':
889 reg = optarg;
890 break;
891 case 'p':
892 part = optarg;
893 break;
894 case 'f':
895 fast_mode = 1;
896 break;
897 case 'q':
898 query_ncont=1;
899 break;
900
901 default:
902 if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
903 /* else fall-through */
904 case '?': usage=1; break;
905 }
906 }
907
908 if (!no_pg && !(arg_list = stringify_argv(argc+1, argv-1))) {
909 print_error("cat", "failed to create arg_list");
910 ret = 1;
911 goto end;
912 }
913
914 // Append files specified in argv to the list.
915 int nargv_fns = argc - optind;
916 if (nargv_fns > 0) {
917 infns = realloc(infns, (infns_size + nargv_fns) * sizeof(char*));
918 if (infns == NULL) { ret = 1; goto end; }
919 memcpy(infns + infns_size, argv + optind, nargv_fns * sizeof(char*));
920 }
921
922 // Require at least one input file
923 if (infns_size + nargv_fns == 0 || usage) {
924 fprintf(samtools_stderr, "Usage: samtools cat [options] <in1.bam> [... <inN.bam>]\n");
925 fprintf(samtools_stderr, " samtools cat [options] <in1.cram> [... <inN.cram>]\n\n");
926 fprintf(samtools_stderr, "Concatenate BAM or CRAM files, first those in <bamlist.fofn>, then those\non the command line.\n\n");
927 fprintf(samtools_stderr, "Options: -b FILE list of input BAM/CRAM file names, one per line\n");
928 fprintf(samtools_stderr, " -h FILE copy the header from FILE [default is 1st input file]\n");
929 fprintf(samtools_stderr, " -o FILE output BAM/CRAM\n");
930 fprintf(samtools_stderr, " --no-PG do not add a PG line\n");
931 fprintf(samtools_stderr, "\nCRAM only options for filtering:\n");
932 fprintf(samtools_stderr, " -r REG filter to region REG.\n");
933 fprintf(samtools_stderr, " REG can also be #:cstart-cend for specific container numbers\n");
934 fprintf(samtools_stderr, " -p N/M Specify part N of M (where N is 1 to M inclusive)\n");
935 fprintf(samtools_stderr, " -f Fast mode: don't filter containers to exactly match region\n");
936 fprintf(samtools_stderr, " -q Query the total number of indexed containers\n");
937 fprintf(samtools_stderr, "\nStandard options:\n");
938 sam_global_opt_help(samtools_stderr, "---.---.");
939 ret = 1;
940 goto end;
941 }
942
943 in = sam_open(infns[0], "r");
944 if (!in) {
945 print_error_errno("cat", "failed to open file '%s'", infns[0]);
946 ret = 1;
947 goto end;
948 }
949
950 switch (hts_get_format(in)->format) {
951 case bam:
952 if (bam_cat(in, infns_size+nargv_fns, infns, h, outfn? outfn : "-", arg_list, no_pg) < 0)
953 ret = 1;
954 break;
955
956 case cram:
957 if (query_ncont) {
958 if (cram_query_ncont(infns_size+nargv_fns, infns, reg) < 0)
959 ret = 1;
960 } else {
961 if (cram_cat(in, infns_size+nargv_fns, infns, h,
962 outfn? outfn : "-", &ga, arg_list, no_pg, reg,
963 part, fast_mode) < 0)
964 ret = 1;
965 }
966 break;
967
968 default:
969 fprintf(samtools_stderr, "[%s] ERROR: input is not BAM or CRAM\n", __func__);
970 ret = 1;
971 }
972 sam_close(in);
973
974 end:
975 if (infns_size > 0) {
976 int i;
977 for (i=0; i<infns_size; i++)
978 free(infns[i]);
979 }
980
981 free(outfn);
982 free(infns);
983 free(arg_list);
984 if (h)
985 sam_hdr_destroy(h);
986 sam_global_args_free(&ga);
987
988 return ret;
989 }