Debian Codegraph @

samtools/bam_cat.c

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