Line | Count | Source |
1 | | /* sam.c -- SAM and BAM file I/O and manipulation. |
2 | | |
3 | | Copyright (C) 2008-2010, 2012-2026 Genome Research Ltd. |
4 | | Copyright (C) 2010, 2012, 2013 Broad Institute. |
5 | | |
6 | | Author: Heng Li <lh3@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 | | #define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h |
27 | | #include <config.h> |
28 | | |
29 | | #include <strings.h> |
30 | | #include <stdio.h> |
31 | | #include <stdlib.h> |
32 | | #include <string.h> |
33 | | #include <errno.h> |
34 | | #include <zlib.h> |
35 | | #include <assert.h> |
36 | | #include <signal.h> |
37 | | #include <inttypes.h> |
38 | | #include <unistd.h> |
39 | | #include <regex.h> |
40 | | |
41 | | #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
42 | | #include "fuzz_settings.h" |
43 | | #endif |
44 | | |
45 | | // Suppress deprecation message for cigar_tab, which we initialise |
46 | | #include "htslib/hts_defs.h" |
47 | | #undef HTS_DEPRECATED |
48 | | #define HTS_DEPRECATED(message) |
49 | | |
50 | | #include "htslib/sam.h" |
51 | | #include "htslib/bgzf.h" |
52 | | #include "cram/cram.h" |
53 | | #include "hts_internal.h" |
54 | | #include "sam_internal.h" |
55 | | #include "htslib/hfile.h" |
56 | | #include "htslib/hts_alloc.h" |
57 | | #include "htslib/hts_endian.h" |
58 | | #include "htslib/hts_expr.h" |
59 | | #include "header.h" |
60 | | #include "bgzf_internal.h" |
61 | | |
62 | | #include "htslib/khash.h" |
63 | | KHASH_DECLARE(s2i, kh_cstr_t, int64_t) |
64 | 0 | KHASH_SET_INIT_INT(tag) |
65 | 0 |
|
66 | 0 | #ifndef EFTYPE |
67 | 0 | #define EFTYPE ENOEXEC |
68 | | #endif |
69 | | #ifndef EOVERFLOW |
70 | | #define EOVERFLOW ERANGE |
71 | | #endif |
72 | | |
73 | | /********************** |
74 | | *** BAM header I/O *** |
75 | | **********************/ |
76 | | |
77 | | HTSLIB_EXPORT |
78 | | const int8_t bam_cigar_table[256] = { |
79 | | // 0 .. 47 |
80 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
81 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
82 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
83 | | |
84 | | // 48 .. 63 (including =) |
85 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, BAM_CEQUAL, -1, -1, |
86 | | |
87 | | // 64 .. 79 (including MIDNHB) |
88 | | -1, -1, BAM_CBACK, -1, BAM_CDEL, -1, -1, -1, |
89 | | BAM_CHARD_CLIP, BAM_CINS, -1, -1, -1, BAM_CMATCH, BAM_CREF_SKIP, -1, |
90 | | |
91 | | // 80 .. 95 (including SPX) |
92 | | BAM_CPAD, -1, -1, BAM_CSOFT_CLIP, -1, -1, -1, -1, |
93 | | BAM_CDIFF, -1, -1, -1, -1, -1, -1, -1, |
94 | | |
95 | | // 96 .. 127 |
96 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
97 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
98 | | |
99 | | // 128 .. 255 |
100 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
101 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
102 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
103 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
104 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
105 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
106 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
107 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 |
108 | | }; |
109 | | |
110 | | sam_hdr_t *sam_hdr_init(void) |
111 | 89.2k | { |
112 | 89.2k | sam_hdr_t *bh = (sam_hdr_t*)calloc(1, sizeof(sam_hdr_t)); |
113 | 89.2k | if (bh == NULL) return NULL; |
114 | | |
115 | 89.2k | bh->cigar_tab = bam_cigar_table; |
116 | 89.2k | return bh; |
117 | 89.2k | } |
118 | | |
119 | | void sam_hdr_destroy(sam_hdr_t *bh) |
120 | 191k | { |
121 | 191k | int32_t i; |
122 | | |
123 | 191k | if (bh == NULL) return; |
124 | | |
125 | 116k | if (bh->ref_count > 0) { |
126 | 27.7k | --bh->ref_count; |
127 | 27.7k | return; |
128 | 27.7k | } |
129 | | |
130 | 89.2k | if (bh->target_name) { |
131 | 72.5k | for (i = 0; i < bh->n_targets; ++i) |
132 | 41.9k | free(bh->target_name[i]); |
133 | 30.5k | free(bh->target_name); |
134 | 30.5k | free(bh->target_len); |
135 | 30.5k | } |
136 | 89.2k | free(bh->text); |
137 | 89.2k | if (bh->hrecs) |
138 | 55.1k | sam_hrecs_free(bh->hrecs); |
139 | 89.2k | if (bh->sdict) |
140 | 2.24k | kh_destroy(s2i, (khash_t(s2i) *) bh->sdict); |
141 | 89.2k | free(bh); |
142 | 89.2k | } |
143 | | |
144 | | // Copy the sam_hdr_t::sdict hash, used to store the real lengths of long |
145 | | // references before sam_hdr_t::hrecs is populated |
146 | | int sam_hdr_dup_sdict(const sam_hdr_t *h0, sam_hdr_t *h) |
147 | 0 | { |
148 | 0 | const khash_t(s2i) *src_long_refs = (khash_t(s2i) *) h0->sdict; |
149 | 0 | khash_t(s2i) *dest_long_refs = kh_init(s2i); |
150 | 0 | int i; |
151 | 0 | if (!dest_long_refs) return -1; |
152 | | |
153 | 0 | for (i = 0; i < h->n_targets; i++) { |
154 | 0 | int ret; |
155 | 0 | khiter_t ksrc, kdest; |
156 | 0 | if (h->target_len[i] < UINT32_MAX) continue; |
157 | 0 | ksrc = kh_get(s2i, src_long_refs, h->target_name[i]); |
158 | 0 | if (ksrc == kh_end(src_long_refs)) continue; |
159 | 0 | kdest = kh_put(s2i, dest_long_refs, h->target_name[i], &ret); |
160 | 0 | if (ret < 0) { |
161 | 0 | kh_destroy(s2i, dest_long_refs); |
162 | 0 | return -1; |
163 | 0 | } |
164 | 0 | kh_val(dest_long_refs, kdest) = kh_val(src_long_refs, ksrc); |
165 | 0 | } |
166 | | |
167 | 0 | h->sdict = dest_long_refs; |
168 | 0 | return 0; |
169 | 0 | } |
170 | | |
171 | | sam_hdr_t *sam_hdr_dup(const sam_hdr_t *h0) |
172 | 51.5k | { |
173 | 51.5k | if (h0 == NULL) return NULL; |
174 | 51.5k | sam_hdr_t *h; |
175 | 51.5k | if ((h = sam_hdr_init()) == NULL) return NULL; |
176 | | // copy the simple data |
177 | 51.5k | h->n_targets = 0; |
178 | 51.5k | h->ignore_sam_err = h0->ignore_sam_err; |
179 | 51.5k | h->l_text = 0; |
180 | | |
181 | | // Then the pointery stuff |
182 | | |
183 | 51.5k | if (!h0->hrecs) { |
184 | 306 | h->target_len = (uint32_t*)calloc(h0->n_targets, sizeof(uint32_t)); |
185 | 306 | if (!h->target_len) goto fail; |
186 | 306 | h->target_name = (char**)calloc(h0->n_targets, sizeof(char*)); |
187 | 306 | if (!h->target_name) goto fail; |
188 | | |
189 | 306 | int i; |
190 | 732 | for (i = 0; i < h0->n_targets; ++i) { |
191 | 426 | h->target_len[i] = h0->target_len[i]; |
192 | 426 | h->target_name[i] = strdup(h0->target_name[i]); |
193 | 426 | if (!h->target_name[i]) break; |
194 | 426 | } |
195 | 306 | h->n_targets = i; |
196 | 306 | if (i < h0->n_targets) goto fail; |
197 | | |
198 | 306 | if (h0->sdict) { |
199 | 0 | if (sam_hdr_dup_sdict(h0, h) < 0) goto fail; |
200 | 0 | } |
201 | 306 | } |
202 | | |
203 | 51.5k | if (h0->hrecs) { |
204 | 51.2k | kstring_t tmp = { 0, 0, NULL }; |
205 | 51.2k | if (sam_hrecs_rebuild_text(h0->hrecs, &tmp) != 0) { |
206 | 0 | free(ks_release(&tmp)); |
207 | 0 | goto fail; |
208 | 0 | } |
209 | | |
210 | 51.2k | h->l_text = tmp.l; |
211 | 51.2k | h->text = ks_release(&tmp); |
212 | | |
213 | 51.2k | if (sam_hdr_update_target_arrays(h, h0->hrecs, 0) != 0) |
214 | 0 | goto fail; |
215 | 51.2k | } else { |
216 | 306 | h->l_text = h0->text ? h0->l_text : 0; |
217 | 306 | h->text = hts_malloc_ps(sizeof(*h->text), h->l_text, 1); |
218 | 306 | if (!h->text) goto fail; |
219 | 306 | if (h0->text) |
220 | 306 | memcpy(h->text, h0->text, h->l_text); |
221 | 306 | h->text[h->l_text] = '\0'; |
222 | 306 | } |
223 | | |
224 | 51.5k | return h; |
225 | | |
226 | 0 | fail: |
227 | 0 | sam_hdr_destroy(h); |
228 | 0 | return NULL; |
229 | 51.5k | } |
230 | | |
231 | | sam_hdr_t *bam_hdr_read(BGZF *fp) |
232 | 3.69k | { |
233 | 3.69k | sam_hdr_t *h; |
234 | 3.69k | uint8_t buf[4]; |
235 | 3.69k | int magic_len, has_EOF; |
236 | 3.69k | int32_t i, name_len, num_names = 0; |
237 | 3.69k | size_t bufsize; |
238 | 3.69k | ssize_t bytes; |
239 | | // check EOF |
240 | 3.69k | has_EOF = bgzf_check_EOF(fp); |
241 | 3.69k | if (has_EOF < 0) { |
242 | 0 | perror("[W::bam_hdr_read] bgzf_check_EOF"); |
243 | 3.69k | } else if (has_EOF == 0) { |
244 | 3.69k | hts_log_warning("EOF marker is absent. The input is probably truncated"); |
245 | 3.69k | } |
246 | | // read "BAM1" |
247 | 3.69k | magic_len = bgzf_read(fp, buf, 4); |
248 | 3.69k | if (magic_len != 4 || memcmp(buf, "BAM\1", 4)) { |
249 | 3 | hts_log_error("Invalid BAM binary header"); |
250 | 3 | return 0; |
251 | 3 | } |
252 | 3.69k | h = sam_hdr_init(); |
253 | 3.69k | if (!h) goto nomem; |
254 | | |
255 | | // read plain text and the number of reference sequences |
256 | 3.69k | bytes = bgzf_read(fp, buf, 4); |
257 | 3.69k | if (bytes != 4) goto read_err; |
258 | 3.68k | h->l_text = le_to_u32(buf); |
259 | | |
260 | 3.68k | bufsize = h->l_text + 1; |
261 | 3.68k | if (bufsize < h->l_text) goto nomem; // so large that adding 1 overflowed |
262 | 3.68k | #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
263 | 3.68k | if (bufsize > FUZZ_ALLOC_LIMIT) goto nomem; |
264 | 3.66k | #endif |
265 | 3.66k | h->text = (char*)malloc(bufsize); |
266 | 3.66k | if (!h->text) goto nomem; |
267 | 3.66k | h->text[h->l_text] = 0; // make sure it is NULL terminated |
268 | 3.66k | bytes = bgzf_read(fp, h->text, h->l_text); |
269 | 3.66k | if (bytes != h->l_text) goto read_err; |
270 | | |
271 | 3.47k | bytes = bgzf_read(fp, &h->n_targets, 4); |
272 | 3.47k | if (bytes != 4) goto read_err; |
273 | 3.46k | if (fp->is_be) ed_swap_4p(&h->n_targets); |
274 | | |
275 | 3.46k | if (h->n_targets < 0) goto invalid; |
276 | | |
277 | | // read reference sequence names and lengths |
278 | 3.40k | #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
279 | 3.40k | if (h->n_targets > (FUZZ_ALLOC_LIMIT - bufsize)/(sizeof(char*)+sizeof(uint32_t))) |
280 | 21 | goto nomem; |
281 | 3.38k | #endif |
282 | 3.38k | if (h->n_targets > 0) { |
283 | 1.54k | h->target_name = (char**)calloc(h->n_targets, sizeof(char*)); |
284 | 1.54k | if (!h->target_name) goto nomem; |
285 | 1.54k | h->target_len = (uint32_t*)calloc(h->n_targets, sizeof(uint32_t)); |
286 | 1.54k | if (!h->target_len) goto nomem; |
287 | 1.54k | } |
288 | 1.83k | else { |
289 | 1.83k | h->target_name = NULL; |
290 | 1.83k | h->target_len = NULL; |
291 | 1.83k | } |
292 | | |
293 | 6.78k | for (i = 0; i != h->n_targets; ++i) { |
294 | 3.68k | bytes = bgzf_read(fp, &name_len, 4); |
295 | 3.68k | if (bytes != 4) goto read_err; |
296 | 3.63k | if (fp->is_be) ed_swap_4p(&name_len); |
297 | 3.63k | if (name_len <= 0) goto invalid; |
298 | | |
299 | 3.57k | h->target_name[i] = (char*)malloc(name_len); |
300 | 3.57k | if (!h->target_name[i]) goto nomem; |
301 | 3.57k | num_names++; |
302 | | |
303 | 3.57k | bytes = bgzf_read(fp, h->target_name[i], name_len); |
304 | 3.57k | if (bytes != name_len) goto read_err; |
305 | | |
306 | 3.42k | if (h->target_name[i][name_len - 1] != '\0') { |
307 | | /* Fix missing NUL-termination. Is this being too nice? |
308 | | We could alternatively bail out with an error. */ |
309 | 2.21k | char *new_name; |
310 | 2.21k | if (name_len == INT32_MAX) goto invalid; |
311 | 2.21k | new_name = realloc(h->target_name[i], name_len + 1); |
312 | 2.21k | if (new_name == NULL) goto nomem; |
313 | 2.21k | h->target_name[i] = new_name; |
314 | 2.21k | h->target_name[i][name_len] = '\0'; |
315 | 2.21k | } |
316 | | |
317 | 3.42k | bytes = bgzf_read(fp, &h->target_len[i], 4); |
318 | 3.42k | if (bytes != 4) goto read_err; |
319 | 3.40k | if (fp->is_be) ed_swap_4p(&h->target_len[i]); |
320 | 3.40k | } |
321 | 3.10k | return h; |
322 | | |
323 | 39 | nomem: |
324 | 39 | hts_log_error("Out of memory"); |
325 | 39 | goto clean; |
326 | | |
327 | 420 | read_err: |
328 | 420 | if (bytes < 0) { |
329 | 30 | hts_log_error("Error reading BGZF stream"); |
330 | 390 | } else { |
331 | 390 | hts_log_error("Truncated BAM header"); |
332 | 390 | } |
333 | 420 | goto clean; |
334 | | |
335 | 126 | invalid: |
336 | 126 | hts_log_error("Invalid BAM binary header"); |
337 | | |
338 | 585 | clean: |
339 | 585 | if (h != NULL) { |
340 | 585 | h->n_targets = num_names; // ensure we free only allocated target_names |
341 | 585 | sam_hdr_destroy(h); |
342 | 585 | } |
343 | 585 | return NULL; |
344 | 126 | } |
345 | | |
346 | | int bam_hdr_write(BGZF *fp, const sam_hdr_t *h) |
347 | 11.0k | { |
348 | 11.0k | int32_t i, name_len, x; |
349 | 11.0k | kstring_t hdr_ks = { 0, 0, NULL }; |
350 | 11.0k | char *text; |
351 | 11.0k | uint32_t l_text; |
352 | | |
353 | 11.0k | if (!h) return -1; |
354 | | |
355 | 11.0k | if (h->hrecs) { |
356 | 10.9k | if (sam_hrecs_rebuild_text(h->hrecs, &hdr_ks) != 0) return -1; |
357 | 10.9k | if (hdr_ks.l > UINT32_MAX) { |
358 | 0 | hts_log_error("Header too long for BAM format"); |
359 | 0 | free(hdr_ks.s); |
360 | 0 | return -1; |
361 | 10.9k | } else if (hdr_ks.l > INT32_MAX) { |
362 | 0 | hts_log_warning("Header too long for BAM specification (>2GB)"); |
363 | 0 | hts_log_warning("Output file may not be portable"); |
364 | 0 | } |
365 | 10.9k | text = hdr_ks.s; |
366 | 10.9k | l_text = hdr_ks.l; |
367 | 10.9k | } else { |
368 | 102 | if (h->l_text > UINT32_MAX) { |
369 | 0 | hts_log_error("Header too long for BAM format"); |
370 | 0 | return -1; |
371 | 102 | } else if (h->l_text > INT32_MAX) { |
372 | 0 | hts_log_warning("Header too long for BAM specification (>2GB)"); |
373 | 0 | hts_log_warning("Output file may not be portable"); |
374 | 0 | } |
375 | 102 | text = h->text; |
376 | 102 | l_text = h->l_text; |
377 | 102 | } |
378 | | // write "BAM1" |
379 | 11.0k | if (bgzf_write(fp, "BAM\1", 4) < 0) { free(hdr_ks.s); return -1; } |
380 | | // write plain text and the number of reference sequences |
381 | 11.0k | if (fp->is_be) { |
382 | 0 | x = ed_swap_4(l_text); |
383 | 0 | if (bgzf_write(fp, &x, 4) < 0) { free(hdr_ks.s); return -1; } |
384 | 0 | if (l_text) { |
385 | 0 | if (bgzf_write(fp, text, l_text) < 0) { free(hdr_ks.s); return -1; } |
386 | 0 | } |
387 | 0 | x = ed_swap_4(h->n_targets); |
388 | 0 | if (bgzf_write(fp, &x, 4) < 0) { free(hdr_ks.s); return -1; } |
389 | 11.0k | } else { |
390 | 11.0k | if (bgzf_write(fp, &l_text, 4) < 0) { free(hdr_ks.s); return -1; } |
391 | 11.0k | if (l_text) { |
392 | 6.23k | if (bgzf_write(fp, text, l_text) < 0) { free(hdr_ks.s); return -1; } |
393 | 6.23k | } |
394 | 11.0k | if (bgzf_write(fp, &h->n_targets, 4) < 0) { free(hdr_ks.s); return -1; } |
395 | 11.0k | } |
396 | 11.0k | free(hdr_ks.s); |
397 | | // write sequence names and lengths |
398 | 16.5k | for (i = 0; i != h->n_targets; ++i) { |
399 | 5.53k | char *p = h->target_name[i]; |
400 | 5.53k | name_len = strlen(p) + 1; |
401 | 5.53k | if (fp->is_be) { |
402 | 0 | x = ed_swap_4(name_len); |
403 | 0 | if (bgzf_write(fp, &x, 4) < 0) return -1; |
404 | 5.53k | } else { |
405 | 5.53k | if (bgzf_write(fp, &name_len, 4) < 0) return -1; |
406 | 5.53k | } |
407 | 5.53k | if (bgzf_write(fp, p, name_len) < 0) return -1; |
408 | 5.53k | if (fp->is_be) { |
409 | 0 | x = ed_swap_4(h->target_len[i]); |
410 | 0 | if (bgzf_write(fp, &x, 4) < 0) return -1; |
411 | 5.53k | } else { |
412 | 5.53k | if (bgzf_write(fp, &h->target_len[i], 4) < 0) return -1; |
413 | 5.53k | } |
414 | 5.53k | } |
415 | 11.0k | if (bgzf_flush(fp) < 0) return -1; |
416 | 11.0k | return 0; |
417 | 11.0k | } |
418 | | |
419 | | // Wrap around bam_name2id() to get the right signature for hts_name2id_f |
420 | 0 | static int bam_name2id_wrapper(void *vhdr, const char *ref) { |
421 | 0 | return bam_name2id((sam_hdr_t *) vhdr, ref); |
422 | 0 | } |
423 | | |
424 | | const char *sam_parse_region(sam_hdr_t *h, const char *s, int *tid, |
425 | 0 | hts_pos_t *beg, hts_pos_t *end, int flags) { |
426 | 0 | return hts_parse_region(s, tid, beg, end, bam_name2id_wrapper, h, flags); |
427 | 0 | } |
428 | | |
429 | | /************************* |
430 | | *** BAM alignment I/O *** |
431 | | *************************/ |
432 | | |
433 | | bam1_t *bam_init1(void) |
434 | 33.0k | { |
435 | 33.0k | return (bam1_t*)calloc(1, sizeof(bam1_t)); |
436 | 33.0k | } |
437 | | |
438 | | int sam_realloc_bam_data(bam1_t *b, size_t desired) |
439 | 1.74M | { |
440 | 1.74M | uint32_t new_m_data; |
441 | 1.74M | uint8_t *new_data; |
442 | 1.74M | new_m_data = desired; |
443 | 1.74M | kroundup32(new_m_data); // next power of 2 |
444 | 1.74M | new_m_data += 32; // reduces malloc arena migrations? |
445 | 1.74M | if (new_m_data < desired) { |
446 | 0 | errno = ENOMEM; // Not strictly true but we can't store the size |
447 | 0 | return -1; |
448 | 0 | } |
449 | 1.74M | #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION |
450 | 1.74M | if (new_m_data > FUZZ_ALLOC_LIMIT) { |
451 | 44 | errno = ENOMEM; |
452 | 44 | return -1; |
453 | 44 | } |
454 | 1.74M | #endif |
455 | 1.74M | if ((bam_get_mempolicy(b) & BAM_USER_OWNS_DATA) == 0) { |
456 | 1.74M | new_data = realloc(b->data, new_m_data); |
457 | 1.74M | } else { |
458 | 0 | if ((new_data = malloc(new_m_data)) != NULL) { |
459 | 0 | if (b->l_data > 0) |
460 | 0 | memcpy(new_data, b->data, |
461 | 0 | b->l_data < b->m_data ? b->l_data : b->m_data); |
462 | 0 | bam_set_mempolicy(b, bam_get_mempolicy(b) & (~BAM_USER_OWNS_DATA)); |
463 | 0 | } |
464 | 0 | } |
465 | 1.74M | if (!new_data) return -1; |
466 | 1.74M | b->data = new_data; |
467 | 1.74M | b->m_data = new_m_data; |
468 | 1.74M | return 0; |
469 | 1.74M | } |
470 | | |
471 | | void bam_destroy1(bam1_t *b) |
472 | 59.6M | { |
473 | 59.6M | if (b == 0) return; |
474 | 59.6M | if ((bam_get_mempolicy(b) & BAM_USER_OWNS_DATA) == 0) { |
475 | 59.6M | free(b->data); |
476 | 59.6M | if ((bam_get_mempolicy(b) & BAM_USER_OWNS_STRUCT) != 0) { |
477 | | // In case of reuse |
478 | 59.6M | b->data = NULL; |
479 | 59.6M | b->m_data = 0; |
480 | 59.6M | b->l_data = 0; |
481 | 59.6M | } |
482 | 59.6M | } |
483 | | |
484 | 59.6M | if ((bam_get_mempolicy(b) & BAM_USER_OWNS_STRUCT) == 0) |
485 | 33.0k | free(b); |
486 | 59.6M | } |
487 | | |
488 | | bam1_t *bam_copy1(bam1_t *bdst, const bam1_t *bsrc) |
489 | 15.0M | { |
490 | 15.0M | if (realloc_bam_data(bdst, bsrc->l_data) < 0) return NULL; |
491 | 15.0M | memcpy(bdst->data, bsrc->data, bsrc->l_data); // copy var-len data |
492 | 15.0M | memcpy(&bdst->core, &bsrc->core, sizeof(bsrc->core)); // copy the rest |
493 | 15.0M | bdst->l_data = bsrc->l_data; |
494 | 15.0M | bdst->id = bsrc->id; |
495 | 15.0M | return bdst; |
496 | 15.0M | } |
497 | | |
498 | | bam1_t *bam_dup1(const bam1_t *bsrc) |
499 | 0 | { |
500 | 0 | if (bsrc == NULL) return NULL; |
501 | 0 | bam1_t *bdst = bam_init1(); |
502 | 0 | if (bdst == NULL) return NULL; |
503 | 0 | if (bam_copy1(bdst, bsrc) == NULL) { |
504 | 0 | bam_destroy1(bdst); |
505 | 0 | return NULL; |
506 | 0 | } |
507 | 0 | return bdst; |
508 | 0 | } |
509 | | |
510 | | static void bam_cigar2rqlens(int n_cigar, const uint32_t *cigar, |
511 | | hts_pos_t *rlen, hts_pos_t *qlen) |
512 | 4.36k | { |
513 | 4.36k | int k; |
514 | 4.36k | *rlen = *qlen = 0; |
515 | 32.7k | for (k = 0; k < n_cigar; ++k) { |
516 | 28.3k | int type = bam_cigar_type(bam_cigar_op(cigar[k])); |
517 | 28.3k | int len = bam_cigar_oplen(cigar[k]); |
518 | 28.3k | if (type & 1) *qlen += len; |
519 | 28.3k | if (type & 2) *rlen += len; |
520 | 28.3k | } |
521 | 4.36k | } |
522 | | |
523 | | static int subtract_check_underflow(size_t length, size_t *limit) |
524 | 222M | { |
525 | 222M | if (length <= *limit) { |
526 | 222M | *limit -= length; |
527 | 222M | return 0; |
528 | 222M | } |
529 | | |
530 | 0 | return -1; |
531 | 222M | } |
532 | | |
533 | | int bam_set1(bam1_t *bam, |
534 | | size_t l_qname, const char *qname, |
535 | | uint16_t flag, int32_t tid, hts_pos_t pos, uint8_t mapq, |
536 | | size_t n_cigar, const uint32_t *cigar, |
537 | | int32_t mtid, hts_pos_t mpos, hts_pos_t isize, |
538 | | size_t l_seq, const char *seq, const char *qual, |
539 | | size_t l_aux) |
540 | 44.5M | { |
541 | | // use a default qname "*" if none is provided |
542 | 44.5M | if (l_qname == 0) { |
543 | 35.4M | l_qname = 1; |
544 | 35.4M | qname = "*"; |
545 | 35.4M | } |
546 | | |
547 | | // note: the qname is stored nul terminated and padded as described in the |
548 | | // documentation for the bam1_t struct. |
549 | 44.5M | size_t qname_nuls = 4 - l_qname % 4; |
550 | | |
551 | | // the alignment length, needed for bam_reg2bin(), is calculated as in bam_endpos(). |
552 | | // can't use bam_endpos() directly as some fields not yet set up. |
553 | 44.5M | hts_pos_t rlen = 0, qlen = 0; |
554 | 44.5M | if (!(flag & BAM_FUNMAP)) { |
555 | 0 | bam_cigar2rqlens((int)n_cigar, cigar, &rlen, &qlen); |
556 | 0 | } |
557 | 44.5M | if (rlen == 0) { |
558 | 44.5M | rlen = 1; |
559 | 44.5M | } |
560 | | |
561 | | // validate parameters |
562 | 44.5M | if (l_seq > INT32_MAX) { |
563 | | // Unfortunately b->core.l_qseq is int32, so signed. |
564 | | // Note an "(int)l_seq < 0" check is already covered by >INT32_MAX |
565 | 0 | hts_log_error("Sequence length too long"); |
566 | 0 | errno = EINVAL; |
567 | 0 | return -1; |
568 | 0 | } |
569 | | |
570 | 44.5M | if (l_qname > BAM_MAX_QNAME_LEN) { |
571 | 162 | hts_log_error("Query name too long"); |
572 | 162 | errno = EINVAL; |
573 | 162 | return -1; |
574 | 162 | } |
575 | 44.5M | if (HTS_POS_MAX - rlen <= pos) { |
576 | 0 | hts_log_error("Read ends beyond highest supported position"); |
577 | 0 | errno = EINVAL; |
578 | 0 | return -1; |
579 | 0 | } |
580 | 44.5M | if (!(flag & BAM_FUNMAP) && l_seq > 0 && n_cigar == 0) { |
581 | 0 | hts_log_error("Mapped query must have a CIGAR"); |
582 | 0 | errno = EINVAL; |
583 | 0 | return -1; |
584 | 0 | } |
585 | 44.5M | if (!(flag & BAM_FUNMAP) && l_seq > 0 && l_seq != qlen) { |
586 | 0 | hts_log_error("CIGAR and query sequence are of different length"); |
587 | 0 | errno = EINVAL; |
588 | 0 | return -1; |
589 | 0 | } |
590 | | |
591 | 44.5M | size_t limit = INT32_MAX; |
592 | 44.5M | int u = subtract_check_underflow(l_qname + qname_nuls, &limit); |
593 | 44.5M | u += subtract_check_underflow(n_cigar * 4, &limit); |
594 | 44.5M | u += subtract_check_underflow((l_seq + 1) / 2, &limit); |
595 | 44.5M | u += subtract_check_underflow(l_seq, &limit); |
596 | 44.5M | u += subtract_check_underflow(l_aux, &limit); |
597 | 44.5M | if (u != 0) { |
598 | 0 | hts_log_error("Size overflow"); |
599 | 0 | errno = EINVAL; |
600 | 0 | return -1; |
601 | 0 | } |
602 | | |
603 | | // re-allocate the data buffer as needed. |
604 | 44.5M | size_t data_len = l_qname + qname_nuls + n_cigar * 4 + (l_seq + 1) / 2 + l_seq; |
605 | 44.5M | if (realloc_bam_data(bam, hts_add_sat2(data_len, l_aux)) < 0) { |
606 | 0 | return -1; |
607 | 0 | } |
608 | | |
609 | 44.5M | bam->l_data = (int)data_len; |
610 | 44.5M | bam->core.pos = pos; |
611 | 44.5M | bam->core.tid = tid; |
612 | 44.5M | bam->core.bin = bam_reg2bin(pos, pos + rlen); |
613 | 44.5M | bam->core.qual = mapq; |
614 | 44.5M | bam->core.l_extranul = (uint8_t)(qname_nuls - 1); |
615 | 44.5M | bam->core.flag = flag; |
616 | 44.5M | bam->core.l_qname = (uint16_t)(l_qname + qname_nuls); |
617 | 44.5M | bam->core.n_cigar = (uint32_t)n_cigar; |
618 | 44.5M | bam->core.l_qseq = (int32_t)l_seq; |
619 | 44.5M | bam->core.mtid = mtid; |
620 | 44.5M | bam->core.mpos = mpos; |
621 | 44.5M | bam->core.isize = isize; |
622 | | |
623 | 44.5M | uint8_t *cp = bam->data; |
624 | 44.5M | strncpy((char *)cp, qname, l_qname); |
625 | 44.5M | int i; |
626 | 171M | for (i = 0; i < qname_nuls; i++) { |
627 | 127M | cp[l_qname + i] = '\0'; |
628 | 127M | } |
629 | 44.5M | cp += l_qname + qname_nuls; |
630 | | |
631 | 44.5M | if (n_cigar > 0) { |
632 | 0 | memcpy(cp, cigar, n_cigar * 4); |
633 | 0 | } |
634 | 44.5M | cp += n_cigar * 4; |
635 | | |
636 | 2.84G | #define NN 16 |
637 | 44.5M | const uint8_t *useq = (uint8_t *)seq; |
638 | 277M | for (i = 0; i + NN < l_seq; i += NN) { |
639 | 233M | int j; |
640 | 233M | const uint8_t *u2 = useq+i; |
641 | 2.09G | for (j = 0; j < NN/2; j++) |
642 | 1.86G | cp[j] = (seq_nt16_table[u2[j*2]]<<4) | seq_nt16_table[u2[j*2+1]]; |
643 | 233M | cp += NN/2; |
644 | 233M | } |
645 | 49.3M | for (; i + 1 < l_seq; i += 2) { |
646 | 4.75M | *cp++ = (seq_nt16_table[useq[i]] << 4) | seq_nt16_table[useq[i + 1]]; |
647 | 4.75M | } |
648 | | |
649 | 45.3M | for (; i < l_seq; i++) { |
650 | 724k | *cp++ = seq_nt16_table[(unsigned char)seq[i]] << 4; |
651 | 724k | } |
652 | | |
653 | 44.5M | if (qual) { |
654 | 1.99k | memcpy(cp, qual, l_seq); |
655 | 1.99k | } |
656 | 44.5M | else { |
657 | 44.5M | memset(cp, '\xff', l_seq); |
658 | 44.5M | } |
659 | | |
660 | 44.5M | return (int)data_len; |
661 | 44.5M | } |
662 | | |
663 | | hts_pos_t bam_cigar2qlen(int n_cigar, const uint32_t *cigar) |
664 | 14.5M | { |
665 | 14.5M | int k; |
666 | 14.5M | hts_pos_t l; |
667 | 20.2M | for (k = l = 0; k < n_cigar; ++k) |
668 | 5.66M | if (bam_cigar_type(bam_cigar_op(cigar[k]))&1) |
669 | 5.22M | l += bam_cigar_oplen(cigar[k]); |
670 | 14.5M | return l; |
671 | 14.5M | } |
672 | | |
673 | | hts_pos_t bam_cigar2rlen(int n_cigar, const uint32_t *cigar) |
674 | 260k | { |
675 | 260k | int k; |
676 | 260k | hts_pos_t l; |
677 | 20.2M | for (k = l = 0; k < n_cigar; ++k) |
678 | 20.0M | if (bam_cigar_type(bam_cigar_op(cigar[k]))&2) |
679 | 18.4M | l += bam_cigar_oplen(cigar[k]); |
680 | 260k | return l; |
681 | 260k | } |
682 | | |
683 | | hts_pos_t bam_endpos(const bam1_t *b) |
684 | 5.18k | { |
685 | 5.18k | hts_pos_t rlen = (b->core.flag & BAM_FUNMAP)? 0 : bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b)); |
686 | 5.18k | if (rlen == 0) rlen = 1; |
687 | 5.18k | return b->core.pos + rlen; |
688 | 5.18k | } |
689 | | |
690 | | // Return 0 if CIGAR is untouched, |
691 | | // 1 if CIGAR is updated with CG, |
692 | | // <0 on error |
693 | | int bam_tag2cigar(bam1_t *b, int recal_bin, int give_warning) |
694 | 407k | { |
695 | 407k | bam1_core_t *c = &b->core; |
696 | | |
697 | | // Bail out as fast as possible for the easy case |
698 | 407k | uint32_t test_CG = BAM_CSOFT_CLIP | (c->l_qseq << BAM_CIGAR_SHIFT); |
699 | 407k | if (c->n_cigar == 0 || test_CG != *bam_get_cigar(b)) |
700 | 188k | return 0; |
701 | | |
702 | | // The above isn't fool proof - we may have old CIGAR tags that aren't used, |
703 | | // but this is much less likely so do as a secondary check. |
704 | 219k | if (c->tid < 0 || c->pos < 0) |
705 | 140k | return 0; |
706 | | |
707 | | // Do we have a CG tag? |
708 | 78.7k | uint8_t *CG = bam_aux_get(b, "CG"); |
709 | 78.7k | int saved_errno = errno; |
710 | 78.7k | if (!CG) { |
711 | 72.1k | if (errno != ENOENT) return -1; // Bad aux data |
712 | 72.1k | errno = saved_errno; // restore errno on expected no-CG-tag case |
713 | 72.1k | return 0; |
714 | 72.1k | } |
715 | | |
716 | | // Now we start with the serious work migrating CG to CIGAR |
717 | 6.61k | uint32_t cigar_st, n_cigar4, CG_st, CG_en, ori_len = b->l_data, |
718 | 6.61k | *cigar0, CG_len, fake_bytes; |
719 | 6.61k | cigar0 = bam_get_cigar(b); |
720 | 6.61k | fake_bytes = c->n_cigar * 4; |
721 | 6.61k | if (CG[0] != 'B' || !(CG[1] == 'I' || CG[1] == 'i')) |
722 | 1.42k | return 0; // not of type B,I |
723 | 5.19k | CG_len = le_to_u32(CG + 2); |
724 | | // don't move if the real CIGAR length is shorter than the fake cigar length |
725 | 5.19k | if (CG_len < c->n_cigar || CG_len >= 1U<<29) return 0; |
726 | | |
727 | | // move from the CG tag to the right position |
728 | 5.18k | cigar_st = (uint8_t*)cigar0 - b->data; |
729 | 5.18k | c->n_cigar = CG_len; |
730 | 5.18k | n_cigar4 = c->n_cigar * 4; |
731 | 5.18k | CG_st = CG - b->data - 2; |
732 | 5.18k | CG_en = CG_st + 8 + n_cigar4; |
733 | 5.18k | if (possibly_expand_bam_data(b, n_cigar4 - fake_bytes) < 0) return -1; |
734 | | // we need c->n_cigar-fake_bytes bytes to swap CIGAR to the right place |
735 | 5.18k | b->l_data = b->l_data - fake_bytes + n_cigar4; |
736 | | // insert c->n_cigar-fake_bytes empty space to make room |
737 | 5.18k | memmove(b->data + cigar_st + n_cigar4, b->data + cigar_st + fake_bytes, ori_len - (cigar_st + fake_bytes)); |
738 | | // copy the real CIGAR to the right place; -fake_bytes for the fake CIGAR |
739 | 5.18k | memcpy(b->data + cigar_st, b->data + (n_cigar4 - fake_bytes) + CG_st + 8, n_cigar4); |
740 | 5.18k | if (ori_len > CG_en) // move data after the CG tag |
741 | 575 | memmove(b->data + CG_st + n_cigar4 - fake_bytes, b->data + CG_en + n_cigar4 - fake_bytes, ori_len - CG_en); |
742 | 5.18k | b->l_data -= n_cigar4 + 8; // 8: CGBI (4 bytes) and CGBI length (4) |
743 | 5.18k | if (recal_bin) |
744 | 5.18k | b->core.bin = hts_reg2bin(b->core.pos, bam_endpos(b), 14, 5); |
745 | 5.18k | if (give_warning) |
746 | 5.18k | hts_log_warning("%s encodes a CIGAR with %d operators at the CG tag", bam_get_qname(b), c->n_cigar); |
747 | | |
748 | | // Check SEQ and CIGAR consistency. (Do this after parsing the CG tag) |
749 | 5.18k | if (c->l_qseq && c->n_cigar) { |
750 | 70 | hts_pos_t ql = bam_cigar2qlen(c->n_cigar, |
751 | 70 | (uint32_t*)(b->data + c->l_qname)); |
752 | 70 | if (ql != c->l_qseq) { |
753 | 67 | hts_log_error("CIGAR and query sequence are of different length"); |
754 | 67 | return -1; |
755 | 67 | } |
756 | 70 | } |
757 | | |
758 | 5.11k | return 1; |
759 | 5.18k | } |
760 | | |
761 | | static inline int aux_type2size(uint8_t type) |
762 | 3.55M | { |
763 | 3.55M | switch (type) { |
764 | 1.73M | case 'A': case 'c': case 'C': |
765 | 1.73M | return 1; |
766 | 277k | case 's': case 'S': |
767 | 277k | return 2; |
768 | 576k | case 'i': case 'I': case 'f': |
769 | 576k | return 4; |
770 | 52.7k | case 'd': |
771 | 52.7k | return 8; |
772 | 911k | case 'Z': case 'H': case 'B': |
773 | 911k | return type; |
774 | 613 | default: |
775 | 613 | return 0; |
776 | 3.55M | } |
777 | 3.55M | } |
778 | | |
779 | | static inline int aux_type2Bsize(uint8_t type) |
780 | 477k | { |
781 | 477k | switch (type) { |
782 | 110k | case 'A': case 'c': case 'C': |
783 | 110k | return 1; |
784 | 155k | case 's': case 'S': |
785 | 155k | return 2; |
786 | 211k | case 'i': case 'I': case 'f': |
787 | 211k | return 4; |
788 | 104 | default: |
789 | 104 | return 0; |
790 | 477k | } |
791 | 477k | } |
792 | | |
793 | | static void swap_data(const bam1_core_t *c, int l_data, uint8_t *data, int is_host) |
794 | 0 | { |
795 | 0 | uint32_t *cigar = (uint32_t*)(data + c->l_qname); |
796 | 0 | uint32_t i; |
797 | 0 | for (i = 0; i < c->n_cigar; ++i) ed_swap_4p(&cigar[i]); |
798 | 0 | } |
799 | | |
800 | | // Fix bad records where qname is not terminated correctly. |
801 | 4.36k | static int fixup_missing_qname_nul(bam1_t *b) { |
802 | 4.36k | bam1_core_t *c = &b->core; |
803 | | |
804 | | // Note this is called before c->l_extranul is added to c->l_qname |
805 | 4.36k | if (c->l_extranul > 0) { |
806 | 3.40k | b->data[c->l_qname++] = '\0'; |
807 | 3.40k | c->l_extranul--; |
808 | 3.40k | } else { |
809 | 958 | if (b->l_data > INT_MAX - 4) return -1; |
810 | 958 | if (realloc_bam_data(b, b->l_data + 4) < 0) return -1; |
811 | 958 | b->l_data += 4; |
812 | 958 | b->data[c->l_qname++] = '\0'; |
813 | 958 | c->l_extranul = 3; |
814 | 958 | } |
815 | 4.36k | return 0; |
816 | 4.36k | } |
817 | | |
818 | | /* |
819 | | * Note a second interface that returns a bam pointer instead would avoid bam_copy1 |
820 | | * in multi-threaded handling. This may be worth considering for htslib2. |
821 | | */ |
822 | | int bam_read1(BGZF *fp, bam1_t *b) |
823 | 7.39k | { |
824 | 7.39k | bam1_core_t *c = &b->core; |
825 | 7.39k | int32_t block_len, ret, i; |
826 | 7.39k | uint32_t new_l_data; |
827 | 7.39k | uint8_t tmp[32], *x; |
828 | | |
829 | 7.39k | b->l_data = 0; |
830 | | |
831 | 7.39k | if ((ret = bgzf_read_small(fp, &block_len, 4)) != 4) { |
832 | 590 | if (ret == 0) return -1; // normal end-of-file |
833 | 321 | else return -2; // truncated |
834 | 590 | } |
835 | 6.80k | if (fp->is_be) |
836 | 0 | ed_swap_4p(&block_len); |
837 | 6.80k | if (block_len < 32) return -4; // block_len includes core data |
838 | 6.39k | if (fp->block_length - fp->block_offset > 32) { |
839 | | // Avoid bgzf_read and a temporary copy to a local buffer |
840 | 5.83k | x = (uint8_t *)fp->uncompressed_block + fp->block_offset; |
841 | 5.83k | fp->block_offset += 32; |
842 | 5.83k | } else { |
843 | 559 | x = tmp; |
844 | 559 | if (bgzf_read(fp, x, 32) != 32) return -3; |
845 | 559 | } |
846 | | |
847 | 5.93k | c->tid = le_to_u32(x); |
848 | 5.93k | c->pos = le_to_i32(x+4); |
849 | 5.93k | uint32_t x2 = le_to_u32(x+8); |
850 | 5.93k | c->bin = x2>>16; |
851 | 5.93k | c->qual = x2>>8&0xff; |
852 | 5.93k | c->l_qname = x2&0xff; |
853 | 5.93k | c->l_extranul = (c->l_qname%4 != 0)? (4 - c->l_qname%4) : 0; |
854 | 5.93k | uint32_t x3 = le_to_u32(x+12); |
855 | 5.93k | c->flag = x3>>16; |
856 | 5.93k | c->n_cigar = x3&0xffff; |
857 | 5.93k | c->l_qseq = le_to_u32(x+16); |
858 | 5.93k | c->mtid = le_to_u32(x+20); |
859 | 5.93k | c->mpos = le_to_i32(x+24); |
860 | 5.93k | c->isize = le_to_i32(x+28); |
861 | | |
862 | 5.93k | new_l_data = block_len - 32 + c->l_extranul; |
863 | 5.93k | if (new_l_data > INT_MAX || c->l_qseq < 0 || c->l_qname < 1) return -4; |
864 | 5.79k | if (((uint64_t) c->n_cigar << 2) + c->l_qname + c->l_extranul |
865 | 5.79k | + (((uint64_t) c->l_qseq + 1) >> 1) + c->l_qseq > (uint64_t) new_l_data) |
866 | 201 | return -4; |
867 | 5.59k | if (realloc_bam_data(b, new_l_data) < 0) return -4; |
868 | 5.55k | b->l_data = new_l_data; |
869 | | |
870 | 5.55k | if (bgzf_read_small(fp, b->data, c->l_qname) != c->l_qname) return -4; |
871 | 5.49k | if (b->data[c->l_qname - 1] != '\0') { // try to fix missing nul termination |
872 | 4.36k | if (fixup_missing_qname_nul(b) < 0) return -4; |
873 | 4.36k | } |
874 | 13.3k | for (i = 0; i < c->l_extranul; ++i) b->data[c->l_qname+i] = '\0'; |
875 | 5.49k | c->l_qname += c->l_extranul; |
876 | 5.49k | if (b->l_data < c->l_qname || |
877 | 5.49k | bgzf_read_small(fp, b->data + c->l_qname, b->l_data - c->l_qname) != b->l_data - c->l_qname) |
878 | 206 | return -4; |
879 | 5.29k | if (fp->is_be) swap_data(c, b->l_data, b->data, 0); |
880 | | |
881 | 5.29k | int t2c = bam_tag2cigar(b, 0, 0); |
882 | 5.29k | if (t2c < 0) |
883 | 52 | return -4; |
884 | | |
885 | | // TODO: consider making this conditional |
886 | 5.23k | if (c->n_cigar > 0) { // recompute "bin" and check CIGAR-qlen consistency |
887 | 4.36k | hts_pos_t rlen, qlen; |
888 | 4.36k | bam_cigar2rqlens(c->n_cigar, bam_get_cigar(b), &rlen, &qlen); |
889 | 4.36k | if ((b->core.flag & BAM_FUNMAP) || rlen == 0) rlen = 1; |
890 | 4.36k | b->core.bin = hts_reg2bin(b->core.pos, b->core.pos + rlen, 14, 5); |
891 | | // Sanity check for broken CIGAR alignments |
892 | 4.36k | if (t2c == 0 && c->l_qseq > 0 && |
893 | 3.04k | !(c->flag & BAM_FUNMAP) && qlen != c->l_qseq) { |
894 | 62 | hts_log_error("CIGAR and query sequence lengths differ for %s", |
895 | 62 | bam_get_qname(b)); |
896 | 62 | return -4; |
897 | 62 | } |
898 | 4.36k | } |
899 | | |
900 | 5.17k | return 4 + block_len; |
901 | 5.23k | } |
902 | | |
903 | | int bam_write1(BGZF *fp, const bam1_t *b) |
904 | 15.0M | { |
905 | 15.0M | const bam1_core_t *c = &b->core; |
906 | 15.0M | uint32_t x[8], block_len = b->l_data - c->l_extranul + 32, y; |
907 | 15.0M | int i, ok; |
908 | 15.0M | if (c->l_qname - c->l_extranul > BAM_MAX_QNAME_LEN + 1) { // +1 for NUL |
909 | 2 | hts_log_error("QNAME \"%s\" is longer than 254 characters", bam_get_qname(b)); |
910 | 2 | errno = EOVERFLOW; |
911 | 2 | return -1; |
912 | 2 | } |
913 | 15.0M | if (c->n_cigar > 0xffff) block_len += 16; // "16" for "CGBI", 4-byte tag length and 8-byte fake CIGAR |
914 | 15.0M | if (c->pos > INT_MAX || |
915 | 15.0M | c->mpos > INT_MAX || |
916 | 15.0M | c->isize < INT_MIN || c->isize > INT_MAX) { |
917 | 997 | hts_log_error("Positional data is too large for BAM format"); |
918 | 997 | return -1; |
919 | 997 | } |
920 | 15.0M | x[0] = c->tid; |
921 | 15.0M | x[1] = c->pos; |
922 | 15.0M | x[2] = (uint32_t)c->bin<<16 | c->qual<<8 | (c->l_qname - c->l_extranul); |
923 | 15.0M | if (c->n_cigar > 0xffff) x[3] = (uint32_t)c->flag << 16 | 2; |
924 | 15.0M | else x[3] = (uint32_t)c->flag << 16 | (c->n_cigar & 0xffff); |
925 | 15.0M | x[4] = c->l_qseq; |
926 | 15.0M | x[5] = c->mtid; |
927 | 15.0M | x[6] = c->mpos; |
928 | 15.0M | x[7] = c->isize; |
929 | 15.0M | ok = (bgzf_flush_try(fp, 4 + block_len) >= 0); |
930 | 15.0M | if (fp->is_be) { |
931 | 0 | for (i = 0; i < 8; ++i) ed_swap_4p(x + i); |
932 | 0 | y = block_len; |
933 | 0 | if (ok) ok = (bgzf_write_small(fp, ed_swap_4p(&y), 4) >= 0); |
934 | 0 | swap_data(c, b->l_data, b->data, 1); |
935 | 15.0M | } else { |
936 | 15.0M | if (ok) ok = (bgzf_write_small(fp, &block_len, 4) >= 0); |
937 | 15.0M | } |
938 | 15.0M | if (ok) ok = (bgzf_write_small(fp, x, 32) >= 0); |
939 | 15.0M | if (ok) ok = (bgzf_write_small(fp, b->data, c->l_qname - c->l_extranul) >= 0); |
940 | 15.0M | if (c->n_cigar <= 0xffff) { // no long CIGAR; write normally |
941 | 15.0M | if (ok) ok = (bgzf_write_small(fp, b->data + c->l_qname, b->l_data - c->l_qname) >= 0); |
942 | 15.0M | } else { // with long CIGAR, insert a fake CIGAR record and move the real CIGAR to the CG:B,I tag |
943 | 32 | uint8_t buf[8]; |
944 | 32 | uint32_t cigar_st, cigar_en, cigar[2]; |
945 | 32 | hts_pos_t cigreflen = bam_cigar2rlen(c->n_cigar, bam_get_cigar(b)); |
946 | 32 | if (cigreflen >= (1<<28)) { |
947 | | // Length of reference covered is greater than the biggest |
948 | | // CIGAR operation currently allowed. |
949 | 5 | hts_log_error("Record %s with %d CIGAR ops and ref length %"PRIhts_pos |
950 | 5 | " cannot be written in BAM. Try writing SAM or CRAM instead.\n", |
951 | 5 | bam_get_qname(b), c->n_cigar, cigreflen); |
952 | 5 | if (fp->is_be) swap_data(c, b->l_data, b->data, 0); |
953 | 5 | return -1; |
954 | 5 | } |
955 | 27 | cigar_st = (uint8_t*)bam_get_cigar(b) - b->data; |
956 | 27 | cigar_en = cigar_st + c->n_cigar * 4; |
957 | 27 | cigar[0] = (uint32_t)c->l_qseq << 4 | BAM_CSOFT_CLIP; |
958 | 27 | cigar[1] = (uint32_t)cigreflen << 4 | BAM_CREF_SKIP; |
959 | 27 | u32_to_le(cigar[0], buf); |
960 | 27 | u32_to_le(cigar[1], buf + 4); |
961 | 27 | if (ok) ok = (bgzf_write_small(fp, buf, 8) >= 0); // write cigar: <read_length>S<ref_length>N |
962 | 27 | if (ok) ok = (bgzf_write_small(fp, &b->data[cigar_en], b->l_data - cigar_en) >= 0); // write data after CIGAR |
963 | 27 | if (ok) ok = (bgzf_write_small(fp, "CGBI", 4) >= 0); // write CG:B,I |
964 | 27 | u32_to_le(c->n_cigar, buf); |
965 | 27 | if (ok) ok = (bgzf_write_small(fp, buf, 4) >= 0); // write the true CIGAR length |
966 | 27 | if (ok) ok = (bgzf_write_small(fp, &b->data[cigar_st], c->n_cigar * 4) >= 0); // write the real CIGAR |
967 | 27 | } |
968 | 15.0M | if (fp->is_be) swap_data(c, b->l_data, b->data, 0); |
969 | 15.0M | return ok? 4 + block_len : -1; |
970 | 15.0M | } |
971 | | |
972 | | /* |
973 | | * Write a BAM file and append to the in-memory index simultaneously. |
974 | | */ |
975 | 15.0M | static int bam_write_idx1(htsFile *fp, const sam_hdr_t *h, const bam1_t *b) { |
976 | 15.0M | BGZF *bfp = fp->fp.bgzf; |
977 | | |
978 | 15.0M | if (!fp->idx) |
979 | 15.0M | return bam_write1(bfp, b); |
980 | | |
981 | 0 | uint32_t block_len = b->l_data - b->core.l_extranul + 32; |
982 | 0 | if (bgzf_flush_try(bfp, 4 + block_len) < 0) |
983 | 0 | return -1; |
984 | 0 | if (!bfp->mt) |
985 | 0 | hts_idx_amend_last(fp->idx, bgzf_tell(bfp)); |
986 | |
|
987 | 0 | int ret = bam_write1(bfp, b); |
988 | 0 | if (ret < 0) |
989 | 0 | return -1; |
990 | | |
991 | 0 | if (bgzf_idx_push(bfp, fp->idx, b->core.tid, b->core.pos, bam_endpos(b), bgzf_tell(bfp), !(b->core.flag&BAM_FUNMAP)) < 0) { |
992 | 0 | hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed", |
993 | 0 | bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), b->core.flag, b->core.pos+1); |
994 | 0 | ret = -1; |
995 | 0 | } |
996 | |
|
997 | 0 | return ret; |
998 | 0 | } |
999 | | |
1000 | | /* |
1001 | | * Set the qname in a BAM record |
1002 | | */ |
1003 | | int bam_set_qname(bam1_t *rec, const char *qname) |
1004 | 0 | { |
1005 | 0 | if (!rec) return -1; |
1006 | 0 | if (!qname || !*qname) return -1; |
1007 | | |
1008 | 0 | size_t old_len = rec->core.l_qname; |
1009 | 0 | size_t new_len = strlen(qname) + 1; |
1010 | 0 | if (new_len < 1 || new_len > 255) return -1; |
1011 | | |
1012 | 0 | int extranul = (new_len%4 != 0) ? (4 - new_len%4) : 0; |
1013 | |
|
1014 | 0 | size_t new_data_len = rec->l_data - old_len + new_len + extranul; |
1015 | 0 | if (realloc_bam_data(rec, new_data_len) < 0) return -1; |
1016 | | |
1017 | | // Make room |
1018 | 0 | if (new_len + extranul != rec->core.l_qname) |
1019 | 0 | memmove(rec->data + new_len + extranul, rec->data + rec->core.l_qname, rec->l_data - rec->core.l_qname); |
1020 | | // Copy in new name and pad if needed |
1021 | 0 | memcpy(rec->data, qname, new_len); |
1022 | 0 | int n; |
1023 | 0 | for (n = 0; n < extranul; n++) rec->data[new_len + n] = '\0'; |
1024 | |
|
1025 | 0 | rec->l_data = new_data_len; |
1026 | 0 | rec->core.l_qname = new_len + extranul; |
1027 | 0 | rec->core.l_extranul = extranul; |
1028 | |
|
1029 | 0 | return 0; |
1030 | 0 | } |
1031 | | |
1032 | | /******************** |
1033 | | *** BAM indexing *** |
1034 | | ********************/ |
1035 | | |
1036 | | static hts_idx_t *sam_index(htsFile *fp, int min_shift) |
1037 | 0 | { |
1038 | 0 | int n_lvls, i, fmt, ret; |
1039 | 0 | bam1_t *b; |
1040 | 0 | hts_idx_t *idx; |
1041 | 0 | sam_hdr_t *h; |
1042 | 0 | h = sam_hdr_read(fp); |
1043 | 0 | if (h == NULL) return NULL; |
1044 | 0 | if (min_shift > 0) { |
1045 | 0 | hts_pos_t max_len = 0; |
1046 | 0 | for (i = 0; i < h->n_targets; ++i) { |
1047 | 0 | hts_pos_t len = sam_hdr_tid2len(h, i); |
1048 | 0 | if (max_len < len) max_len = len; |
1049 | 0 | } |
1050 | 0 | n_lvls = 0; |
1051 | 0 | hts_adjust_csi_settings(max_len, &min_shift, &n_lvls); |
1052 | 0 | fmt = HTS_FMT_CSI; |
1053 | 0 | } else min_shift = 14, n_lvls = 5, fmt = HTS_FMT_BAI; |
1054 | 0 | idx = hts_idx_init(h->n_targets, fmt, bgzf_tell(fp->fp.bgzf), min_shift, n_lvls); |
1055 | 0 | b = bam_init1(); |
1056 | 0 | while ((ret = sam_read1(fp, h, b)) >= 0) { |
1057 | 0 | ret = hts_idx_push(idx, b->core.tid, b->core.pos, bam_endpos(b), bgzf_tell(fp->fp.bgzf), !(b->core.flag&BAM_FUNMAP)); |
1058 | 0 | if (ret < 0) { // unsorted or doesn't fit |
1059 | 0 | hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed", bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), b->core.flag, b->core.pos+1); |
1060 | 0 | goto err; |
1061 | 0 | } |
1062 | 0 | } |
1063 | 0 | if (ret < -1) goto err; // corrupted BAM file |
1064 | | |
1065 | 0 | if (hts_idx_finish(idx, bgzf_tell(fp->fp.bgzf)) != 0) |
1066 | 0 | goto err; |
1067 | 0 | sam_hdr_destroy(h); |
1068 | 0 | bam_destroy1(b); |
1069 | 0 | return idx; |
1070 | | |
1071 | 0 | err: |
1072 | 0 | bam_destroy1(b); |
1073 | 0 | hts_idx_destroy(idx); |
1074 | 0 | sam_hdr_destroy(h); |
1075 | 0 | return NULL; |
1076 | 0 | } |
1077 | | |
1078 | | int sam_index_build3(const char *fn, const char *fnidx, int min_shift, int nthreads) |
1079 | 0 | { |
1080 | 0 | hts_idx_t *idx; |
1081 | 0 | htsFile *fp; |
1082 | 0 | int ret = 0; |
1083 | |
|
1084 | 0 | if ((fp = hts_open(fn, "r")) == 0) return -2; |
1085 | 0 | if (nthreads) |
1086 | 0 | hts_set_threads(fp, nthreads); |
1087 | |
|
1088 | 0 | switch (fp->format.format) { |
1089 | 0 | case cram: |
1090 | |
|
1091 | 0 | ret = cram_index_build(fp->fp.cram, fn, fnidx); |
1092 | 0 | break; |
1093 | | |
1094 | 0 | case bam: |
1095 | 0 | case sam: |
1096 | 0 | if (fp->format.compression != bgzf) { |
1097 | 0 | hts_log_error("%s file \"%s\" not BGZF compressed", |
1098 | 0 | fp->format.format == bam ? "BAM" : "SAM", fn); |
1099 | 0 | ret = -1; |
1100 | 0 | break; |
1101 | 0 | } |
1102 | 0 | idx = sam_index(fp, min_shift); |
1103 | 0 | if (idx) { |
1104 | 0 | ret = hts_idx_save_as(idx, fn, fnidx, (min_shift > 0)? HTS_FMT_CSI : HTS_FMT_BAI); |
1105 | 0 | if (ret < 0) ret = -4; |
1106 | 0 | hts_idx_destroy(idx); |
1107 | 0 | } |
1108 | 0 | else ret = -1; |
1109 | 0 | break; |
1110 | | |
1111 | 0 | default: |
1112 | 0 | ret = -3; |
1113 | 0 | break; |
1114 | 0 | } |
1115 | 0 | hts_close(fp); |
1116 | |
|
1117 | 0 | return ret; |
1118 | 0 | } |
1119 | | |
1120 | | int sam_index_build2(const char *fn, const char *fnidx, int min_shift) |
1121 | 0 | { |
1122 | 0 | return sam_index_build3(fn, fnidx, min_shift, 0); |
1123 | 0 | } |
1124 | | |
1125 | | int sam_index_build(const char *fn, int min_shift) |
1126 | 0 | { |
1127 | 0 | return sam_index_build3(fn, NULL, min_shift, 0); |
1128 | 0 | } |
1129 | | |
1130 | | // Provide bam_index_build() symbol for binary compatibility with earlier HTSlib |
1131 | | #undef bam_index_build |
1132 | | int bam_index_build(const char *fn, int min_shift) |
1133 | 0 | { |
1134 | 0 | return sam_index_build2(fn, NULL, min_shift); |
1135 | 0 | } |
1136 | | |
1137 | | // Initialise fp->idx for the current format type. |
1138 | | // This must be called after the header has been written but no other data. |
1139 | 0 | int sam_idx_init(htsFile *fp, sam_hdr_t *h, int min_shift, const char *fnidx) { |
1140 | 0 | fp->fnidx = fnidx; |
1141 | 0 | if (fp->format.format == bam || fp->format.format == bcf || |
1142 | 0 | (fp->format.format == sam && fp->format.compression == bgzf)) { |
1143 | 0 | int n_lvls, fmt = HTS_FMT_CSI; |
1144 | 0 | if (min_shift > 0) { |
1145 | 0 | int64_t max_len = 0; |
1146 | 0 | int i; |
1147 | 0 | for (i = 0; i < h->n_targets; ++i) |
1148 | 0 | if (max_len < h->target_len[i]) max_len = h->target_len[i]; |
1149 | 0 | n_lvls = 0; |
1150 | 0 | hts_adjust_csi_settings(max_len, &min_shift, &n_lvls); |
1151 | 0 | } else min_shift = 14, n_lvls = 5, fmt = HTS_FMT_BAI; |
1152 | |
|
1153 | 0 | fp->idx = hts_idx_init(h->n_targets, fmt, bgzf_tell(fp->fp.bgzf), min_shift, n_lvls); |
1154 | 0 | return fp->idx ? 0 : -1; |
1155 | 0 | } |
1156 | | |
1157 | 0 | if (fp->format.format == cram) { |
1158 | 0 | fp->fp.cram->idxfp = bgzf_open(fnidx, "wg"); |
1159 | 0 | return fp->fp.cram->idxfp ? 0 : -1; |
1160 | 0 | } |
1161 | | |
1162 | 0 | return -1; |
1163 | 0 | } |
1164 | | |
1165 | | // Finishes an index. Call after the last record has been written. |
1166 | | // Returns 0 on success, <0 on failure. |
1167 | 0 | int sam_idx_save(htsFile *fp) { |
1168 | 0 | if (fp->format.format == bam || fp->format.format == bcf || |
1169 | 0 | fp->format.format == vcf || fp->format.format == sam) { |
1170 | 0 | int ret; |
1171 | 0 | if ((ret = sam_state_destroy(fp)) < 0) { |
1172 | 0 | errno = -ret; |
1173 | 0 | return -1; |
1174 | 0 | } |
1175 | 0 | if (!fp->is_bgzf || bgzf_flush(fp->fp.bgzf) < 0) |
1176 | 0 | return -1; |
1177 | 0 | hts_idx_amend_last(fp->idx, bgzf_tell(fp->fp.bgzf)); |
1178 | |
|
1179 | 0 | if (hts_idx_finish(fp->idx, bgzf_tell(fp->fp.bgzf)) < 0) |
1180 | 0 | return -1; |
1181 | | |
1182 | 0 | return hts_idx_save_but_not_close(fp->idx, fp->fnidx, hts_idx_fmt(fp->idx)); |
1183 | |
|
1184 | 0 | } else if (fp->format.format == cram) { |
1185 | | // flushed and closed by cram_close |
1186 | 0 | } |
1187 | | |
1188 | 0 | return 0; |
1189 | 0 | } |
1190 | | |
1191 | | static int sam_readrec(BGZF *ignored, void *fpv, void *bv, int *tid, hts_pos_t *beg, hts_pos_t *end) |
1192 | 0 | { |
1193 | 0 | htsFile *fp = (htsFile *)fpv; |
1194 | 0 | bam1_t *b = bv; |
1195 | 0 | fp->line.l = 0; |
1196 | 0 | int ret = sam_read1(fp, fp->bam_header, b); |
1197 | 0 | if (ret >= 0) { |
1198 | 0 | *tid = b->core.tid; |
1199 | 0 | *beg = b->core.pos; |
1200 | 0 | *end = bam_endpos(b); |
1201 | 0 | } |
1202 | 0 | return ret; |
1203 | 0 | } |
1204 | | |
1205 | | // This is used only with read_rest=1 iterators, so need not set tid/beg/end. |
1206 | | static int sam_readrec_rest(BGZF *ignored, void *fpv, void *bv, int *tid, hts_pos_t *beg, hts_pos_t *end) |
1207 | 0 | { |
1208 | 0 | htsFile *fp = (htsFile *)fpv; |
1209 | 0 | bam1_t *b = bv; |
1210 | 0 | fp->line.l = 0; |
1211 | 0 | int ret = sam_read1(fp, fp->bam_header, b); |
1212 | 0 | return ret; |
1213 | 0 | } |
1214 | | |
1215 | | static uint8_t *bam_aux_getZ(const bam1_t *b, const char tag[2]); |
1216 | | |
1217 | | // Used by bam_sym_lookup. Originated in samtools/sam.c |
1218 | | // Returns 0 on success, -1 on not found, and <-1 on error |
1219 | | static int bam_get_library(const bam_hdr_t *h, const bam1_t *b, kstring_t *s) |
1220 | 0 | { |
1221 | | // initialise or clear, for early exits |
1222 | 0 | if (kputsn("", 0, ks_clear(s)) < 0) |
1223 | 0 | return -2; |
1224 | | |
1225 | 0 | const char *rg = (char *)bam_aux_getZ(b, "RG"); |
1226 | 0 | if (!rg) |
1227 | 0 | return -1; |
1228 | | |
1229 | | // sam_hdr_find_tag_id has the same 0/-1/-2 return values. |
1230 | | // NB: it doesn't modify s on error. |
1231 | 0 | return sam_hdr_find_tag_id((bam_hdr_t *)h, "RG", "ID", rg+1, "LB", s); |
1232 | 0 | } |
1233 | | |
1234 | | |
1235 | | // Bam record pointer and SAM header combined |
1236 | | typedef struct { |
1237 | | const sam_hdr_t *h; |
1238 | | const bam1_t *b; |
1239 | | } hb_pair; |
1240 | | |
1241 | | // Looks up variable names in str and replaces them with their value. |
1242 | | // Also supports aux tags. |
1243 | | // |
1244 | | // Note the expression parser deliberately overallocates str size so it |
1245 | | // is safe to use memcmp over strcmp. |
1246 | | static int bam_sym_lookup(void *data, char *str, char **end, |
1247 | 0 | hts_expr_val_t *res) { |
1248 | 0 | hb_pair *hb = (hb_pair *)data; |
1249 | 0 | const bam1_t *b = hb->b; |
1250 | |
|
1251 | 0 | res->is_str = 0; |
1252 | 0 | switch(*str) { |
1253 | 0 | case 'c': |
1254 | 0 | if (memcmp(str, "cigar", 5) == 0) { |
1255 | 0 | *end = str+5; |
1256 | 0 | res->is_str = 1; |
1257 | 0 | ks_clear(&res->s); |
1258 | 0 | uint32_t *cigar = bam_get_cigar(b); |
1259 | 0 | int i, n = b->core.n_cigar, r = 0; |
1260 | 0 | if (n) { |
1261 | 0 | for (i = 0; i < n; i++) { |
1262 | 0 | r |= kputw (bam_cigar_oplen(cigar[i]), &res->s) < 0; |
1263 | 0 | r |= kputc_(bam_cigar_opchr(cigar[i]), &res->s) < 0; |
1264 | 0 | } |
1265 | 0 | r |= kputs("", &res->s) < 0; |
1266 | 0 | } else { |
1267 | 0 | r |= kputs("*", &res->s) < 0; |
1268 | 0 | } |
1269 | 0 | return r ? -1 : 0; |
1270 | 0 | } |
1271 | 0 | break; |
1272 | | |
1273 | 0 | case 'e': |
1274 | 0 | if (memcmp(str, "endpos", 6) == 0) { |
1275 | 0 | *end = str+6; |
1276 | 0 | res->d = bam_endpos(b); |
1277 | 0 | return 0; |
1278 | 0 | } |
1279 | 0 | break; |
1280 | | |
1281 | 0 | case 'f': |
1282 | 0 | if (memcmp(str, "flag", 4) == 0) { |
1283 | 0 | str = *end = str+4; |
1284 | 0 | if (*str != '.') { |
1285 | 0 | res->d = b->core.flag; |
1286 | 0 | return 0; |
1287 | 0 | } else { |
1288 | 0 | str++; |
1289 | 0 | if (!memcmp(str, "paired", 6)) { |
1290 | 0 | *end = str+6; |
1291 | 0 | res->d = b->core.flag & BAM_FPAIRED; |
1292 | 0 | return 0; |
1293 | 0 | } else if (!memcmp(str, "proper_pair", 11)) { |
1294 | 0 | *end = str+11; |
1295 | 0 | res->d = b->core.flag & BAM_FPROPER_PAIR; |
1296 | 0 | return 0; |
1297 | 0 | } else if (!memcmp(str, "unmap", 5)) { |
1298 | 0 | *end = str+5; |
1299 | 0 | res->d = b->core.flag & BAM_FUNMAP; |
1300 | 0 | return 0; |
1301 | 0 | } else if (!memcmp(str, "munmap", 6)) { |
1302 | 0 | *end = str+6; |
1303 | 0 | res->d = b->core.flag & BAM_FMUNMAP; |
1304 | 0 | return 0; |
1305 | 0 | } else if (!memcmp(str, "reverse", 7)) { |
1306 | 0 | *end = str+7; |
1307 | 0 | res->d = b->core.flag & BAM_FREVERSE; |
1308 | 0 | return 0; |
1309 | 0 | } else if (!memcmp(str, "mreverse", 8)) { |
1310 | 0 | *end = str+8; |
1311 | 0 | res->d = b->core.flag & BAM_FMREVERSE; |
1312 | 0 | return 0; |
1313 | 0 | } else if (!memcmp(str, "read1", 5)) { |
1314 | 0 | *end = str+5; |
1315 | 0 | res->d = b->core.flag & BAM_FREAD1; |
1316 | 0 | return 0; |
1317 | 0 | } else if (!memcmp(str, "read2", 5)) { |
1318 | 0 | *end = str+5; |
1319 | 0 | res->d = b->core.flag & BAM_FREAD2; |
1320 | 0 | return 0; |
1321 | 0 | } else if (!memcmp(str, "secondary", 9)) { |
1322 | 0 | *end = str+9; |
1323 | 0 | res->d = b->core.flag & BAM_FSECONDARY; |
1324 | 0 | return 0; |
1325 | 0 | } else if (!memcmp(str, "qcfail", 6)) { |
1326 | 0 | *end = str+6; |
1327 | 0 | res->d = b->core.flag & BAM_FQCFAIL; |
1328 | 0 | return 0; |
1329 | 0 | } else if (!memcmp(str, "dup", 3)) { |
1330 | 0 | *end = str+3; |
1331 | 0 | res->d = b->core.flag & BAM_FDUP; |
1332 | 0 | return 0; |
1333 | 0 | } else if (!memcmp(str, "supplementary", 13)) { |
1334 | 0 | *end = str+13; |
1335 | 0 | res->d = b->core.flag & BAM_FSUPPLEMENTARY; |
1336 | 0 | return 0; |
1337 | 0 | } else { |
1338 | 0 | hts_log_error("Unrecognised flag string"); |
1339 | 0 | return -1; |
1340 | 0 | } |
1341 | 0 | } |
1342 | 0 | } |
1343 | 0 | break; |
1344 | | |
1345 | 0 | case 'h': |
1346 | 0 | if (memcmp(str, "hclen", 5) == 0) { |
1347 | 0 | int hclen = 0; |
1348 | 0 | uint32_t *cigar = bam_get_cigar(b); |
1349 | 0 | uint32_t ncigar = b->core.n_cigar; |
1350 | | |
1351 | | // left |
1352 | 0 | if (ncigar > 0 && bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP) |
1353 | 0 | hclen = bam_cigar_oplen(cigar[0]); |
1354 | | |
1355 | | // right |
1356 | 0 | if (ncigar > 1 && bam_cigar_op(cigar[ncigar-1]) == BAM_CHARD_CLIP) |
1357 | 0 | hclen += bam_cigar_oplen(cigar[ncigar-1]); |
1358 | |
|
1359 | 0 | *end = str+5; |
1360 | 0 | res->d = hclen; |
1361 | 0 | return 0; |
1362 | 0 | } |
1363 | 0 | break; |
1364 | | |
1365 | 0 | case 'l': |
1366 | 0 | if (memcmp(str, "library", 7) == 0) { |
1367 | 0 | *end = str+7; |
1368 | 0 | res->is_str = 1; |
1369 | 0 | return (bam_get_library(hb->h, b, &res->s) < -1) ? -1 : 0; |
1370 | 0 | } |
1371 | 0 | break; |
1372 | | |
1373 | 0 | case 'm': |
1374 | 0 | if (memcmp(str, "mapq", 4) == 0) { |
1375 | 0 | *end = str+4; |
1376 | 0 | res->d = b->core.qual; |
1377 | 0 | return 0; |
1378 | 0 | } else if (memcmp(str, "mpos", 4) == 0) { |
1379 | 0 | *end = str+4; |
1380 | 0 | res->d = b->core.mpos+1; |
1381 | 0 | return 0; |
1382 | 0 | } else if (memcmp(str, "mrname", 6) == 0) { |
1383 | 0 | *end = str+6; |
1384 | 0 | res->is_str = 1; |
1385 | 0 | const char *rn = sam_hdr_tid2name(hb->h, b->core.mtid); |
1386 | 0 | return kputs(rn ? rn : "*", ks_clear(&res->s)) >= 0 ? 0 : -1; |
1387 | 0 | } else if (memcmp(str, "mrefid", 6) == 0) { |
1388 | 0 | *end = str+6; |
1389 | 0 | res->d = b->core.mtid; |
1390 | 0 | return 0; |
1391 | 0 | } |
1392 | 0 | break; |
1393 | | |
1394 | 0 | case 'n': |
1395 | 0 | if (memcmp(str, "ncigar", 6) == 0) { |
1396 | 0 | *end = str+6; |
1397 | 0 | res->d = b->core.n_cigar; |
1398 | 0 | return 0; |
1399 | 0 | } |
1400 | 0 | break; |
1401 | | |
1402 | 0 | case 'p': |
1403 | 0 | if (memcmp(str, "pos", 3) == 0) { |
1404 | 0 | *end = str+3; |
1405 | 0 | res->d = b->core.pos+1; |
1406 | 0 | return 0; |
1407 | 0 | } else if (memcmp(str, "pnext", 5) == 0) { |
1408 | 0 | *end = str+5; |
1409 | 0 | res->d = b->core.mpos+1; |
1410 | 0 | return 0; |
1411 | 0 | } |
1412 | 0 | break; |
1413 | | |
1414 | 0 | case 'q': |
1415 | 0 | if (memcmp(str, "qlen", 4) == 0) { |
1416 | 0 | *end = str+4; |
1417 | 0 | res->d = bam_cigar2qlen(b->core.n_cigar, bam_get_cigar(b)); |
1418 | 0 | return 0; |
1419 | 0 | } else if (memcmp(str, "qname", 5) == 0) { |
1420 | 0 | *end = str+5; |
1421 | 0 | res->is_str = 1; |
1422 | 0 | return kputs(bam_get_qname(b), ks_clear(&res->s)) >= 0 ? 0 : -1; |
1423 | 0 | } else if (memcmp(str, "qual", 4) == 0) { |
1424 | 0 | *end = str+4; |
1425 | 0 | ks_clear(&res->s); |
1426 | 0 | if (ks_resize(&res->s, b->core.l_qseq+1) < 0) |
1427 | 0 | return -1; |
1428 | 0 | memcpy(res->s.s, bam_get_qual(b), b->core.l_qseq); |
1429 | 0 | res->s.l = b->core.l_qseq; |
1430 | 0 | res->s.s[res->s.l] = 0; |
1431 | 0 | res->is_str = 1; |
1432 | 0 | return 0; |
1433 | 0 | } |
1434 | 0 | break; |
1435 | | |
1436 | 0 | case 'r': |
1437 | 0 | if (memcmp(str, "rlen", 4) == 0) { |
1438 | 0 | *end = str+4; |
1439 | 0 | res->d = bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b)); |
1440 | 0 | return 0; |
1441 | 0 | } else if (memcmp(str, "rname", 5) == 0) { |
1442 | 0 | *end = str+5; |
1443 | 0 | res->is_str = 1; |
1444 | 0 | const char *rn = sam_hdr_tid2name(hb->h, b->core.tid); |
1445 | 0 | return kputs(rn ? rn : "*", ks_clear(&res->s)) >= 0 ? 0 : -1; |
1446 | 0 | } else if (memcmp(str, "rnext", 5) == 0) { |
1447 | 0 | *end = str+5; |
1448 | 0 | res->is_str = 1; |
1449 | 0 | const char *rn = sam_hdr_tid2name(hb->h, b->core.mtid); |
1450 | 0 | return kputs(rn ? rn : "*", ks_clear(&res->s)) >= 0 ? 0 : -1; |
1451 | 0 | } else if (memcmp(str, "refid", 5) == 0) { |
1452 | 0 | *end = str+5; |
1453 | 0 | res->d = b->core.tid; |
1454 | 0 | return 0; |
1455 | 0 | } |
1456 | 0 | break; |
1457 | | |
1458 | 0 | case 's': |
1459 | 0 | if (memcmp(str, "seq", 3) == 0) { |
1460 | 0 | *end = str+3; |
1461 | 0 | ks_clear(&res->s); |
1462 | 0 | if (ks_resize(&res->s, b->core.l_qseq+1) < 0) |
1463 | 0 | return -1; |
1464 | 0 | nibble2base(bam_get_seq(b), res->s.s, b->core.l_qseq); |
1465 | 0 | res->s.s[b->core.l_qseq] = 0; |
1466 | 0 | res->s.l = b->core.l_qseq; |
1467 | 0 | res->is_str = 1; |
1468 | 0 | return 0; |
1469 | 0 | } else if (memcmp(str, "sclen", 5) == 0) { |
1470 | 0 | int sclen = 0; |
1471 | 0 | uint32_t *cigar = bam_get_cigar(b); |
1472 | 0 | int ncigar = b->core.n_cigar; |
1473 | 0 | int left = 0; |
1474 | | |
1475 | | // left |
1476 | 0 | if (ncigar > 0 |
1477 | 0 | && bam_cigar_op(cigar[0]) == BAM_CSOFT_CLIP) |
1478 | 0 | left = 0, sclen += bam_cigar_oplen(cigar[0]); |
1479 | 0 | else if (ncigar > 1 |
1480 | 0 | && bam_cigar_op(cigar[0]) == BAM_CHARD_CLIP |
1481 | 0 | && bam_cigar_op(cigar[1]) == BAM_CSOFT_CLIP) |
1482 | 0 | left = 1, sclen += bam_cigar_oplen(cigar[1]); |
1483 | | |
1484 | | // right |
1485 | 0 | if (ncigar-1 > left |
1486 | 0 | && bam_cigar_op(cigar[ncigar-1]) == BAM_CSOFT_CLIP) |
1487 | 0 | sclen += bam_cigar_oplen(cigar[ncigar-1]); |
1488 | 0 | else if (ncigar-2 > left |
1489 | 0 | && bam_cigar_op(cigar[ncigar-1]) == BAM_CHARD_CLIP |
1490 | 0 | && bam_cigar_op(cigar[ncigar-2]) == BAM_CSOFT_CLIP) |
1491 | 0 | sclen += bam_cigar_oplen(cigar[ncigar-2]); |
1492 | |
|
1493 | 0 | *end = str+5; |
1494 | 0 | res->d = sclen; |
1495 | 0 | return 0; |
1496 | 0 | } |
1497 | 0 | break; |
1498 | | |
1499 | 0 | case 't': |
1500 | 0 | if (memcmp(str, "tlen", 4) == 0) { |
1501 | 0 | *end = str+4; |
1502 | 0 | res->d = b->core.isize; |
1503 | 0 | return 0; |
1504 | 0 | } |
1505 | 0 | break; |
1506 | | |
1507 | 0 | case '[': |
1508 | 0 | if (*str == '[' && str[1] && str[2] && str[3] == ']') { |
1509 | | /* aux tags */ |
1510 | 0 | *end = str+4; |
1511 | |
|
1512 | 0 | uint8_t *aux = bam_aux_get(b, str+1); |
1513 | 0 | if (aux) { |
1514 | | // we define the truth of a tag to be its presence, even if 0. |
1515 | 0 | int nomem = 0; |
1516 | 0 | res->is_true = 1; |
1517 | 0 | switch (*aux) { |
1518 | 0 | case 'Z': |
1519 | 0 | case 'H': |
1520 | 0 | res->is_str = 1; |
1521 | 0 | kputs_chk(&nomem, (char *)aux+1, ks_clear(&res->s)); |
1522 | 0 | break; |
1523 | | |
1524 | 0 | case 'A': |
1525 | 0 | res->is_str = 1; |
1526 | 0 | kputsn_chk(&nomem, (char *)aux+1, 1, ks_clear(&res->s)); |
1527 | 0 | break; |
1528 | | |
1529 | 0 | case 'i': case 'I': |
1530 | 0 | case 's': case 'S': |
1531 | 0 | case 'c': case 'C': |
1532 | 0 | res->is_str = 0; |
1533 | 0 | res->d = bam_aux2i(aux); |
1534 | 0 | break; |
1535 | | |
1536 | 0 | case 'f': |
1537 | 0 | case 'd': |
1538 | 0 | res->is_str = 0; |
1539 | 0 | res->d = bam_aux2f(aux); |
1540 | 0 | break; |
1541 | | |
1542 | 0 | default: |
1543 | 0 | hts_log_error("Aux type '%c not yet supported by filters", |
1544 | 0 | *aux); |
1545 | 0 | return -1; |
1546 | 0 | } |
1547 | 0 | return nomem ? -1 : 0; |
1548 | |
|
1549 | 0 | } else { |
1550 | | // hence absent tags are always false (and strings) |
1551 | 0 | res->is_str = 1; |
1552 | 0 | res->s.l = 0; |
1553 | 0 | res->d = 0; |
1554 | 0 | res->is_true = 0; |
1555 | 0 | return 0; |
1556 | 0 | } |
1557 | 0 | } |
1558 | 0 | break; |
1559 | 0 | } |
1560 | | |
1561 | | // All successful matches in switch should return 0. |
1562 | | // So if we didn't match, it's a parse error. |
1563 | 0 | return -1; |
1564 | 0 | } |
1565 | | |
1566 | | // Returns 1 when accepted by the filter, 0 if not, -1 on error. |
1567 | | int sam_passes_filter(const sam_hdr_t *h, const bam1_t *b, hts_filter_t *filt) |
1568 | 0 | { |
1569 | 0 | hb_pair hb = {h, b}; |
1570 | 0 | hts_expr_val_t res = HTS_EXPR_VAL_INIT; |
1571 | 0 | if (hts_filter_eval2(filt, &hb, bam_sym_lookup, &res)) { |
1572 | 0 | hts_log_error("Couldn't process filter expression"); |
1573 | 0 | hts_expr_val_free(&res); |
1574 | 0 | return -1; |
1575 | 0 | } |
1576 | | |
1577 | 0 | int t = res.is_true; |
1578 | 0 | hts_expr_val_free(&res); |
1579 | |
|
1580 | 0 | return t; |
1581 | 0 | } |
1582 | | |
1583 | | static int cram_readrec(BGZF *ignored, void *fpv, void *bv, int *tid, hts_pos_t *beg, hts_pos_t *end) |
1584 | 0 | { |
1585 | 0 | htsFile *fp = fpv; |
1586 | 0 | bam1_t *b = bv; |
1587 | 0 | int pass_filter, ret; |
1588 | |
|
1589 | 0 | do { |
1590 | 0 | ret = cram_get_bam_seq(fp->fp.cram, &b); |
1591 | 0 | if (ret < 0) |
1592 | 0 | return cram_eof(fp->fp.cram) ? -1 : -2; |
1593 | | |
1594 | 0 | *tid = b->core.tid; |
1595 | 0 | *beg = b->core.pos; |
1596 | 0 | *end = bam_endpos(b); |
1597 | |
|
1598 | 0 | if (fp->filter) { |
1599 | 0 | pass_filter = sam_passes_filter(fp->bam_header, b, fp->filter); |
1600 | 0 | if (pass_filter < 0) |
1601 | 0 | return -2; |
1602 | 0 | } else { |
1603 | 0 | pass_filter = 1; |
1604 | 0 | } |
1605 | 0 | } while (pass_filter == 0); |
1606 | | |
1607 | 0 | return ret; |
1608 | 0 | } |
1609 | | |
1610 | | static int cram_pseek(void *fp, int64_t offset, int whence) |
1611 | 0 | { |
1612 | 0 | cram_fd *fd = (cram_fd *)fp; |
1613 | |
|
1614 | 0 | if ((0 != cram_seek(fd, offset, SEEK_SET)) |
1615 | 0 | && (0 != cram_seek(fd, offset - fd->first_container, SEEK_CUR))) |
1616 | 0 | return -1; |
1617 | | |
1618 | 0 | fd->curr_position = offset; |
1619 | |
|
1620 | 0 | if (fd->ctr) { |
1621 | 0 | cram_free_container(fd->ctr); |
1622 | 0 | if (fd->ctr_mt && fd->ctr_mt != fd->ctr) |
1623 | 0 | cram_free_container(fd->ctr_mt); |
1624 | |
|
1625 | 0 | fd->ctr = NULL; |
1626 | 0 | fd->ctr_mt = NULL; |
1627 | 0 | fd->ooc = 0; |
1628 | 0 | } |
1629 | |
|
1630 | 0 | return 0; |
1631 | 0 | } |
1632 | | |
1633 | | /* |
1634 | | * cram_ptell is a pseudo-tell function, because it matches the position of the disk cursor only |
1635 | | * after a fresh seek call. Otherwise it indicates that the read takes place inside the buffered |
1636 | | * container previously fetched. It was designed like this to integrate with the functionality |
1637 | | * of the iterator stepping logic. |
1638 | | */ |
1639 | | |
1640 | | static int64_t cram_ptell(void *fp) |
1641 | 0 | { |
1642 | 0 | cram_fd *fd = (cram_fd *)fp; |
1643 | 0 | cram_container *c; |
1644 | 0 | cram_slice *s; |
1645 | 0 | int64_t ret = -1L; |
1646 | |
|
1647 | 0 | if (fd) { |
1648 | 0 | if ((c = fd->ctr) != NULL) { |
1649 | 0 | if ((s = c->slice) != NULL && s->max_rec) { |
1650 | 0 | if ((c->curr_slice + s->curr_rec/s->max_rec) >= (c->max_slice + 1)) |
1651 | 0 | fd->curr_position += c->offset + c->length; |
1652 | 0 | } |
1653 | 0 | } |
1654 | 0 | ret = fd->curr_position; |
1655 | 0 | } |
1656 | |
|
1657 | 0 | return ret; |
1658 | 0 | } |
1659 | | |
1660 | | |
1661 | | static hts_idx_t *index_load(htsFile *fp, const char *fn, const char *fnidx, int flags) |
1662 | 0 | { |
1663 | 0 | switch (fp->format.format) { |
1664 | 0 | case bam: |
1665 | 0 | case sam: |
1666 | 0 | return hts_idx_load3(fn, fnidx, HTS_FMT_BAI, flags); |
1667 | | |
1668 | 0 | case cram: { |
1669 | 0 | if (cram_index_load(fp->fp.cram, fn, fnidx) < 0) return NULL; |
1670 | | |
1671 | | // Cons up a fake "index" just pointing at the associated cram_fd: |
1672 | 0 | hts_cram_idx_t *idx = malloc(sizeof (hts_cram_idx_t)); |
1673 | 0 | if (idx == NULL) return NULL; |
1674 | 0 | idx->fmt = HTS_FMT_CRAI; |
1675 | 0 | idx->cram = fp->fp.cram; |
1676 | 0 | return (hts_idx_t *) idx; |
1677 | 0 | } |
1678 | | |
1679 | 0 | default: |
1680 | 0 | return NULL; // TODO Would use tbx_index_load if it returned hts_idx_t |
1681 | 0 | } |
1682 | 0 | } |
1683 | | |
1684 | | hts_idx_t *sam_index_load3(htsFile *fp, const char *fn, const char *fnidx, int flags) |
1685 | 0 | { |
1686 | 0 | return index_load(fp, fn, fnidx, flags); |
1687 | 0 | } |
1688 | | |
1689 | 0 | hts_idx_t *sam_index_load2(htsFile *fp, const char *fn, const char *fnidx) { |
1690 | 0 | return index_load(fp, fn, fnidx, HTS_IDX_SAVE_REMOTE); |
1691 | 0 | } |
1692 | | |
1693 | | hts_idx_t *sam_index_load(htsFile *fp, const char *fn) |
1694 | 0 | { |
1695 | 0 | return index_load(fp, fn, NULL, HTS_IDX_SAVE_REMOTE); |
1696 | 0 | } |
1697 | | |
1698 | | static hts_itr_t *cram_itr_query(const hts_idx_t *idx, int tid, hts_pos_t beg, hts_pos_t end, hts_readrec_func *readrec) |
1699 | 0 | { |
1700 | 0 | const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx; |
1701 | 0 | hts_itr_t *iter = (hts_itr_t *) calloc(1, sizeof(hts_itr_t)); |
1702 | 0 | if (iter == NULL) return NULL; |
1703 | | |
1704 | | // Cons up a dummy iterator for which hts_itr_next() will simply invoke |
1705 | | // the readrec function: |
1706 | 0 | iter->is_cram = 1; |
1707 | 0 | iter->read_rest = 1; |
1708 | 0 | iter->off = NULL; |
1709 | 0 | iter->bins.a = NULL; |
1710 | 0 | iter->readrec = readrec; |
1711 | |
|
1712 | 0 | if (tid >= 0 || tid == HTS_IDX_NOCOOR || tid == HTS_IDX_START) { |
1713 | 0 | cram_range r = { tid, beg+1, end }; |
1714 | 0 | int ret = cram_set_option(cidx->cram, CRAM_OPT_RANGE, &r); |
1715 | |
|
1716 | 0 | iter->curr_off = 0; |
1717 | | // The following fields are not required by hts_itr_next(), but are |
1718 | | // filled in in case user code wants to look at them. |
1719 | 0 | iter->tid = tid; |
1720 | 0 | iter->beg = beg; |
1721 | 0 | iter->end = end; |
1722 | |
|
1723 | 0 | switch (ret) { |
1724 | 0 | case 0: |
1725 | 0 | break; |
1726 | | |
1727 | 0 | case -2: |
1728 | | // No data vs this ref, so mark iterator as completed. |
1729 | | // Same as HTS_IDX_NONE. |
1730 | 0 | iter->finished = 1; |
1731 | 0 | break; |
1732 | | |
1733 | 0 | default: |
1734 | 0 | free(iter); |
1735 | 0 | return NULL; |
1736 | 0 | } |
1737 | 0 | } |
1738 | 0 | else switch (tid) { |
1739 | 0 | case HTS_IDX_REST: |
1740 | 0 | iter->curr_off = 0; |
1741 | 0 | break; |
1742 | 0 | case HTS_IDX_NONE: |
1743 | 0 | iter->curr_off = 0; |
1744 | 0 | iter->finished = 1; |
1745 | 0 | break; |
1746 | 0 | default: |
1747 | 0 | hts_log_error("Query with tid=%d not implemented for CRAM files", tid); |
1748 | 0 | abort(); |
1749 | 0 | break; |
1750 | 0 | } |
1751 | | |
1752 | 0 | return iter; |
1753 | 0 | } |
1754 | | |
1755 | | hts_itr_t *sam_itr_queryi(const hts_idx_t *idx, int tid, hts_pos_t beg, hts_pos_t end) |
1756 | 0 | { |
1757 | 0 | const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx; |
1758 | 0 | if (idx == NULL) |
1759 | 0 | return hts_itr_query(NULL, tid, beg, end, sam_readrec_rest); |
1760 | 0 | else if (cidx->fmt == HTS_FMT_CRAI) |
1761 | 0 | return cram_itr_query(idx, tid, beg, end, sam_readrec); |
1762 | 0 | else |
1763 | 0 | return hts_itr_query(idx, tid, beg, end, sam_readrec); |
1764 | 0 | } |
1765 | | |
1766 | | static int cram_name2id(void *fdv, const char *ref) |
1767 | 0 | { |
1768 | 0 | cram_fd *fd = (cram_fd *) fdv; |
1769 | 0 | return sam_hdr_name2tid(fd->header, ref); |
1770 | 0 | } |
1771 | | |
1772 | | hts_itr_t *sam_itr_querys(const hts_idx_t *idx, sam_hdr_t *hdr, const char *region) |
1773 | 0 | { |
1774 | 0 | const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx; |
1775 | 0 | return hts_itr_querys(idx, region, bam_name2id_wrapper, hdr, |
1776 | 0 | cidx->fmt == HTS_FMT_CRAI ? cram_itr_query : hts_itr_query, |
1777 | 0 | sam_readrec); |
1778 | 0 | } |
1779 | | |
1780 | | hts_itr_t *sam_itr_regarray(const hts_idx_t *idx, sam_hdr_t *hdr, char **regarray, unsigned int regcount) |
1781 | 0 | { |
1782 | 0 | const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx; |
1783 | 0 | hts_reglist_t *r_list = NULL; |
1784 | 0 | int r_count = 0; |
1785 | |
|
1786 | 0 | if (!cidx || !hdr) |
1787 | 0 | return NULL; |
1788 | | |
1789 | 0 | hts_itr_t *itr = NULL; |
1790 | 0 | if (cidx->fmt == HTS_FMT_CRAI) { |
1791 | 0 | r_list = hts_reglist_create(regarray, regcount, &r_count, cidx->cram, cram_name2id); |
1792 | 0 | if (!r_list) |
1793 | 0 | return NULL; |
1794 | 0 | itr = hts_itr_regions(idx, r_list, r_count, cram_name2id, cidx->cram, |
1795 | 0 | hts_itr_multi_cram, cram_readrec, cram_pseek, cram_ptell); |
1796 | 0 | } else { |
1797 | 0 | r_list = hts_reglist_create(regarray, regcount, &r_count, hdr, bam_name2id_wrapper); |
1798 | 0 | if (!r_list) |
1799 | 0 | return NULL; |
1800 | 0 | itr = hts_itr_regions(idx, r_list, r_count, bam_name2id_wrapper, hdr, |
1801 | 0 | hts_itr_multi_bam, sam_readrec, bgzf_pseek, bgzf_ptell); |
1802 | 0 | } |
1803 | | |
1804 | 0 | return itr; |
1805 | 0 | } |
1806 | | |
1807 | | hts_itr_t *sam_itr_regions(const hts_idx_t *idx, sam_hdr_t *hdr, hts_reglist_t *reglist, unsigned int regcount) |
1808 | 0 | { |
1809 | 0 | const hts_cram_idx_t *cidx = (const hts_cram_idx_t *) idx; |
1810 | |
|
1811 | 0 | if(!cidx || !hdr || !reglist) |
1812 | 0 | return NULL; |
1813 | | |
1814 | 0 | if (cidx->fmt == HTS_FMT_CRAI) |
1815 | 0 | return hts_itr_regions(idx, reglist, regcount, cram_name2id, cidx->cram, |
1816 | 0 | hts_itr_multi_cram, cram_readrec, cram_pseek, cram_ptell); |
1817 | 0 | else |
1818 | 0 | return hts_itr_regions(idx, reglist, regcount, bam_name2id_wrapper, hdr, |
1819 | 0 | hts_itr_multi_bam, sam_readrec, bgzf_pseek, bgzf_ptell); |
1820 | 0 | } |
1821 | | |
1822 | | /********************** |
1823 | | *** SAM header I/O *** |
1824 | | **********************/ |
1825 | | |
1826 | | #include "htslib/kseq.h" |
1827 | | #include "htslib/kstring.h" |
1828 | | |
1829 | | sam_hdr_t *sam_hdr_parse(size_t l_text, const char *text) |
1830 | 0 | { |
1831 | 0 | sam_hdr_t *bh = sam_hdr_init(); |
1832 | 0 | if (!bh) return NULL; |
1833 | | |
1834 | 0 | if (sam_hdr_add_lines(bh, text, l_text) != 0) { |
1835 | 0 | sam_hdr_destroy(bh); |
1836 | 0 | return NULL; |
1837 | 0 | } |
1838 | | |
1839 | 0 | return bh; |
1840 | 0 | } |
1841 | | |
1842 | | // Minimal sanitisation of a header to ensure. |
1843 | | // - null terminated string. |
1844 | | // - all lines start with @ (also implies no blank lines). |
1845 | | // |
1846 | | // Much more could be done, but currently is not, including: |
1847 | | // - checking header types are known (HD, SQ, etc). |
1848 | | // - syntax (eg checking tab separated fields). |
1849 | | // - validating n_targets matches @SQ records. |
1850 | | // - validating target lengths against @SQ records. |
1851 | 28.3k | static sam_hdr_t *sam_hdr_sanitise(sam_hdr_t *h) { |
1852 | 28.3k | if (!h) |
1853 | 588 | return NULL; |
1854 | | |
1855 | | // Special case for empty headers. |
1856 | 27.7k | if (h->l_text == 0) |
1857 | 9.81k | return h; |
1858 | | |
1859 | 17.9k | size_t i; |
1860 | 17.9k | unsigned int lnum = 0; |
1861 | 17.9k | char *cp = h->text, last = '\n'; |
1862 | 56.8M | for (i = 0; i < h->l_text; i++) { |
1863 | | // NB: l_text excludes terminating nul. This finds early ones. |
1864 | 56.8M | if (cp[i] == 0) |
1865 | 8.22k | break; |
1866 | | |
1867 | | // Error on \n[^@], including duplicate newlines |
1868 | 56.8M | if (last == '\n') { |
1869 | 29.7k | lnum++; |
1870 | 29.7k | if (cp[i] != '@') { |
1871 | 3 | hts_log_error("Malformed SAM header at line %u", lnum); |
1872 | 3 | sam_hdr_destroy(h); |
1873 | 3 | return NULL; |
1874 | 3 | } |
1875 | 29.7k | } |
1876 | | |
1877 | 56.8M | last = cp[i]; |
1878 | 56.8M | } |
1879 | | |
1880 | 17.9k | if (i < h->l_text) { // Early nul found. Complain if not just padding. |
1881 | 8.22k | size_t j = i; |
1882 | 178k | while (j < h->l_text && cp[j] == '\0') j++; |
1883 | 8.22k | if (j < h->l_text) |
1884 | 7.88k | hts_log_warning("Unexpected NUL character in header. Possibly truncated"); |
1885 | 8.22k | } |
1886 | | |
1887 | | // Add trailing newline and/or trailing nul if required. |
1888 | 17.9k | if (last != '\n') { |
1889 | 7.95k | hts_log_warning("Missing trailing newline on SAM header. Possibly truncated"); |
1890 | | |
1891 | 7.95k | if (h->l_text < 2 || i >= h->l_text - 2) { |
1892 | 756 | if (h->l_text >= SIZE_MAX - 2) { |
1893 | 0 | hts_log_error("No room for extra newline"); |
1894 | 0 | sam_hdr_destroy(h); |
1895 | 0 | return NULL; |
1896 | 0 | } |
1897 | | |
1898 | 756 | cp = realloc(h->text, (size_t) h->l_text+2); |
1899 | 756 | if (!cp) { |
1900 | 0 | sam_hdr_destroy(h); |
1901 | 0 | return NULL; |
1902 | 0 | } |
1903 | 756 | h->text = cp; |
1904 | 756 | } |
1905 | 7.95k | cp[i++] = '\n'; |
1906 | | |
1907 | | // l_text may be larger already due to multiple nul padding |
1908 | 7.95k | if (h->l_text < i) |
1909 | 51 | h->l_text = i; |
1910 | 7.95k | cp[h->l_text] = '\0'; |
1911 | 7.95k | } |
1912 | | |
1913 | 17.9k | return h; |
1914 | 17.9k | } |
1915 | | |
1916 | 18.5k | static sam_hdr_t *sam_hdr_create(htsFile* fp) { |
1917 | 18.5k | sam_hdr_t* h = sam_hdr_init(); |
1918 | 18.5k | if (!h) |
1919 | 0 | return NULL; |
1920 | | |
1921 | 18.5k | if (sam_hdr_build_from_sam_file(h, fp) != 0) { |
1922 | 1.31k | sam_hdr_destroy(h); |
1923 | 1.31k | return NULL; |
1924 | 1.31k | } |
1925 | | |
1926 | 17.2k | if (fp->bam_header) |
1927 | 0 | sam_hdr_destroy(fp->bam_header); |
1928 | 17.2k | fp->bam_header = sam_hdr_sanitise(h); |
1929 | 17.2k | if (fp->bam_header) |
1930 | 17.2k | fp->bam_header->ref_count = 1; |
1931 | | |
1932 | 17.2k | return fp->bam_header; |
1933 | 18.5k | } |
1934 | | |
1935 | | sam_hdr_t *sam_hdr_read(htsFile *fp) |
1936 | 35.0k | { |
1937 | 35.0k | sam_hdr_t *h = NULL; |
1938 | 35.0k | if (!fp) { |
1939 | 0 | errno = EINVAL; |
1940 | 0 | return NULL; |
1941 | 0 | } |
1942 | | |
1943 | 35.0k | switch (fp->format.format) { |
1944 | 3.69k | case bam: |
1945 | 3.69k | h = sam_hdr_sanitise(bam_hdr_read(fp->fp.bgzf)); |
1946 | 3.69k | break; |
1947 | | |
1948 | 7.44k | case cram: |
1949 | 7.44k | h = sam_hdr_sanitise(sam_hdr_dup(fp->fp.cram->header)); |
1950 | 7.44k | break; |
1951 | | |
1952 | 18.5k | case sam: |
1953 | 18.5k | h = sam_hdr_create(fp); |
1954 | 18.5k | break; |
1955 | | |
1956 | 315 | case fastq_format: |
1957 | 5.42k | case fasta_format: |
1958 | 5.42k | return sam_hdr_init(); |
1959 | | |
1960 | 0 | case empty_format: |
1961 | 0 | errno = EPIPE; |
1962 | 0 | return NULL; |
1963 | | |
1964 | 0 | default: |
1965 | 0 | errno = EFTYPE; |
1966 | 0 | return NULL; |
1967 | 35.0k | } |
1968 | | //only sam,bam and cram reaches here |
1969 | 29.6k | if (h && !fp->bam_header) { //set except for sam which already has it |
1970 | | //for cram, it is the o/p header as for rest and not the internal header |
1971 | 10.5k | fp->bam_header = h; |
1972 | 10.5k | sam_hdr_incr_ref(fp->bam_header); |
1973 | 10.5k | } |
1974 | | |
1975 | | // Sanity check incase we have nul bytes in the header we just read |
1976 | 29.6k | if (h) |
1977 | 27.7k | h->l_text = h->text ? strlen(h->text) : 0; |
1978 | | |
1979 | 29.6k | return h; |
1980 | 35.0k | } |
1981 | | |
1982 | | int sam_hdr_write(htsFile *fp, const sam_hdr_t *h) |
1983 | 33.1k | { |
1984 | 33.1k | if (!fp || !h) { |
1985 | 0 | errno = EINVAL; |
1986 | 0 | return -1; |
1987 | 0 | } |
1988 | | |
1989 | 33.1k | switch (fp->format.format) { |
1990 | 11.0k | case binary_format: |
1991 | 11.0k | fp->format.category = sequence_data; |
1992 | 11.0k | fp->format.format = bam; |
1993 | | /* fall-through */ |
1994 | 11.0k | case bam: |
1995 | 11.0k | if (bam_hdr_write(fp->fp.bgzf, h) < 0) return -1; |
1996 | 11.0k | break; |
1997 | | |
1998 | 11.0k | case cram: { |
1999 | 11.0k | cram_fd *fd = fp->fp.cram; |
2000 | 11.0k | if (cram_set_header2(fd, h) < 0) return -1; |
2001 | 10.9k | if (fp->fn_aux) |
2002 | 0 | cram_load_reference(fd, fp->fn_aux); |
2003 | 10.9k | if (cram_write_SAM_hdr(fd, fd->header) < 0) return -1; |
2004 | 10.9k | } |
2005 | 10.9k | break; |
2006 | | |
2007 | 11.0k | case text_format: |
2008 | 11.0k | fp->format.category = sequence_data; |
2009 | 11.0k | fp->format.format = sam; |
2010 | | /* fall-through */ |
2011 | 11.0k | case sam: { |
2012 | 11.0k | if (!h->hrecs && !h->text) |
2013 | 0 | return 0; |
2014 | 11.0k | char *text; |
2015 | 11.0k | kstring_t hdr_ks = { 0, 0, NULL }; |
2016 | 11.0k | size_t l_text; |
2017 | 11.0k | ssize_t bytes; |
2018 | 11.0k | int r = 0, no_sq = 0; |
2019 | | |
2020 | 11.0k | if (h->hrecs) { |
2021 | 10.9k | if (sam_hrecs_rebuild_text(h->hrecs, &hdr_ks) != 0) |
2022 | 0 | return -1; |
2023 | 10.9k | text = hdr_ks.s; |
2024 | 10.9k | l_text = hdr_ks.l; |
2025 | 10.9k | } else { |
2026 | 102 | const char *p = NULL; |
2027 | 121 | do { |
2028 | 121 | const char *q = p == NULL ? h->text : p + 4; |
2029 | 121 | p = strstr(q, "@SQ\t"); |
2030 | 121 | } while (!(p == NULL || p == h->text || *(p - 1) == '\n')); |
2031 | 102 | no_sq = p == NULL; |
2032 | 102 | text = h->text; |
2033 | 102 | l_text = h->l_text; |
2034 | 102 | } |
2035 | | |
2036 | 11.0k | if (fp->is_bgzf) { |
2037 | 0 | bytes = bgzf_write(fp->fp.bgzf, text, l_text); |
2038 | 11.0k | } else { |
2039 | 11.0k | bytes = hwrite(fp->fp.hfile, text, l_text); |
2040 | 11.0k | } |
2041 | 11.0k | free(hdr_ks.s); |
2042 | 11.0k | if (bytes != l_text) |
2043 | 0 | return -1; |
2044 | | |
2045 | 11.0k | if (no_sq) { |
2046 | 83 | int i; |
2047 | 225 | for (i = 0; i < h->n_targets; ++i) { |
2048 | 142 | fp->line.l = 0; |
2049 | 142 | r |= kputsn("@SQ\tSN:", 7, &fp->line) < 0; |
2050 | 142 | r |= kputs(h->target_name[i], &fp->line) < 0; |
2051 | 142 | r |= kputsn("\tLN:", 4, &fp->line) < 0; |
2052 | 142 | r |= kputw(h->target_len[i], &fp->line) < 0; |
2053 | 142 | r |= kputc('\n', &fp->line) < 0; |
2054 | 142 | if (r != 0) |
2055 | 0 | return -1; |
2056 | | |
2057 | 142 | if (fp->is_bgzf) { |
2058 | 0 | bytes = bgzf_write(fp->fp.bgzf, fp->line.s, fp->line.l); |
2059 | 142 | } else { |
2060 | 142 | bytes = hwrite(fp->fp.hfile, fp->line.s, fp->line.l); |
2061 | 142 | } |
2062 | 142 | if (bytes != fp->line.l) |
2063 | 0 | return -1; |
2064 | 142 | } |
2065 | 83 | } |
2066 | 11.0k | if (fp->is_bgzf) { |
2067 | 0 | if (bgzf_flush(fp->fp.bgzf) != 0) return -1; |
2068 | 11.0k | } else { |
2069 | 11.0k | if (hflush(fp->fp.hfile) != 0) return -1; |
2070 | 11.0k | } |
2071 | 11.0k | } |
2072 | 11.0k | break; |
2073 | | |
2074 | 11.0k | case fastq_format: |
2075 | 0 | case fasta_format: |
2076 | | // Nothing to output; FASTQ has no file headers. |
2077 | 0 | return 0; |
2078 | 0 | break; |
2079 | | |
2080 | 0 | default: |
2081 | 0 | errno = EBADF; |
2082 | 0 | return -1; |
2083 | 33.1k | } |
2084 | | //only sam,bam and cram reaches here |
2085 | 33.0k | if (h) { //the new header |
2086 | 33.0k | sam_hdr_t *tmp = fp->bam_header; |
2087 | 33.0k | fp->bam_header = sam_hdr_dup(h); |
2088 | 33.0k | sam_hdr_destroy(tmp); |
2089 | 33.0k | if (!fp->bam_header && h) |
2090 | 0 | return -1; //failed to duplicate |
2091 | 33.0k | } |
2092 | 33.0k | return 0; |
2093 | 33.0k | } |
2094 | | |
2095 | | static int old_sam_hdr_change_HD(sam_hdr_t *h, const char *key, const char *val) |
2096 | 0 | { |
2097 | 0 | char *p, *q, *beg = NULL, *end = NULL, *newtext; |
2098 | 0 | size_t new_l_text; |
2099 | 0 | if (!h || !key) |
2100 | 0 | return -1; |
2101 | | |
2102 | 0 | if (h->l_text > 3) { |
2103 | 0 | if (strncmp(h->text, "@HD", 3) == 0) { //@HD line exists |
2104 | 0 | if ((p = strchr(h->text, '\n')) == 0) return -1; |
2105 | 0 | *p = '\0'; // for strstr call |
2106 | |
|
2107 | 0 | char tmp[5] = { '\t', key[0], key[0] ? key[1] : '\0', ':', '\0' }; |
2108 | |
|
2109 | 0 | if ((q = strstr(h->text, tmp)) != 0) { // key exists |
2110 | 0 | *p = '\n'; // change back |
2111 | | |
2112 | | // mark the key:val |
2113 | 0 | beg = q; |
2114 | 0 | for (q += 4; *q != '\n' && *q != '\t'; ++q); |
2115 | 0 | end = q; |
2116 | |
|
2117 | 0 | if (val && (strncmp(beg + 4, val, end - beg - 4) == 0) |
2118 | 0 | && strlen(val) == end - beg - 4) |
2119 | 0 | return 0; // val is the same, no need to change |
2120 | |
|
2121 | 0 | } else { |
2122 | 0 | beg = end = p; |
2123 | 0 | *p = '\n'; |
2124 | 0 | } |
2125 | 0 | } |
2126 | 0 | } |
2127 | 0 | if (beg == NULL) { // no @HD |
2128 | 0 | new_l_text = h->l_text; |
2129 | 0 | if (new_l_text > SIZE_MAX - strlen(SAM_FORMAT_VERSION) - 9) |
2130 | 0 | return -1; |
2131 | 0 | new_l_text += strlen(SAM_FORMAT_VERSION) + 8; |
2132 | 0 | if (val) { |
2133 | 0 | if (new_l_text > SIZE_MAX - strlen(val) - 5) |
2134 | 0 | return -1; |
2135 | 0 | new_l_text += strlen(val) + 4; |
2136 | 0 | } |
2137 | 0 | newtext = (char*)malloc(new_l_text + 1); |
2138 | 0 | if (!newtext) return -1; |
2139 | | |
2140 | 0 | if (val) |
2141 | 0 | snprintf(newtext, new_l_text + 1, |
2142 | 0 | "@HD\tVN:%s\t%s:%s\n%s", SAM_FORMAT_VERSION, key, val, h->text); |
2143 | 0 | else |
2144 | 0 | snprintf(newtext, new_l_text + 1, |
2145 | 0 | "@HD\tVN:%s\n%s", SAM_FORMAT_VERSION, h->text); |
2146 | 0 | } else { // has @HD but different or no key |
2147 | 0 | new_l_text = (beg - h->text) + (h->text + h->l_text - end); |
2148 | 0 | if (val) { |
2149 | 0 | if (new_l_text > SIZE_MAX - strlen(val) - 5) |
2150 | 0 | return -1; |
2151 | 0 | new_l_text += strlen(val) + 4; |
2152 | 0 | } |
2153 | 0 | newtext = (char*)malloc(new_l_text + 1); |
2154 | 0 | if (!newtext) return -1; |
2155 | | |
2156 | 0 | if (val) { |
2157 | 0 | snprintf(newtext, new_l_text + 1, "%.*s\t%s:%s%s", |
2158 | 0 | (int) (beg - h->text), h->text, key, val, end); |
2159 | 0 | } else { //delete key |
2160 | 0 | snprintf(newtext, new_l_text + 1, "%.*s%s", |
2161 | 0 | (int) (beg - h->text), h->text, end); |
2162 | 0 | } |
2163 | 0 | } |
2164 | 0 | free(h->text); |
2165 | 0 | h->text = newtext; |
2166 | 0 | h->l_text = new_l_text; |
2167 | 0 | return 0; |
2168 | 0 | } |
2169 | | |
2170 | | |
2171 | | int sam_hdr_change_HD(sam_hdr_t *h, const char *key, const char *val) |
2172 | 0 | { |
2173 | 0 | if (!h || !key) |
2174 | 0 | return -1; |
2175 | | |
2176 | 0 | if (!h->hrecs) |
2177 | 0 | return old_sam_hdr_change_HD(h, key, val); |
2178 | | |
2179 | 0 | if (val) { |
2180 | 0 | if (sam_hdr_update_line(h, "HD", NULL, NULL, key, val, NULL) != 0) |
2181 | 0 | return -1; |
2182 | 0 | } else { |
2183 | 0 | if (sam_hdr_remove_tag_id(h, "HD", NULL, NULL, key) != 0) |
2184 | 0 | return -1; |
2185 | 0 | } |
2186 | 0 | return sam_hdr_rebuild(h); |
2187 | 0 | } |
2188 | | |
2189 | | /* releases existing header and sets new one; increments ref count if not |
2190 | | duplicating */ |
2191 | | int sam_hdr_set(samFile *fp, sam_hdr_t *h, int duplicate) |
2192 | 0 | { |
2193 | 0 | if (!fp) |
2194 | 0 | return -1; |
2195 | | |
2196 | 0 | if (duplicate) { |
2197 | 0 | sam_hdr_t *tmp = fp->bam_header; |
2198 | 0 | fp->bam_header = sam_hdr_dup(h); |
2199 | 0 | sam_hdr_destroy(tmp); |
2200 | 0 | if (!fp->bam_header && h) |
2201 | 0 | return -1; //duplicate failed |
2202 | 0 | } else { |
2203 | 0 | if (fp->bam_header != h) { //if not the same |
2204 | 0 | sam_hdr_destroy(fp->bam_header); |
2205 | 0 | fp->bam_header = h; |
2206 | 0 | sam_hdr_incr_ref(fp->bam_header); |
2207 | 0 | } |
2208 | 0 | } |
2209 | | |
2210 | 0 | return 0; |
2211 | 0 | } |
2212 | | |
2213 | | //return the bam_header, user has to use sam_hdr_incr_ref where ever required |
2214 | | sam_hdr_t* sam_hdr_get(samFile* fp) |
2215 | 0 | { |
2216 | 0 | if (!fp) |
2217 | 0 | return NULL; |
2218 | 0 | return fp->bam_header; |
2219 | 0 | } |
2220 | | |
2221 | | /********************** |
2222 | | *** SAM record I/O *** |
2223 | | **********************/ |
2224 | | |
2225 | | // The speed of this code can vary considerably depending on minor code |
2226 | | // changes elsewhere as some of the tight loops are particularly prone to |
2227 | | // speed changes when the instruction blocks are split over a 32-byte |
2228 | | // boundary. To protect against this, we explicitly specify an alignment |
2229 | | // for this function. If this is insufficient, we may also wish to |
2230 | | // consider alignment of blocks within this function via |
2231 | | // __attribute__((optimize("align-loops=5"))) (gcc) or clang equivalents. |
2232 | | // However it's not very portable. |
2233 | | // Instead we break into separate functions so we can explicitly specify |
2234 | | // use __attribute__((aligned(32))) instead and force consistent loop |
2235 | | // alignment. |
2236 | 394k | static inline int64_t grow_B_array(bam1_t *b, uint32_t *n, size_t size) { |
2237 | | // Avoid overflow on 32-bit platforms, but it breaks BAM anyway |
2238 | 394k | if (*n > INT32_MAX*0.666) { |
2239 | 0 | errno = ENOMEM; |
2240 | 0 | return -1; |
2241 | 0 | } |
2242 | | |
2243 | 394k | size_t bytes = (size_t)size * (size_t)(*n>>1); |
2244 | 394k | if (possibly_expand_bam_data(b, bytes) < 0) { |
2245 | 0 | hts_log_error("Out of memory"); |
2246 | 0 | return -1; |
2247 | 0 | } |
2248 | | |
2249 | 394k | (*n)+=*n>>1; |
2250 | 394k | return 0; |
2251 | 394k | } |
2252 | | |
2253 | | |
2254 | | // This ensures that q always ends up at the next comma after |
2255 | | // reading a number even if it's followed by junk. It |
2256 | | // prevents the possibility of trying to read more than n items. |
2257 | 23.5M | #define skip_to_comma_(q) do { while (*(q) > '\t' && *(q) != ',') (q)++; } while (0) |
2258 | | |
2259 | | HTS_ALIGN32 |
2260 | | static char *sam_parse_Bc_vals(bam1_t *b, char *q, uint32_t *nused, |
2261 | 31.3k | uint32_t *nalloc, int *overflow) { |
2262 | 814k | while (*q == ',') { |
2263 | 783k | if ((*nused)++ >= (*nalloc)) { |
2264 | 12.7k | if (grow_B_array(b, nalloc, 1) < 0) |
2265 | 0 | return NULL; |
2266 | 12.7k | } |
2267 | 783k | *(b->data + b->l_data) = hts_str2int(q + 1, &q, 8, overflow); |
2268 | 783k | b->l_data++; |
2269 | 783k | } |
2270 | 31.3k | return q; |
2271 | 31.3k | } |
2272 | | |
2273 | | HTS_ALIGN32 |
2274 | | static char *sam_parse_BC_vals(bam1_t *b, char *q, uint32_t *nused, |
2275 | 54.2k | uint32_t *nalloc, int *overflow) { |
2276 | 4.80M | while (*q == ',') { |
2277 | 4.74M | if ((*nused)++ >= (*nalloc)) { |
2278 | 150k | if (grow_B_array(b, nalloc, 1) < 0) |
2279 | 0 | return NULL; |
2280 | 150k | } |
2281 | 4.74M | if (q[1] != '-') { |
2282 | 4.40M | *(b->data + b->l_data) = hts_str2uint(q + 1, &q, 8, overflow); |
2283 | 4.40M | b->l_data++; |
2284 | 4.40M | } else { |
2285 | 343k | *overflow = 1; |
2286 | 343k | q++; |
2287 | 343k | skip_to_comma_(q); |
2288 | 343k | } |
2289 | 4.74M | } |
2290 | 54.2k | return q; |
2291 | 54.2k | } |
2292 | | |
2293 | | HTS_ALIGN32 |
2294 | | static char *sam_parse_Bs_vals(bam1_t *b, char *q, uint32_t *nused, |
2295 | 60.9k | uint32_t *nalloc, int *overflow) { |
2296 | 15.1M | while (*q == ',') { |
2297 | 15.0M | if ((*nused)++ >= (*nalloc)) { |
2298 | 8.39k | if (grow_B_array(b, nalloc, 2) < 0) |
2299 | 0 | return NULL; |
2300 | 8.39k | } |
2301 | 15.0M | i16_to_le(hts_str2int(q + 1, &q, 16, overflow), |
2302 | 15.0M | b->data + b->l_data); |
2303 | 15.0M | b->l_data += 2; |
2304 | 15.0M | } |
2305 | 60.9k | return q; |
2306 | 60.9k | } |
2307 | | |
2308 | | HTS_ALIGN32 |
2309 | | static char *sam_parse_BS_vals(bam1_t *b, char *q, uint32_t *nused, |
2310 | 22.7k | uint32_t *nalloc, int *overflow) { |
2311 | 710k | while (*q == ',') { |
2312 | 687k | if ((*nused)++ >= (*nalloc)) { |
2313 | 7.27k | if (grow_B_array(b, nalloc, 2) < 0) |
2314 | 0 | return NULL; |
2315 | 7.27k | } |
2316 | 687k | if (q[1] != '-') { |
2317 | 655k | u16_to_le(hts_str2uint(q + 1, &q, 16, overflow), |
2318 | 655k | b->data + b->l_data); |
2319 | 655k | b->l_data += 2; |
2320 | 655k | } else { |
2321 | 32.3k | *overflow = 1; |
2322 | 32.3k | q++; |
2323 | 32.3k | skip_to_comma_(q); |
2324 | 32.3k | } |
2325 | 687k | } |
2326 | 22.7k | return q; |
2327 | 22.7k | } |
2328 | | |
2329 | | HTS_ALIGN32 |
2330 | | static char *sam_parse_Bi_vals(bam1_t *b, char *q, uint32_t *nused, |
2331 | 43.7k | uint32_t *nalloc, int *overflow) { |
2332 | 20.5M | while (*q == ',') { |
2333 | 20.4M | if ((*nused)++ >= (*nalloc)) { |
2334 | 694 | if (grow_B_array(b, nalloc, 4) < 0) |
2335 | 0 | return NULL; |
2336 | 694 | } |
2337 | 20.4M | i32_to_le(hts_str2int(q + 1, &q, 32, overflow), |
2338 | 20.4M | b->data + b->l_data); |
2339 | 20.4M | b->l_data += 4; |
2340 | 20.4M | } |
2341 | 43.7k | return q; |
2342 | 43.7k | } |
2343 | | |
2344 | | HTS_ALIGN32 |
2345 | | static char *sam_parse_BI_vals(bam1_t *b, char *q, uint32_t *nused, |
2346 | 75.1k | uint32_t *nalloc, int *overflow) { |
2347 | 1.41M | while (*q == ',') { |
2348 | 1.33M | if ((*nused)++ >= (*nalloc)) { |
2349 | 163k | if (grow_B_array(b, nalloc, 4) < 0) |
2350 | 0 | return NULL; |
2351 | 163k | } |
2352 | 1.33M | if (q[1] != '-') { |
2353 | 1.25M | u32_to_le(hts_str2uint(q + 1, &q, 32, overflow), |
2354 | 1.25M | b->data + b->l_data); |
2355 | 1.25M | b->l_data += 4; |
2356 | 1.25M | } else { |
2357 | 79.0k | *overflow = 1; |
2358 | 79.0k | q++; |
2359 | 79.0k | skip_to_comma_(q); |
2360 | 79.0k | } |
2361 | 1.33M | } |
2362 | 75.1k | return q; |
2363 | 75.1k | } |
2364 | | |
2365 | | HTS_ALIGN32 |
2366 | | static char *sam_parse_Bf_vals(bam1_t *b, char *q, uint32_t *nused, |
2367 | 20.2k | uint32_t *nalloc, int *overflow) { |
2368 | 532k | while (*q == ',') { |
2369 | 512k | if ((*nused)++ >= (*nalloc)) { |
2370 | 51.3k | if (grow_B_array(b, nalloc, 4) < 0) |
2371 | 0 | return NULL; |
2372 | 51.3k | } |
2373 | 512k | float_to_le(strtod(q + 1, &q), b->data + b->l_data); |
2374 | 512k | b->l_data += 4; |
2375 | 512k | } |
2376 | 20.2k | return q; |
2377 | 20.2k | } |
2378 | | |
2379 | | HTS_ALIGN32 |
2380 | | static int sam_parse_B_vals_r(char type, uint32_t nalloc, char *in, |
2381 | | char **end, bam1_t *b, |
2382 | 308k | int *ctr) { |
2383 | | // Protect against infinite recursion when dealing with invalid input. |
2384 | | // An example string is "XX:B:C,-". The lack of a number means min=0, |
2385 | | // but it overflowed due to "-" and so we repeat ad-infinitum. |
2386 | | // |
2387 | | // Loop detection is the safest solution in case there are other |
2388 | | // strange corner cases with malformed inputs. |
2389 | 308k | if (++(*ctr) > 2) { |
2390 | 120 | hts_log_error("Malformed data in B:%c array", type); |
2391 | 120 | return -1; |
2392 | 120 | } |
2393 | | |
2394 | 308k | int orig_l = b->l_data; |
2395 | 308k | char *q = in; |
2396 | 308k | int32_t size; |
2397 | 308k | size_t bytes; |
2398 | 308k | int overflow = 0; |
2399 | | |
2400 | 308k | size = aux_type2Bsize(type); |
2401 | 308k | if (size <= 0) { |
2402 | 44 | hts_log_error("Unrecognized type B:%c", type); |
2403 | 44 | return -1; |
2404 | 44 | } |
2405 | | |
2406 | | // Ensure space for type + values. |
2407 | | // The first pass through here we don't know the number of entries and |
2408 | | // nalloc == 0. We start with a small working set and then parse the |
2409 | | // data, growing as needed. |
2410 | | // |
2411 | | // If we have a second pass through we do know the number of entries |
2412 | | // and nalloc is already known. We have no need to expand the bam data. |
2413 | 308k | if (!nalloc) |
2414 | 207k | nalloc=7; |
2415 | | |
2416 | | // Ensure allocated memory is big enough (for current nalloc estimate) |
2417 | 308k | bytes = (size_t) nalloc * (size_t) size; |
2418 | 308k | if (bytes / size != nalloc |
2419 | 308k | || possibly_expand_bam_data(b, bytes + 2 + sizeof(uint32_t))) { |
2420 | 0 | hts_log_error("Out of memory"); |
2421 | 0 | return -1; |
2422 | 0 | } |
2423 | | |
2424 | 308k | uint32_t nused = 0; |
2425 | | |
2426 | 308k | b->data[b->l_data++] = 'B'; |
2427 | 308k | b->data[b->l_data++] = type; |
2428 | | // 32-bit B-array length is inserted later once we know it. |
2429 | 308k | int b_len_idx = b->l_data; |
2430 | 308k | b->l_data += sizeof(uint32_t); |
2431 | | |
2432 | 308k | if (type == 'c') { |
2433 | 31.3k | if (!(q = sam_parse_Bc_vals(b, q, &nused, &nalloc, &overflow))) |
2434 | 0 | return -1; |
2435 | 277k | } else if (type == 'C') { |
2436 | 54.2k | if (!(q = sam_parse_BC_vals(b, q, &nused, &nalloc, &overflow))) |
2437 | 0 | return -1; |
2438 | 223k | } else if (type == 's') { |
2439 | 60.9k | if (!(q = sam_parse_Bs_vals(b, q, &nused, &nalloc, &overflow))) |
2440 | 0 | return -1; |
2441 | 162k | } else if (type == 'S') { |
2442 | 22.7k | if (!(q = sam_parse_BS_vals(b, q, &nused, &nalloc, &overflow))) |
2443 | 0 | return -1; |
2444 | 139k | } else if (type == 'i') { |
2445 | 43.7k | if (!(q = sam_parse_Bi_vals(b, q, &nused, &nalloc, &overflow))) |
2446 | 0 | return -1; |
2447 | 95.6k | } else if (type == 'I') { |
2448 | 75.1k | if (!(q = sam_parse_BI_vals(b, q, &nused, &nalloc, &overflow))) |
2449 | 0 | return -1; |
2450 | 75.1k | } else if (type == 'f') { |
2451 | 20.2k | if (!(q = sam_parse_Bf_vals(b, q, &nused, &nalloc, &overflow))) |
2452 | 0 | return -1; |
2453 | 20.2k | } |
2454 | 308k | if (*q != '\t' && *q != '\0') { |
2455 | | // Unknown B array type or junk in the numbers |
2456 | 388 | hts_log_error("Malformed B:%c", type); |
2457 | 388 | return -1; |
2458 | 388 | } |
2459 | 308k | i32_to_le(nused, b->data + b_len_idx); |
2460 | | |
2461 | 308k | if (!overflow) { |
2462 | 206k | *end = q; |
2463 | 206k | return 0; |
2464 | 206k | } else { |
2465 | 101k | int64_t max = 0, min = 0, val; |
2466 | | // Given type was incorrect. Try to rescue the situation. |
2467 | 101k | char *r = q; |
2468 | 101k | q = in; |
2469 | 101k | overflow = 0; |
2470 | 101k | b->l_data = orig_l; |
2471 | | // Find out what range of values is present |
2472 | 21.5M | while (q < r) { |
2473 | 21.4M | val = hts_str2int(q + 1, &q, 64, &overflow); |
2474 | 21.4M | if (max < val) max = val; |
2475 | 21.4M | if (min > val) min = val; |
2476 | 21.4M | skip_to_comma_(q); |
2477 | 21.4M | } |
2478 | | // Retry with appropriate type |
2479 | 101k | if (!overflow) { |
2480 | 101k | if (min < 0) { |
2481 | 94.9k | if (min >= INT8_MIN && max <= INT8_MAX) { |
2482 | 18.2k | return sam_parse_B_vals_r('c', nalloc, in, end, b, ctr); |
2483 | 76.7k | } else if (min >= INT16_MIN && max <= INT16_MAX) { |
2484 | 33.5k | return sam_parse_B_vals_r('s', nalloc, in, end, b, ctr); |
2485 | 43.2k | } else if (min >= INT32_MIN && max <= INT32_MAX) { |
2486 | 42.8k | return sam_parse_B_vals_r('i', nalloc, in, end, b, ctr); |
2487 | 42.8k | } |
2488 | 94.9k | } else { |
2489 | 6.62k | if (max < UINT8_MAX) { |
2490 | 828 | return sam_parse_B_vals_r('C', nalloc, in, end, b, ctr); |
2491 | 5.79k | } else if (max <= UINT16_MAX) { |
2492 | 484 | return sam_parse_B_vals_r('S', nalloc, in, end, b, ctr); |
2493 | 5.30k | } else if (max <= UINT32_MAX) { |
2494 | 5.12k | return sam_parse_B_vals_r('I', nalloc, in, end, b, ctr); |
2495 | 5.12k | } |
2496 | 6.62k | } |
2497 | 101k | } |
2498 | | // If here then at least one of the values is too big to store |
2499 | 709 | hts_log_error("Numeric value in B array out of allowed range"); |
2500 | 709 | return -1; |
2501 | 101k | } |
2502 | 308k | #undef skip_to_comma_ |
2503 | 308k | } |
2504 | | |
2505 | | HTS_ALIGN32 |
2506 | | static int sam_parse_B_vals(char type, char *in, char **end, bam1_t *b) |
2507 | 207k | { |
2508 | 207k | int ctr = 0; |
2509 | 207k | uint32_t nalloc = 0; |
2510 | 207k | return sam_parse_B_vals_r(type, nalloc, in, end, b, &ctr); |
2511 | 207k | } |
2512 | | |
2513 | 409k | static inline unsigned int parse_sam_flag(char *v, char **rv, int *overflow) { |
2514 | 409k | if (*v >= '1' && *v <= '9') { |
2515 | 159k | return hts_str2uint(v, rv, 16, overflow); |
2516 | 159k | } |
2517 | 250k | else if (*v == '0') { |
2518 | | // handle single-digit "0" directly; otherwise it's hex or octal |
2519 | 131k | if (v[1] == '\t') { *rv = v+1; return 0; } |
2520 | 2.35k | else { |
2521 | 2.35k | unsigned long val = strtoul(v, rv, 0); |
2522 | 2.35k | if (val > 65535) { *overflow = 1; return 65535; } |
2523 | 2.29k | return val; |
2524 | 2.35k | } |
2525 | 131k | } |
2526 | 118k | else { |
2527 | | // TODO implement symbolic flag letters |
2528 | 118k | *rv = v; |
2529 | 118k | return 0; |
2530 | 118k | } |
2531 | 409k | } |
2532 | | |
2533 | | // Parse tag line and append to bam object b. |
2534 | | // Shared by both SAM and FASTQ parsers. |
2535 | | // |
2536 | | // The difference between the two is how lenient we are to recognising |
2537 | | // non-compliant strings. The FASTQ parser glosses over arbitrary |
2538 | | // non-SAM looking strings. |
2539 | | static inline int aux_parse(char *start, char *end, bam1_t *b, int lenient, |
2540 | 405k | khash_t(tag) *tag_whitelist) { |
2541 | 405k | int overflow = 0; |
2542 | 405k | int checkpoint; |
2543 | 405k | char logbuf[40]; |
2544 | 405k | char *q = start, *p = end; |
2545 | | |
2546 | 405k | #define _parse_err(cond, ...) \ |
2547 | 9.18M | do { \ |
2548 | 19.6M | if (cond) { \ |
2549 | 957 | if (lenient) { \ |
2550 | 0 | while (q < p && !isspace_c(*q)) \ |
2551 | 0 | q++; \ |
2552 | 0 | while (q < p && isspace_c(*q)) \ |
2553 | 0 | q++; \ |
2554 | 0 | b->l_data = checkpoint; \ |
2555 | 0 | goto loop; \ |
2556 | 957 | } else { \ |
2557 | 957 | hts_log_error(__VA_ARGS__); \ |
2558 | 957 | goto err_ret; \ |
2559 | 957 | } \ |
2560 | 957 | } \ |
2561 | 9.18M | } while (0) |
2562 | | |
2563 | 8.57M | while (q < p) loop: { |
2564 | 8.57M | char type; |
2565 | 8.57M | checkpoint = b->l_data; |
2566 | 8.57M | if (p - q < 5) { |
2567 | 193 | if (lenient) { |
2568 | 0 | break; |
2569 | 193 | } else { |
2570 | 193 | hts_log_error("Incomplete aux field"); |
2571 | 193 | goto err_ret; |
2572 | 193 | } |
2573 | 193 | } |
2574 | 4.28M | _parse_err(q[0] < '!' || q[1] < '!', "invalid aux tag id"); |
2575 | | |
2576 | 4.28M | if (lenient && (q[2] | q[4]) != ':') { |
2577 | 0 | while (q < p && !isspace_c(*q)) |
2578 | 0 | q++; |
2579 | 0 | while (q < p && isspace_c(*q)) |
2580 | 0 | q++; |
2581 | 0 | continue; |
2582 | 0 | } |
2583 | | |
2584 | 4.28M | if (tag_whitelist) { |
2585 | 0 | int tt = q[0]*256 + q[1]; |
2586 | 0 | if (kh_get(tag, tag_whitelist, tt) == kh_end(tag_whitelist)) { |
2587 | 0 | while (q < p && *q != '\t') |
2588 | 0 | q++; |
2589 | 0 | continue; |
2590 | 0 | } |
2591 | 0 | } |
2592 | | |
2593 | | // Copy over id |
2594 | 4.28M | if (possibly_expand_bam_data(b, 2) < 0) goto err_ret; |
2595 | 4.28M | memcpy(b->data + b->l_data, q, 2); b->l_data += 2; |
2596 | 4.28M | q += 3; type = *q++; ++q; // q points to value |
2597 | 4.28M | if (type != 'Z' && type != 'H') // the only zero length acceptable fields |
2598 | 3.89M | _parse_err(*q <= '\t', "incomplete aux field"); |
2599 | | |
2600 | | // Ensure enough space for a double + type allocated. |
2601 | 4.28M | if (possibly_expand_bam_data(b, 16) < 0) goto err_ret; |
2602 | | |
2603 | 4.28M | if (type == 'A' || type == 'a' || type == 'c' || type == 'C') { |
2604 | 1.55M | b->data[b->l_data++] = 'A'; |
2605 | 1.55M | b->data[b->l_data++] = *q++; |
2606 | 2.73M | } else if (type == 'i' || type == 'I') { |
2607 | 1.97M | if (*q == '-') { |
2608 | 1.65M | int32_t x = hts_str2int(q, &q, 32, &overflow); |
2609 | 1.65M | if (x >= INT8_MIN) { |
2610 | 797k | b->data[b->l_data++] = 'c'; |
2611 | 797k | b->data[b->l_data++] = x; |
2612 | 857k | } else if (x >= INT16_MIN) { |
2613 | 272k | b->data[b->l_data++] = 's'; |
2614 | 272k | i16_to_le(x, b->data + b->l_data); |
2615 | 272k | b->l_data += 2; |
2616 | 585k | } else { |
2617 | 585k | b->data[b->l_data++] = 'i'; |
2618 | 585k | i32_to_le(x, b->data + b->l_data); |
2619 | 585k | b->l_data += 4; |
2620 | 585k | } |
2621 | 1.65M | } else { |
2622 | 318k | uint32_t x = hts_str2uint(q, &q, 32, &overflow); |
2623 | 318k | if (x <= UINT8_MAX) { |
2624 | 175k | b->data[b->l_data++] = 'C'; |
2625 | 175k | b->data[b->l_data++] = x; |
2626 | 175k | } else if (x <= UINT16_MAX) { |
2627 | 139k | b->data[b->l_data++] = 'S'; |
2628 | 139k | u16_to_le(x, b->data + b->l_data); |
2629 | 139k | b->l_data += 2; |
2630 | 139k | } else { |
2631 | 3.46k | b->data[b->l_data++] = 'I'; |
2632 | 3.46k | u32_to_le(x, b->data + b->l_data); |
2633 | 3.46k | b->l_data += 4; |
2634 | 3.46k | } |
2635 | 318k | } |
2636 | 1.97M | } else if (type == 'f') { |
2637 | 78.8k | b->data[b->l_data++] = 'f'; |
2638 | 78.8k | float_to_le(strtod(q, &q), b->data + b->l_data); |
2639 | 78.8k | b->l_data += sizeof(float); |
2640 | 683k | } else if (type == 'd') { |
2641 | 80.0k | b->data[b->l_data++] = 'd'; |
2642 | 80.0k | double_to_le(strtod(q, &q), b->data + b->l_data); |
2643 | 80.0k | b->l_data += sizeof(double); |
2644 | 603k | } else if (type == 'Z' || type == 'H') { |
2645 | 395k | char *end = strchr(q, '\t'); |
2646 | 395k | if (!end) end = q + strlen(q); |
2647 | 395k | _parse_err(type == 'H' && ((end-q)&1) != 0, |
2648 | 395k | "hex field does not have an even number of digits"); |
2649 | 395k | b->data[b->l_data++] = type; |
2650 | 395k | if (possibly_expand_bam_data(b, end - q + 1) < 0) goto err_ret; |
2651 | 395k | memcpy(b->data + b->l_data, q, end - q); |
2652 | 395k | b->l_data += end - q; |
2653 | 395k | b->data[b->l_data++] = '\0'; |
2654 | 395k | q = end; |
2655 | 395k | } else if (type == 'B') { |
2656 | 207k | type = *q++; // q points to the first ',' following the typing byte |
2657 | 207k | _parse_err(*q && *q != ',' && *q != '\t', |
2658 | 207k | "B aux field type not followed by ','"); |
2659 | | |
2660 | 207k | if (sam_parse_B_vals(type, q, &q, b) < 0) |
2661 | 1.26k | goto err_ret; |
2662 | 207k | } else _parse_err(1, "unrecognized type %s", hts_strprint(logbuf, sizeof logbuf, '\'', &type, 1)); |
2663 | | |
2664 | 24.2M | while (*q > '\t') { q++; } // Skip any junk to next tab |
2665 | 4.28M | q++; |
2666 | 4.28M | } |
2667 | | |
2668 | 402k | _parse_err(!lenient && overflow != 0, "numeric value out of allowed range"); |
2669 | 402k | #undef _parse_err |
2670 | | |
2671 | 402k | return 0; |
2672 | | |
2673 | 2.41k | err_ret: |
2674 | 2.41k | return -2; |
2675 | 402k | } |
2676 | | |
2677 | | int sam_parse1(kstring_t *s, sam_hdr_t *h, bam1_t *b) |
2678 | 410k | { |
2679 | 1.66M | #define _read_token(_p) (_p); do { char *tab = strchr((_p), '\t'); if (!tab) goto err_ret; *tab = '\0'; (_p) = tab + 1; } while (0) |
2680 | | |
2681 | 410k | #if HTS_ALLOW_UNALIGNED != 0 && ULONG_MAX == 0xffffffffffffffff |
2682 | | |
2683 | | // Macro that operates on 64-bits at a time. |
2684 | 410k | #define COPY_MINUS_N(to,from,n,l,failed) \ |
2685 | 410k | do { \ |
2686 | 263k | uint64_u *from8 = (uint64_u *)(from); \ |
2687 | 263k | uint64_u *to8 = (uint64_u *)(to); \ |
2688 | 263k | uint64_t uflow = 0; \ |
2689 | 263k | size_t l8 = (l)>>3, i; \ |
2690 | 264k | for (i = 0; i < l8; i++) { \ |
2691 | 400 | to8[i] = from8[i] - (n)*0x0101010101010101UL; \ |
2692 | 400 | uflow |= to8[i]; \ |
2693 | 400 | } \ |
2694 | 270k | for (i<<=3; i < (l); ++i) { \ |
2695 | 6.22k | to[i] = from[i] - (n); \ |
2696 | 6.22k | uflow |= to[i]; \ |
2697 | 6.22k | } \ |
2698 | 263k | failed = (uflow & 0x8080808080808080UL) > 0; \ |
2699 | 263k | } while (0) |
2700 | | |
2701 | | #else |
2702 | | |
2703 | | // Basic version which operates a byte at a time |
2704 | | #define COPY_MINUS_N(to,from,n,l,failed) do { \ |
2705 | | uint8_t uflow = 0; \ |
2706 | | for (i = 0; i < (l); ++i) { \ |
2707 | | (to)[i] = (from)[i] - (n); \ |
2708 | | uflow |= (uint8_t) (to)[i]; \ |
2709 | | } \ |
2710 | | failed = (uflow & 0x80) > 0; \ |
2711 | | } while (0) |
2712 | | |
2713 | | #endif |
2714 | | |
2715 | 770k | #define _get_mem(type_t, x, b, l) if (possibly_expand_bam_data((b), (l)) < 0) goto err_ret; *(x) = (type_t*)((b)->data + (b)->l_data); (b)->l_data += (l) |
2716 | 4.46M | #define _parse_err(cond, ...) do { if (cond) { hts_log_error(__VA_ARGS__); goto err_ret; } } while (0) |
2717 | 1.52M | #define _parse_warn(cond, ...) do { if (cond) { hts_log_warning(__VA_ARGS__); } } while (0) |
2718 | | |
2719 | 410k | uint8_t *t; |
2720 | | |
2721 | 410k | char *p = s->s, *q; |
2722 | 410k | int i, overflow = 0; |
2723 | 410k | char logbuf[40]; |
2724 | 410k | hts_pos_t cigreflen; |
2725 | 410k | bam1_core_t *c = &b->core; |
2726 | | |
2727 | 410k | b->l_data = 0; |
2728 | 410k | memset(c, 0, 32); |
2729 | | |
2730 | | // qname |
2731 | 410k | q = _read_token(p); |
2732 | | |
2733 | 409k | _parse_warn(p - q <= 1, "empty query name"); |
2734 | 409k | _parse_err(p - q > 255, "query name too long"); |
2735 | | // resize large enough for name + extranul |
2736 | 409k | if (possibly_expand_bam_data(b, (p - q) + 4) < 0) goto err_ret; |
2737 | 409k | memcpy(b->data + b->l_data, q, p-q); b->l_data += p-q; |
2738 | | |
2739 | 409k | c->l_extranul = (4 - (b->l_data & 3)) & 3; |
2740 | 409k | memcpy(b->data + b->l_data, "\0\0\0\0", c->l_extranul); |
2741 | 409k | b->l_data += c->l_extranul; |
2742 | | |
2743 | 409k | c->l_qname = p - q + c->l_extranul; |
2744 | | |
2745 | | // flag |
2746 | 409k | c->flag = parse_sam_flag(p, &p, &overflow); |
2747 | 409k | if (*p++ != '\t') goto err_ret; // malformated flag |
2748 | | |
2749 | | // chr |
2750 | 408k | q = _read_token(p); |
2751 | 408k | if (strcmp(q, "*")) { |
2752 | 392k | _parse_err(h->n_targets == 0, "no SQ lines present in the header"); |
2753 | 392k | c->tid = bam_name2id(h, q); |
2754 | 392k | _parse_err(c->tid < -1, "failed to parse header"); |
2755 | 392k | _parse_warn(c->tid < 0, "unrecognized reference name %s; treated as unmapped", hts_strprint(logbuf, sizeof logbuf, '"', q, SIZE_MAX)); |
2756 | 392k | } else c->tid = -1; |
2757 | | |
2758 | | // pos |
2759 | 408k | c->pos = hts_str2uint(p, &p, 62, &overflow) - 1; |
2760 | 408k | if (*p++ != '\t') goto err_ret; |
2761 | 407k | if (c->pos < 0 && c->tid >= 0) { |
2762 | 107k | _parse_warn(1, "mapped query cannot have zero coordinate; treated as unmapped"); |
2763 | 107k | c->tid = -1; |
2764 | 107k | } |
2765 | 407k | if (c->tid < 0) c->flag |= BAM_FUNMAP; |
2766 | | |
2767 | | // mapq |
2768 | 407k | c->qual = hts_str2uint(p, &p, 8, &overflow); |
2769 | 407k | if (*p++ != '\t') goto err_ret; |
2770 | | // cigar |
2771 | 407k | if (*p != '*') { |
2772 | 371k | uint32_t *cigar = NULL; |
2773 | 371k | int old_l_data = b->l_data; |
2774 | 371k | int n_cigar = bam_parse_cigar(p, &p, b); |
2775 | 371k | if (n_cigar < 1 || *p++ != '\t') goto err_ret; |
2776 | 370k | cigar = (uint32_t *)(b->data + old_l_data); |
2777 | | |
2778 | | // can't use bam_endpos() directly as some fields not yet set up |
2779 | 370k | cigreflen = (!(c->flag&BAM_FUNMAP))? bam_cigar2rlen(c->n_cigar, cigar) : 1; |
2780 | 370k | if (cigreflen == 0) cigreflen = 1; |
2781 | 370k | } else { |
2782 | 36.2k | _parse_warn(!(c->flag&BAM_FUNMAP), "mapped query must have a CIGAR; treated as unmapped"); |
2783 | 36.2k | c->flag |= BAM_FUNMAP; |
2784 | 36.2k | q = _read_token(p); |
2785 | 36.2k | cigreflen = 1; |
2786 | 36.2k | } |
2787 | 406k | _parse_err(HTS_POS_MAX - cigreflen <= c->pos, |
2788 | 406k | "read ends beyond highest supported position"); |
2789 | 406k | c->bin = hts_reg2bin(c->pos, c->pos + cigreflen, 14, 5); |
2790 | | |
2791 | | // mate chr |
2792 | 406k | q = _read_token(p); |
2793 | 406k | if (strcmp(q, "=") == 0) { |
2794 | 148 | c->mtid = c->tid; |
2795 | 405k | } else if (strcmp(q, "*") == 0) { |
2796 | 1.64k | c->mtid = -1; |
2797 | 404k | } else { |
2798 | 404k | c->mtid = bam_name2id(h, q); |
2799 | 404k | _parse_err(c->mtid < -1, "failed to parse header"); |
2800 | 404k | _parse_warn(c->mtid < 0, "unrecognized mate reference name %s; treated as unmapped", hts_strprint(logbuf, sizeof logbuf, '"', q, SIZE_MAX)); |
2801 | 404k | } |
2802 | | |
2803 | | // mpos |
2804 | 406k | c->mpos = hts_str2uint(p, &p, 62, &overflow) - 1; |
2805 | 406k | if (*p++ != '\t') goto err_ret; |
2806 | 405k | if (c->mpos < 0 && c->mtid >= 0) { |
2807 | 171k | _parse_warn(1, "mapped mate cannot have zero coordinate; treated as unmapped"); |
2808 | 171k | c->mtid = -1; |
2809 | 171k | } |
2810 | | |
2811 | | // tlen |
2812 | 405k | c->isize = hts_str2int(p, &p, 63, &overflow); |
2813 | 405k | if (*p++ != '\t') goto err_ret; |
2814 | 405k | _parse_err(overflow, "number outside allowed range"); |
2815 | | |
2816 | | // seq |
2817 | 405k | q = _read_token(p); |
2818 | 405k | if (strcmp(q, "*")) { |
2819 | 365k | _parse_err(p - q - 1 > INT32_MAX, "read sequence is too long"); |
2820 | 365k | c->l_qseq = p - q - 1; |
2821 | 365k | i = (c->l_qseq + 1) >> 1; |
2822 | 365k | _get_mem(uint8_t, &t, b, i); |
2823 | | |
2824 | 365k | unsigned int lqs2 = c->l_qseq&~1, i; |
2825 | 469k | for (i = 0; i < lqs2; i+=2) |
2826 | 103k | t[i>>1] = (seq_nt16_table[(unsigned char)q[i]] << 4) | seq_nt16_table[(unsigned char)q[i+1]]; |
2827 | 463k | for (; i < c->l_qseq; ++i) |
2828 | 97.7k | t[i>>1] = seq_nt16_table[(unsigned char)q[i]] << ((~i&1)<<2); |
2829 | 365k | } else c->l_qseq = 0; |
2830 | | |
2831 | | // qual |
2832 | 810k | _get_mem(uint8_t, &t, b, c->l_qseq); |
2833 | 810k | if (p[0] == '*' && (p[1] == '\t' || p[1] == '\0')) { |
2834 | 141k | memset(t, 0xff, c->l_qseq); |
2835 | 141k | p += 2; |
2836 | 264k | } else { |
2837 | 264k | int failed = 0; |
2838 | 264k | _parse_err(s->l - (p - s->s) < c->l_qseq |
2839 | 264k | || (p[c->l_qseq] != '\t' && p[c->l_qseq] != '\0'), |
2840 | 264k | "SEQ and QUAL are of different length"); |
2841 | 263k | COPY_MINUS_N(t, p, 33, c->l_qseq, failed); |
2842 | 263k | _parse_err(failed, "invalid QUAL character"); |
2843 | 263k | p += c->l_qseq + 1; |
2844 | 263k | } |
2845 | | |
2846 | | // aux |
2847 | 405k | if (aux_parse(p, s->s + s->l, b, 0, NULL) < 0) |
2848 | 2.41k | goto err_ret; |
2849 | | |
2850 | 402k | int t2c = bam_tag2cigar(b, 1, 1); |
2851 | 402k | if (t2c == 0) { |
2852 | | // Check SEQ and CIGAR consistency. (Do this after parsing the CG tag) |
2853 | 397k | if (c->l_qseq) { |
2854 | 113k | hts_pos_t ql = bam_cigar2qlen(c->n_cigar, |
2855 | 113k | (uint32_t*)(b->data + c->l_qname)); |
2856 | 113k | _parse_err(c->n_cigar && ql != c->l_qseq, |
2857 | 113k | "CIGAR and query sequence are of different length"); |
2858 | 113k | } |
2859 | 397k | } else if (t2c < 0) { |
2860 | 67 | return -2; |
2861 | 67 | } |
2862 | | |
2863 | 402k | return 0; |
2864 | | |
2865 | 0 | #undef _parse_warn |
2866 | 0 | #undef _parse_err |
2867 | 0 | #undef _get_mem |
2868 | 0 | #undef _read_token |
2869 | 7.66k | err_ret: |
2870 | 7.66k | return -2; |
2871 | 402k | } |
2872 | | |
2873 | 371k | static uint32_t read_ncigar(const char *q) { |
2874 | 371k | uint32_t n_cigar = 0; |
2875 | 2.56M | for (; *q && *q != '\t'; ++q) |
2876 | 2.19M | if (!isdigit_c(*q)) ++n_cigar; |
2877 | 371k | if (!n_cigar) { |
2878 | 217 | hts_log_error("No CIGAR operations"); |
2879 | 217 | return 0; |
2880 | 217 | } |
2881 | 371k | if (n_cigar >= 2147483647) { |
2882 | 0 | hts_log_error("Too many CIGAR operations"); |
2883 | 0 | return 0; |
2884 | 0 | } |
2885 | | |
2886 | 371k | return n_cigar; |
2887 | 371k | } |
2888 | | |
2889 | | /*! @function |
2890 | | @abstract Parse a CIGAR string into preallocated a uint32_t array |
2891 | | @param in [in] pointer to the source string |
2892 | | @param a_cigar [out] address of the destination uint32_t buffer |
2893 | | @return number of processed input characters; 0 on error |
2894 | | */ |
2895 | 371k | static int parse_cigar(const char *in, uint32_t *a_cigar, uint32_t n_cigar) { |
2896 | 371k | int i, overflow = 0; |
2897 | 371k | const char *p = in; |
2898 | 1.07M | for (i = 0; i < n_cigar; i++) { |
2899 | 700k | uint32_t len; |
2900 | 700k | int op; |
2901 | 700k | char *q; |
2902 | 700k | len = hts_str2uint(p, &q, 28, &overflow)<<BAM_CIGAR_SHIFT; |
2903 | 700k | if (q == p) { |
2904 | 326 | hts_log_error("CIGAR length invalid at position %d (%s)", (int)(i+1), p); |
2905 | 326 | return 0; |
2906 | 326 | } |
2907 | 699k | if (overflow) { |
2908 | 98 | hts_log_error("CIGAR length too long at position %d (%.*s)", (int)(i+1), (int)(q-p+1), p); |
2909 | 98 | return 0; |
2910 | 98 | } |
2911 | 699k | p = q; |
2912 | 699k | op = bam_cigar_table[(unsigned char)*p++]; |
2913 | 699k | if (op < 0) { |
2914 | 384 | hts_log_error("Unrecognized CIGAR operator"); |
2915 | 384 | return 0; |
2916 | 384 | } |
2917 | 699k | a_cigar[i] = len; |
2918 | 699k | a_cigar[i] |= op; |
2919 | 699k | } |
2920 | | |
2921 | 370k | return p-in; |
2922 | 371k | } |
2923 | | |
2924 | 0 | ssize_t sam_parse_cigar(const char *in, char **end, uint32_t **a_cigar, size_t *a_mem) { |
2925 | 0 | size_t n_cigar = 0; |
2926 | 0 | int diff; |
2927 | |
|
2928 | 0 | if (!in || !a_cigar || !a_mem) { |
2929 | 0 | hts_log_error("NULL pointer arguments"); |
2930 | 0 | return -1; |
2931 | 0 | } |
2932 | 0 | if (end) *end = (char *)in; |
2933 | |
|
2934 | 0 | if (*in == '*') { |
2935 | 0 | if (end) (*end)++; |
2936 | 0 | return 0; |
2937 | 0 | } |
2938 | 0 | n_cigar = read_ncigar(in); |
2939 | 0 | if (!n_cigar) return 0; |
2940 | 0 | if (n_cigar > *a_mem) { |
2941 | 0 | uint32_t *a_tmp = hts_realloc_p(*a_cigar, sizeof(**a_cigar), n_cigar); |
2942 | 0 | if (a_tmp) { |
2943 | 0 | *a_cigar = a_tmp; |
2944 | 0 | *a_mem = n_cigar; |
2945 | 0 | } else { |
2946 | 0 | hts_log_error("Memory allocation error"); |
2947 | 0 | return -1; |
2948 | 0 | } |
2949 | 0 | } |
2950 | | |
2951 | 0 | if (!(diff = parse_cigar(in, *a_cigar, n_cigar))) return -1; |
2952 | 0 | if (end) *end = (char *)in+diff; |
2953 | |
|
2954 | 0 | return n_cigar; |
2955 | 0 | } |
2956 | | |
2957 | 371k | ssize_t bam_parse_cigar(const char *in, char **end, bam1_t *b) { |
2958 | 371k | size_t n_cigar = 0; |
2959 | 371k | int diff; |
2960 | | |
2961 | 371k | if (!in || !b) { |
2962 | 0 | hts_log_error("NULL pointer arguments"); |
2963 | 0 | return -1; |
2964 | 0 | } |
2965 | 371k | if (end) *end = (char *)in; |
2966 | | |
2967 | 371k | n_cigar = (*in == '*') ? 0 : read_ncigar(in); |
2968 | 371k | if (!n_cigar && b->core.n_cigar == 0) { |
2969 | 217 | if (end) *end = (char *)in+1; |
2970 | 217 | return 0; |
2971 | 217 | } |
2972 | | |
2973 | 371k | ssize_t cig_diff = n_cigar - b->core.n_cigar; |
2974 | 371k | if (cig_diff > 0 && |
2975 | 371k | possibly_expand_bam_data(b, cig_diff * sizeof(uint32_t)) < 0) { |
2976 | 0 | hts_log_error("Memory allocation error"); |
2977 | 0 | return -1; |
2978 | 0 | } |
2979 | | |
2980 | 371k | uint32_t *cig = bam_get_cigar(b); |
2981 | 371k | if ((uint8_t *)cig != b->data + b->l_data) { |
2982 | | // Modifying an BAM existing BAM record |
2983 | 0 | uint8_t *seq = bam_get_seq(b); |
2984 | 0 | memmove(cig + n_cigar, seq, (b->data + b->l_data) - seq); |
2985 | 0 | } |
2986 | | |
2987 | 371k | if (n_cigar) { |
2988 | 371k | if (!(diff = parse_cigar(in, cig, n_cigar))) |
2989 | 808 | return -1; |
2990 | 371k | } else { |
2991 | 0 | diff = 1; // handle "*" |
2992 | 0 | } |
2993 | | |
2994 | 370k | b->l_data += cig_diff * sizeof(uint32_t); |
2995 | 370k | b->core.n_cigar = n_cigar; |
2996 | 370k | if (end) *end = (char *)in + diff; |
2997 | | |
2998 | 370k | return n_cigar; |
2999 | 371k | } |
3000 | | |
3001 | | /* |
3002 | | * ----------------------------------------------------------------------------- |
3003 | | * SAM threading |
3004 | | */ |
3005 | | // Size of SAM text block (reading) |
3006 | 0 | #define SAM_NBYTES 240000 |
3007 | | |
3008 | | // Number of BAM records (writing, up to NB_mem in size) |
3009 | 0 | #define SAM_NBAM 1000 |
3010 | | |
3011 | | struct SAM_state; |
3012 | | |
3013 | | // Output job - a block of BAM records |
3014 | | typedef struct sp_bams { |
3015 | | struct sp_bams *next; |
3016 | | int serial; |
3017 | | |
3018 | | bam1_t *bams; |
3019 | | int nbams, abams; // used and alloc for bams[] array |
3020 | | size_t bam_mem; // very approximate total size |
3021 | | |
3022 | | struct SAM_state *fd; |
3023 | | } sp_bams; |
3024 | | |
3025 | | // Input job - a block of SAM text |
3026 | | typedef struct sp_lines { |
3027 | | struct sp_lines *next; |
3028 | | int serial; |
3029 | | |
3030 | | char *data; |
3031 | | int data_size; |
3032 | | int alloc; |
3033 | | |
3034 | | struct SAM_state *fd; |
3035 | | sp_bams *bams; |
3036 | | } sp_lines; |
3037 | | |
3038 | | enum sam_cmd { |
3039 | | SAM_NONE = 0, |
3040 | | SAM_CLOSE, |
3041 | | SAM_CLOSE_DONE, |
3042 | | SAM_AT_EOF, |
3043 | | }; |
3044 | | |
3045 | | typedef struct SAM_state { |
3046 | | sam_hdr_t *h; |
3047 | | |
3048 | | hts_tpool *p; |
3049 | | int own_pool; |
3050 | | pthread_mutex_t lines_m; |
3051 | | hts_tpool_process *q; |
3052 | | pthread_t dispatcher; |
3053 | | int dispatcher_set; |
3054 | | |
3055 | | sp_lines *lines; |
3056 | | sp_bams *bams; |
3057 | | |
3058 | | sp_bams *curr_bam; |
3059 | | int curr_idx; |
3060 | | int serial; |
3061 | | |
3062 | | // Be warned: moving these mutexes around in this struct can reduce |
3063 | | // threading performance by up to 70%! |
3064 | | pthread_mutex_t command_m; |
3065 | | pthread_cond_t command_c; |
3066 | | enum sam_cmd command; |
3067 | | |
3068 | | // One of the E* errno codes |
3069 | | int errcode; |
3070 | | |
3071 | | htsFile *fp; |
3072 | | } SAM_state; |
3073 | | |
3074 | | // Returns a SAM_state struct from a generic hFILE. |
3075 | | // |
3076 | | // Returns NULL on failure. |
3077 | 0 | static SAM_state *sam_state_create(htsFile *fp) { |
3078 | | // Ideally sam_open wouldn't be a #define to hts_open but instead would |
3079 | | // be a redirect call with an additional 'S' mode. This in turn would |
3080 | | // correctly set the designed format to sam instead of a generic |
3081 | | // text_format. |
3082 | 0 | if (fp->format.format != sam && fp->format.format != text_format) |
3083 | 0 | return NULL; |
3084 | | |
3085 | 0 | SAM_state *fd = calloc(1, sizeof(*fd)); |
3086 | 0 | if (!fd) |
3087 | 0 | return NULL; |
3088 | | |
3089 | 0 | fp->state = fd; |
3090 | 0 | fd->fp = fp; |
3091 | |
|
3092 | 0 | return fd; |
3093 | 0 | } |
3094 | | |
3095 | | static int sam_format1_append(const bam_hdr_t *h, const bam1_t *b, kstring_t *str); |
3096 | | static void *sam_format_worker(void *arg); |
3097 | | |
3098 | 0 | static void sam_state_err(SAM_state *fd, int errcode) { |
3099 | 0 | pthread_mutex_lock(&fd->command_m); |
3100 | 0 | if (!fd->errcode) |
3101 | 0 | fd->errcode = errcode; |
3102 | 0 | pthread_mutex_unlock(&fd->command_m); |
3103 | 0 | } |
3104 | | |
3105 | 0 | static void sam_free_sp_bams(sp_bams *b) { |
3106 | 0 | if (!b) |
3107 | 0 | return; |
3108 | | |
3109 | 0 | if (b->bams) { |
3110 | 0 | int i; |
3111 | 0 | for (i = 0; i < b->abams; i++) { |
3112 | 0 | if (b->bams[i].data) |
3113 | 0 | free(b->bams[i].data); |
3114 | 0 | } |
3115 | 0 | free(b->bams); |
3116 | 0 | } |
3117 | 0 | free(b); |
3118 | 0 | } |
3119 | | |
3120 | | // Destroys the state produce by sam_state_create. |
3121 | 35.7k | int sam_state_destroy(htsFile *fp) { |
3122 | 35.7k | int ret = 0; |
3123 | | |
3124 | 35.7k | if (!fp->state) |
3125 | 35.7k | return 0; |
3126 | | |
3127 | 0 | SAM_state *fd = fp->state; |
3128 | 0 | if (fd->p) { |
3129 | 0 | if (fd->h) { |
3130 | | // Notify sam_dispatcher we're closing |
3131 | 0 | pthread_mutex_lock(&fd->command_m); |
3132 | 0 | if (fd->command != SAM_CLOSE_DONE) |
3133 | 0 | fd->command = SAM_CLOSE; |
3134 | 0 | pthread_cond_signal(&fd->command_c); |
3135 | 0 | ret = -fd->errcode; |
3136 | 0 | if (fd->q) |
3137 | 0 | hts_tpool_wake_dispatch(fd->q); // unstick the reader |
3138 | |
|
3139 | 0 | if (!fp->is_write && fd->q && fd->dispatcher_set) { |
3140 | 0 | for (;;) { |
3141 | | // Avoid deadlocks with dispatcher |
3142 | 0 | if (fd->command == SAM_CLOSE_DONE) |
3143 | 0 | break; |
3144 | 0 | hts_tpool_wake_dispatch(fd->q); |
3145 | 0 | pthread_mutex_unlock(&fd->command_m); |
3146 | 0 | hts_usleep(10000); |
3147 | 0 | pthread_mutex_lock(&fd->command_m); |
3148 | 0 | } |
3149 | 0 | } |
3150 | 0 | pthread_mutex_unlock(&fd->command_m); |
3151 | |
|
3152 | 0 | if (fp->is_write) { |
3153 | | // Dispatch the last partial block. |
3154 | 0 | sp_bams *gb = fd->curr_bam; |
3155 | 0 | if (!ret && gb && gb->nbams > 0 && fd->q) |
3156 | 0 | ret = hts_tpool_dispatch(fd->p, fd->q, sam_format_worker, gb); |
3157 | | |
3158 | | // Flush and drain output |
3159 | 0 | if (fd->q) |
3160 | 0 | hts_tpool_process_flush(fd->q); |
3161 | 0 | pthread_mutex_lock(&fd->command_m); |
3162 | 0 | if (!ret) ret = -fd->errcode; |
3163 | 0 | pthread_mutex_unlock(&fd->command_m); |
3164 | |
|
3165 | 0 | while (!ret && fd->q && !hts_tpool_process_empty(fd->q)) { |
3166 | 0 | hts_usleep(10000); |
3167 | 0 | pthread_mutex_lock(&fd->command_m); |
3168 | 0 | ret = -fd->errcode; |
3169 | | // not empty but shutdown implies error |
3170 | 0 | if (hts_tpool_process_is_shutdown(fd->q) && !ret) |
3171 | 0 | ret = EIO; |
3172 | 0 | pthread_mutex_unlock(&fd->command_m); |
3173 | 0 | } |
3174 | 0 | if (fd->q) |
3175 | 0 | hts_tpool_process_shutdown(fd->q); |
3176 | 0 | } |
3177 | | |
3178 | | // Wait for it to acknowledge |
3179 | 0 | if (fd->dispatcher_set) |
3180 | 0 | pthread_join(fd->dispatcher, NULL); |
3181 | 0 | if (!ret) ret = -fd->errcode; |
3182 | 0 | } |
3183 | | |
3184 | | // Tidy up memory |
3185 | 0 | if (fd->q) |
3186 | 0 | hts_tpool_process_destroy(fd->q); |
3187 | |
|
3188 | 0 | if (fd->own_pool && fp->format.compression == no_compression) { |
3189 | 0 | hts_tpool_destroy(fd->p); |
3190 | 0 | fd->p = NULL; |
3191 | 0 | } |
3192 | 0 | pthread_mutex_destroy(&fd->lines_m); |
3193 | 0 | pthread_mutex_destroy(&fd->command_m); |
3194 | 0 | pthread_cond_destroy(&fd->command_c); |
3195 | |
|
3196 | 0 | sp_lines *l = fd->lines; |
3197 | 0 | while (l) { |
3198 | 0 | sp_lines *n = l->next; |
3199 | 0 | free(l->data); |
3200 | 0 | free(l); |
3201 | 0 | l = n; |
3202 | 0 | } |
3203 | |
|
3204 | 0 | sp_bams *b = fd->bams; |
3205 | 0 | while (b) { |
3206 | 0 | if (fd->curr_bam == b) |
3207 | 0 | fd->curr_bam = NULL; |
3208 | 0 | sp_bams *n = b->next; |
3209 | 0 | sam_free_sp_bams(b); |
3210 | 0 | b = n; |
3211 | 0 | } |
3212 | |
|
3213 | 0 | if (fd->curr_bam) |
3214 | 0 | sam_free_sp_bams(fd->curr_bam); |
3215 | | |
3216 | | // Decrement counter by one, maybe destroying too. |
3217 | | // This is to permit the caller using bam_hdr_destroy |
3218 | | // before sam_close without triggering decode errors |
3219 | | // in the background threads. |
3220 | 0 | bam_hdr_destroy(fd->h); |
3221 | 0 | } |
3222 | |
|
3223 | 0 | free(fp->state); |
3224 | 0 | fp->state = NULL; |
3225 | 0 | return ret; |
3226 | 35.7k | } |
3227 | | |
3228 | | // Cleanup function - job for sam_parse_worker; result for sam_format_worker |
3229 | 0 | static void cleanup_sp_lines(void *arg) { |
3230 | 0 | sp_lines *gl = (sp_lines *)arg; |
3231 | 0 | if (!gl) return; |
3232 | | |
3233 | | // Should always be true for lines passed to / from thread workers. |
3234 | 0 | assert(gl->next == NULL); |
3235 | |
|
3236 | 0 | free(gl->data); |
3237 | 0 | sam_free_sp_bams(gl->bams); |
3238 | 0 | free(gl); |
3239 | 0 | } |
3240 | | |
3241 | | // Run from one of the worker threads. |
3242 | | // Convert a passed in array of lines to array of BAMs, returning |
3243 | | // the result back to the thread queue. |
3244 | 0 | static void *sam_parse_worker(void *arg) { |
3245 | 0 | sp_lines *gl = (sp_lines *)arg; |
3246 | 0 | sp_bams *gb = NULL; |
3247 | 0 | char *lines = gl->data; |
3248 | 0 | int i; |
3249 | 0 | bam1_t *b; |
3250 | 0 | SAM_state *fd = gl->fd; |
3251 | | |
3252 | | // Use a block of BAM structs we had earlier if available. |
3253 | 0 | pthread_mutex_lock(&fd->lines_m); |
3254 | 0 | if (fd->bams) { |
3255 | 0 | gb = fd->bams; |
3256 | 0 | fd->bams = gb->next; |
3257 | 0 | } |
3258 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3259 | |
|
3260 | 0 | if (gb == NULL) { |
3261 | 0 | gb = calloc(1, sizeof(*gb)); |
3262 | 0 | if (!gb) { |
3263 | 0 | return NULL; |
3264 | 0 | } |
3265 | 0 | gb->abams = 100; |
3266 | 0 | gb->bams = b = calloc(gb->abams, sizeof(*b)); |
3267 | 0 | if (!gb->bams) { |
3268 | 0 | sam_state_err(fd, ENOMEM); |
3269 | 0 | goto err; |
3270 | 0 | } |
3271 | 0 | gb->nbams = 0; |
3272 | 0 | gb->bam_mem = 0; |
3273 | 0 | } |
3274 | 0 | gb->serial = gl->serial; |
3275 | 0 | gb->next = NULL; |
3276 | |
|
3277 | 0 | b = (bam1_t *)gb->bams; |
3278 | 0 | if (!b) { |
3279 | 0 | sam_state_err(fd, ENOMEM); |
3280 | 0 | goto err; |
3281 | 0 | } |
3282 | | |
3283 | 0 | i = 0; |
3284 | 0 | char *cp = lines, *cp_end = lines + gl->data_size; |
3285 | 0 | while (cp < cp_end) { |
3286 | 0 | if (i >= gb->abams) { |
3287 | 0 | int old_abams = gb->abams; |
3288 | 0 | gb->abams *= 2; |
3289 | 0 | b = hts_realloc_p(gb->bams, sizeof(bam1_t), gb->abams); |
3290 | 0 | if (!b) { |
3291 | 0 | gb->abams /= 2; |
3292 | 0 | sam_state_err(fd, ENOMEM); |
3293 | 0 | goto err; |
3294 | 0 | } |
3295 | 0 | memset(&b[old_abams], 0, (gb->abams - old_abams)*sizeof(*b)); |
3296 | 0 | gb->bams = b; |
3297 | 0 | } |
3298 | | |
3299 | | // Ideally we'd get sam_parse1 to return the number of |
3300 | | // bytes decoded and to be able to stop on newline as |
3301 | | // well as \0. |
3302 | | // |
3303 | | // We can then avoid the additional strchr loop. |
3304 | | // It's around 6% of our CPU cost, albeit threadable. |
3305 | | // |
3306 | | // However this is an API change so for now we copy. |
3307 | | |
3308 | 0 | char *nl = memchr(cp, '\n', cp_end - cp); |
3309 | 0 | char *line_end; |
3310 | 0 | if (nl) { |
3311 | 0 | line_end = nl; |
3312 | 0 | if (line_end > cp && *(line_end - 1) == '\r') |
3313 | 0 | line_end--; |
3314 | 0 | nl++; |
3315 | 0 | } else { |
3316 | 0 | nl = line_end = cp_end; |
3317 | 0 | } |
3318 | 0 | *line_end = '\0'; |
3319 | 0 | kstring_t ks = { line_end - cp, gl->alloc, cp }; |
3320 | 0 | if (sam_parse1(&ks, fd->h, &b[i]) < 0) { |
3321 | 0 | sam_state_err(fd, errno ? errno : EIO); |
3322 | 0 | cleanup_sp_lines(gl); |
3323 | 0 | goto err; |
3324 | 0 | } |
3325 | | |
3326 | 0 | cp = nl; |
3327 | 0 | i++; |
3328 | 0 | } |
3329 | 0 | gb->nbams = i; |
3330 | |
|
3331 | 0 | pthread_mutex_lock(&fd->lines_m); |
3332 | 0 | gl->next = fd->lines; |
3333 | 0 | fd->lines = gl; |
3334 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3335 | 0 | return gb; |
3336 | | |
3337 | 0 | err: |
3338 | 0 | sam_free_sp_bams(gb); |
3339 | 0 | return NULL; |
3340 | 0 | } |
3341 | | |
3342 | 0 | static void *sam_parse_eof(void *arg) { |
3343 | 0 | return NULL; |
3344 | 0 | } |
3345 | | |
3346 | | // Cleanup function - result for sam_parse_worker; job for sam_format_worker |
3347 | 0 | static void cleanup_sp_bams(void *arg) { |
3348 | 0 | sam_free_sp_bams((sp_bams *) arg); |
3349 | 0 | } |
3350 | | |
3351 | | // Runs in its own thread. |
3352 | | // Reads a block of text (SAM) and sends a new job to the thread queue to |
3353 | | // translate this to BAM. |
3354 | 0 | static void *sam_dispatcher_read(void *vp) { |
3355 | 0 | htsFile *fp = vp; |
3356 | 0 | kstring_t line = {0}; |
3357 | 0 | int line_frag = 0; |
3358 | 0 | SAM_state *fd = fp->state; |
3359 | 0 | sp_lines *l = NULL; |
3360 | | |
3361 | | // Pre-allocate buffer for left-over bits of line (exact size doesn't |
3362 | | // matter as it will grow if necessary). |
3363 | 0 | if (ks_resize(&line, 1000) < 0) |
3364 | 0 | goto err; |
3365 | | |
3366 | 0 | for (;;) { |
3367 | | // Check for command |
3368 | 0 | pthread_mutex_lock(&fd->command_m); |
3369 | 0 | switch (fd->command) { |
3370 | | |
3371 | 0 | case SAM_CLOSE: |
3372 | 0 | pthread_cond_signal(&fd->command_c); |
3373 | 0 | pthread_mutex_unlock(&fd->command_m); |
3374 | 0 | hts_tpool_process_shutdown(fd->q); |
3375 | 0 | goto tidyup; |
3376 | | |
3377 | 0 | default: |
3378 | 0 | break; |
3379 | 0 | } |
3380 | 0 | pthread_mutex_unlock(&fd->command_m); |
3381 | |
|
3382 | 0 | pthread_mutex_lock(&fd->lines_m); |
3383 | 0 | if (fd->lines) { |
3384 | | // reuse existing line buffer |
3385 | 0 | l = fd->lines; |
3386 | 0 | fd->lines = l->next; |
3387 | 0 | } |
3388 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3389 | |
|
3390 | 0 | if (l == NULL) { |
3391 | | // none to reuse, to create a new one |
3392 | 0 | l = calloc(1, sizeof(*l)); |
3393 | 0 | if (!l) |
3394 | 0 | goto err; |
3395 | 0 | l->alloc = SAM_NBYTES; |
3396 | 0 | l->data = hts_malloc_ps(sizeof(*l->data), l->alloc, 8); // +8 for optimisation in sam_parse1 |
3397 | 0 | if (!l->data) { |
3398 | 0 | free(l); |
3399 | 0 | l = NULL; |
3400 | 0 | goto err; |
3401 | 0 | } |
3402 | 0 | l->fd = fd; |
3403 | 0 | } |
3404 | 0 | l->next = NULL; |
3405 | |
|
3406 | 0 | if (l->alloc < line_frag+SAM_NBYTES/2) { |
3407 | 0 | char *rp = hts_realloc_ps(l->data, sizeof(*rp), |
3408 | 0 | line_frag, SAM_NBYTES/2 + 8); |
3409 | 0 | if (!rp) |
3410 | 0 | goto err; |
3411 | 0 | l->alloc = line_frag+SAM_NBYTES/2; |
3412 | 0 | l->data = rp; |
3413 | 0 | } |
3414 | 0 | memcpy(l->data, line.s, line_frag); |
3415 | |
|
3416 | 0 | l->data_size = line_frag; |
3417 | 0 | ssize_t nbytes; |
3418 | 0 | longer_line: |
3419 | 0 | if (fp->is_bgzf) |
3420 | 0 | nbytes = bgzf_read(fp->fp.bgzf, l->data + line_frag, l->alloc - line_frag); |
3421 | 0 | else |
3422 | 0 | nbytes = hread(fp->fp.hfile, l->data + line_frag, l->alloc - line_frag); |
3423 | 0 | if (nbytes < 0) { |
3424 | 0 | sam_state_err(fd, errno ? errno : EIO); |
3425 | 0 | goto err; |
3426 | 0 | } else if (nbytes == 0) |
3427 | 0 | break; // EOF |
3428 | 0 | l->data_size += nbytes; |
3429 | | |
3430 | | // trim to last \n. Maybe \r\n, but that's still fine |
3431 | 0 | if (nbytes == l->alloc - line_frag) { |
3432 | 0 | char *cp_end = l->data + l->data_size; |
3433 | 0 | char *cp = cp_end-1; |
3434 | |
|
3435 | 0 | while (cp > (char *)l->data && *cp != '\n') |
3436 | 0 | cp--; |
3437 | | |
3438 | | // entire buffer is part of a single line |
3439 | 0 | if (cp == l->data) { |
3440 | 0 | line_frag = l->data_size; |
3441 | 0 | char *rp = hts_realloc_pse(l->data, 2, l->alloc, 0, 8); |
3442 | 0 | if (!rp) |
3443 | 0 | goto err; |
3444 | 0 | l->alloc *= 2; |
3445 | 0 | l->data = rp; |
3446 | 0 | assert(l->alloc >= l->data_size); |
3447 | 0 | assert(l->alloc >= line_frag); |
3448 | 0 | assert(l->alloc >= l->alloc - line_frag); |
3449 | 0 | goto longer_line; |
3450 | 0 | } |
3451 | 0 | cp++; |
3452 | | |
3453 | | // line holds the remainder of our line. |
3454 | 0 | if (ks_resize(&line, cp_end - cp) < 0) |
3455 | 0 | goto err; |
3456 | 0 | memcpy(line.s, cp, cp_end - cp); |
3457 | 0 | line_frag = cp_end - cp; |
3458 | 0 | l->data_size = l->alloc - line_frag; |
3459 | 0 | } else { |
3460 | | // out of buffer |
3461 | 0 | line_frag = 0; |
3462 | 0 | } |
3463 | | |
3464 | 0 | l->serial = fd->serial++; |
3465 | | //fprintf(stderr, "Dispatching %p, %d bytes, serial %d\n", l, l->data_size, l->serial); |
3466 | 0 | if (hts_tpool_dispatch3(fd->p, fd->q, sam_parse_worker, l, |
3467 | 0 | cleanup_sp_lines, cleanup_sp_bams, 0) < 0) |
3468 | 0 | goto err; |
3469 | 0 | pthread_mutex_lock(&fd->command_m); |
3470 | 0 | if (fd->command == SAM_CLOSE) { |
3471 | 0 | pthread_mutex_unlock(&fd->command_m); |
3472 | 0 | l = NULL; |
3473 | 0 | goto tidyup; |
3474 | 0 | } |
3475 | 0 | l = NULL; // Now "owned" by sam_parse_worker() |
3476 | 0 | pthread_mutex_unlock(&fd->command_m); |
3477 | 0 | } |
3478 | | |
3479 | | // Submit a NULL sp_bams entry to act as an EOF marker |
3480 | 0 | if (hts_tpool_dispatch(fd->p, fd->q, sam_parse_eof, NULL) < 0) |
3481 | 0 | goto err; |
3482 | | |
3483 | | // At EOF, wait for close request. |
3484 | | // (In future if we add support for seek, this is where we need to catch it.) |
3485 | 0 | for (;;) { |
3486 | 0 | pthread_mutex_lock(&fd->command_m); |
3487 | 0 | if (fd->command == SAM_NONE) |
3488 | 0 | pthread_cond_wait(&fd->command_c, &fd->command_m); |
3489 | 0 | switch (fd->command) { |
3490 | 0 | case SAM_CLOSE: |
3491 | 0 | pthread_cond_signal(&fd->command_c); |
3492 | 0 | pthread_mutex_unlock(&fd->command_m); |
3493 | 0 | hts_tpool_process_shutdown(fd->q); |
3494 | 0 | goto tidyup; |
3495 | | |
3496 | 0 | default: |
3497 | 0 | pthread_mutex_unlock(&fd->command_m); |
3498 | 0 | break; |
3499 | 0 | } |
3500 | 0 | } |
3501 | | |
3502 | 0 | tidyup: |
3503 | 0 | pthread_mutex_lock(&fd->command_m); |
3504 | 0 | fd->command = SAM_CLOSE_DONE; |
3505 | 0 | pthread_cond_signal(&fd->command_c); |
3506 | 0 | pthread_mutex_unlock(&fd->command_m); |
3507 | |
|
3508 | 0 | if (l) { |
3509 | 0 | pthread_mutex_lock(&fd->lines_m); |
3510 | 0 | l->next = fd->lines; |
3511 | 0 | fd->lines = l; |
3512 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3513 | 0 | } |
3514 | 0 | free(line.s); |
3515 | |
|
3516 | 0 | return NULL; |
3517 | | |
3518 | 0 | err: |
3519 | 0 | sam_state_err(fd, errno ? errno : ENOMEM); |
3520 | 0 | hts_tpool_process_shutdown(fd->q); |
3521 | 0 | goto tidyup; |
3522 | 0 | } |
3523 | | |
3524 | | // Runs in its own thread. |
3525 | | // Takes encoded blocks of SAM off the thread results queue and writes them |
3526 | | // to our output stream. |
3527 | 0 | static void *sam_dispatcher_write(void *vp) { |
3528 | 0 | htsFile *fp = vp; |
3529 | 0 | SAM_state *fd = fp->state; |
3530 | 0 | hts_tpool_result *r; |
3531 | | |
3532 | | // Iterates until result queue is shutdown, where it returns NULL. |
3533 | 0 | while ((r = hts_tpool_next_result_wait(fd->q))) { |
3534 | 0 | sp_lines *gl = (sp_lines *)hts_tpool_result_data(r); |
3535 | 0 | if (!gl) { |
3536 | 0 | sam_state_err(fd, ENOMEM); |
3537 | 0 | goto err; |
3538 | 0 | } |
3539 | | |
3540 | 0 | if (fp->idx) { |
3541 | 0 | sp_bams *gb = gl->bams; |
3542 | 0 | int i = 0, count = 0; |
3543 | 0 | while (i < gl->data_size) { |
3544 | 0 | int j = i; |
3545 | 0 | while (i < gl->data_size && gl->data[i] != '\n') |
3546 | 0 | i++; |
3547 | 0 | if (i < gl->data_size) |
3548 | 0 | i++; |
3549 | |
|
3550 | 0 | if (fp->is_bgzf) { |
3551 | 0 | if (bgzf_flush_try(fp->fp.bgzf, i-j) < 0) |
3552 | 0 | goto err; |
3553 | 0 | if (bgzf_write(fp->fp.bgzf, &gl->data[j], i-j) != i-j) |
3554 | 0 | goto err; |
3555 | 0 | } else { |
3556 | 0 | if (hwrite(fp->fp.hfile, &gl->data[j], i-j) != i-j) |
3557 | 0 | goto err; |
3558 | 0 | } |
3559 | | |
3560 | 0 | if (count >= gb->nbams) { |
3561 | 0 | hts_log_error("Attempted to write too many bam objects - " |
3562 | 0 | "malformed data?"); |
3563 | 0 | goto err; |
3564 | 0 | } |
3565 | 0 | bam1_t *b = &gb->bams[count++]; |
3566 | 0 | if (fp->format.compression == bgzf) { |
3567 | 0 | if (bgzf_idx_push(fp->fp.bgzf, fp->idx, |
3568 | 0 | b->core.tid, b->core.pos, bam_endpos(b), |
3569 | 0 | bgzf_tell(fp->fp.bgzf), |
3570 | 0 | !(b->core.flag&BAM_FUNMAP)) < 0) { |
3571 | 0 | sam_state_err(fd, errno ? errno : ENOMEM); |
3572 | 0 | hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed", |
3573 | 0 | bam_get_qname(b), sam_hdr_tid2name(fd->h, b->core.tid), sam_hdr_tid2len(fd->h, b->core.tid), b->core.flag, b->core.pos+1); |
3574 | 0 | goto err; |
3575 | 0 | } |
3576 | 0 | } else { |
3577 | 0 | if (hts_idx_push(fp->idx, b->core.tid, b->core.pos, bam_endpos(b), |
3578 | 0 | bgzf_tell(fp->fp.bgzf), !(b->core.flag&BAM_FUNMAP)) < 0) { |
3579 | 0 | sam_state_err(fd, errno ? errno : ENOMEM); |
3580 | 0 | hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed", |
3581 | 0 | bam_get_qname(b), sam_hdr_tid2name(fd->h, b->core.tid), sam_hdr_tid2len(fd->h, b->core.tid), b->core.flag, b->core.pos+1); |
3582 | 0 | goto err; |
3583 | 0 | } |
3584 | 0 | } |
3585 | 0 | } |
3586 | | |
3587 | 0 | assert(count == gb->nbams); |
3588 | | |
3589 | | // Add bam array to free-list |
3590 | 0 | pthread_mutex_lock(&fd->lines_m); |
3591 | 0 | gb->next = fd->bams; |
3592 | 0 | fd->bams = gl->bams; |
3593 | 0 | gl->bams = NULL; |
3594 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3595 | 0 | } else { |
3596 | 0 | if (fp->is_bgzf) { |
3597 | | // We keep track of how much in the current block we have |
3598 | | // remaining => R. We look for the last newline in input |
3599 | | // [i] to [i+R], backwards => position N. |
3600 | | // |
3601 | | // If we find a newline, we write out bytes i to N. |
3602 | | // We know we cannot fit the next record in this bgzf block, |
3603 | | // so we flush what we have and copy input N to i+R into |
3604 | | // the start of a new block, and recompute a new R for that. |
3605 | | // |
3606 | | // If we don't find a newline (i==N) then we cannot extend |
3607 | | // the current block at all, so flush whatever is in it now |
3608 | | // if it ends on a newline. |
3609 | | // We still copy i(==N) to i+R to the next block and |
3610 | | // continue as before with a new R. |
3611 | | // |
3612 | | // The only exception on the flush is when we run out of |
3613 | | // data in the input. In that case we skip it as we don't |
3614 | | // yet know if the next record will fit. |
3615 | | // |
3616 | | // Both conditions share the same code here: |
3617 | | // - Look for newline (pos N) |
3618 | | // - Write i to N (which maybe 0) |
3619 | | // - Flush if block ends on newline and not end of input |
3620 | | // - write N to i+R |
3621 | |
|
3622 | 0 | int i = 0; |
3623 | 0 | BGZF *fb = fp->fp.bgzf; |
3624 | 0 | while (i < gl->data_size) { |
3625 | | // remaining space in block |
3626 | 0 | int R = BGZF_BLOCK_SIZE - fb->block_offset; |
3627 | 0 | int eod = 0; |
3628 | 0 | if (R > gl->data_size-i) |
3629 | 0 | R = gl->data_size-i, eod = 1; |
3630 | | |
3631 | | // Find last newline in input data |
3632 | 0 | int N = i + R; |
3633 | 0 | while (--N > i) { |
3634 | 0 | if (gl->data[N] == '\n') |
3635 | 0 | break; |
3636 | 0 | } |
3637 | |
|
3638 | 0 | if (N != i) { |
3639 | | // Found a newline |
3640 | 0 | N++; |
3641 | 0 | if (bgzf_write(fb, &gl->data[i], N-i) != N-i) |
3642 | 0 | goto err; |
3643 | 0 | } |
3644 | | |
3645 | | // Flush bgzf block |
3646 | 0 | int b_off = fb->block_offset; |
3647 | 0 | if (!eod && b_off && |
3648 | 0 | ((char *)fb->uncompressed_block)[b_off-1] == '\n') |
3649 | 0 | if (bgzf_flush_try(fb, BGZF_BLOCK_SIZE) < 0) |
3650 | 0 | goto err; |
3651 | | |
3652 | | // Copy from N onwards into next block |
3653 | 0 | if (i+R > N) |
3654 | 0 | if (bgzf_write(fb, &gl->data[N], i+R - N) |
3655 | 0 | != i+R - N) |
3656 | 0 | goto err; |
3657 | | |
3658 | 0 | i = i+R; |
3659 | 0 | } |
3660 | 0 | } else { |
3661 | 0 | if (hwrite(fp->fp.hfile, gl->data, gl->data_size) != gl->data_size) |
3662 | 0 | goto err; |
3663 | 0 | } |
3664 | 0 | } |
3665 | | |
3666 | 0 | hts_tpool_delete_result(r, 0); |
3667 | | |
3668 | | // Also updated by main thread |
3669 | 0 | pthread_mutex_lock(&fd->lines_m); |
3670 | 0 | gl->next = fd->lines; |
3671 | 0 | fd->lines = gl; |
3672 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3673 | 0 | } |
3674 | | |
3675 | 0 | sam_state_err(fd, 0); // success |
3676 | 0 | hts_tpool_process_shutdown(fd->q); |
3677 | 0 | return NULL; |
3678 | | |
3679 | 0 | err: |
3680 | 0 | sam_state_err(fd, errno ? errno : EIO); |
3681 | 0 | return (void *)-1; |
3682 | 0 | } |
3683 | | |
3684 | | // Run from one of the worker threads. |
3685 | | // Convert a passed in array of BAMs (sp_bams) and converts to a block |
3686 | | // of text SAM records (sp_lines). |
3687 | 0 | static void *sam_format_worker(void *arg) { |
3688 | 0 | sp_bams *gb = (sp_bams *)arg; |
3689 | 0 | sp_lines *gl = NULL; |
3690 | 0 | int i; |
3691 | 0 | SAM_state *fd = gb->fd; |
3692 | 0 | htsFile *fp = fd->fp; |
3693 | | |
3694 | | // Use a block of SAM strings we had earlier if available. |
3695 | 0 | pthread_mutex_lock(&fd->lines_m); |
3696 | 0 | if (fd->lines) { |
3697 | 0 | gl = fd->lines; |
3698 | 0 | fd->lines = gl->next; |
3699 | 0 | } |
3700 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3701 | |
|
3702 | 0 | if (gl == NULL) { |
3703 | 0 | gl = calloc(1, sizeof(*gl)); |
3704 | 0 | if (!gl) { |
3705 | 0 | sam_state_err(fd, ENOMEM); |
3706 | 0 | return NULL; |
3707 | 0 | } |
3708 | 0 | gl->alloc = gl->data_size = 0; |
3709 | 0 | gl->data = NULL; |
3710 | 0 | } |
3711 | 0 | gl->serial = gb->serial; |
3712 | 0 | gl->next = NULL; |
3713 | |
|
3714 | 0 | kstring_t ks = {0, gl->alloc, gl->data}; |
3715 | |
|
3716 | 0 | int nomem = 0; |
3717 | 0 | for (i = 0; !nomem && i < gb->nbams; i++) { |
3718 | 0 | nomem |= sam_format1_append(fd->h, &gb->bams[i], &ks) < 0; |
3719 | 0 | nomem |= kputc('\n', &ks) < 0; |
3720 | 0 | } |
3721 | 0 | gl->data_size = ks.l; |
3722 | 0 | gl->alloc = ks.m; |
3723 | 0 | gl->data = ks.s; |
3724 | 0 | if (nomem) { |
3725 | 0 | sam_state_err(fd, errno ? errno : EIO); |
3726 | 0 | goto err; |
3727 | 0 | } |
3728 | | |
3729 | 0 | pthread_mutex_lock(&fd->lines_m); |
3730 | 0 | if (fp->idx) { |
3731 | | // Keep hold of the bam array a little longer as |
3732 | | // sam_dispatcher_write needs to use them for building the index. |
3733 | 0 | gl->bams = gb; |
3734 | 0 | } else { |
3735 | | // Add bam array to free-list |
3736 | 0 | gb->next = fd->bams; |
3737 | 0 | fd->bams = gb; |
3738 | 0 | } |
3739 | 0 | pthread_mutex_unlock(&fd->lines_m); |
3740 | |
|
3741 | 0 | return gl; |
3742 | | |
3743 | 0 | err: |
3744 | | // Possible race between this and fd->curr_bam. |
3745 | | // Easier to not free and leave it on the input list so it |
3746 | | // gets freed there instead? |
3747 | | // sam_free_sp_bams(gb); |
3748 | 0 | if (gl) { |
3749 | 0 | free(gl->data); |
3750 | 0 | free(gl); |
3751 | 0 | } |
3752 | 0 | return NULL; |
3753 | 0 | } |
3754 | | |
3755 | 0 | int sam_set_thread_pool(htsFile *fp, htsThreadPool *p) { |
3756 | 0 | if (fp->state) |
3757 | 0 | return -2; //already exists! |
3758 | | |
3759 | 0 | if (!(fp->state = sam_state_create(fp))) |
3760 | 0 | return -1; |
3761 | 0 | SAM_state *fd = (SAM_state *)fp->state; |
3762 | |
|
3763 | 0 | pthread_mutex_init(&fd->lines_m, NULL); |
3764 | 0 | pthread_mutex_init(&fd->command_m, NULL); |
3765 | 0 | pthread_cond_init(&fd->command_c, NULL); |
3766 | 0 | fd->p = p->pool; |
3767 | 0 | int qsize = p->qsize; |
3768 | 0 | if (!qsize) |
3769 | 0 | qsize = 2*hts_tpool_size(fd->p); |
3770 | 0 | fd->q = hts_tpool_process_init(fd->p, qsize, 0); |
3771 | 0 | if (!fd->q) { |
3772 | 0 | sam_state_destroy(fp); |
3773 | 0 | return -1; |
3774 | 0 | } |
3775 | | |
3776 | 0 | if (fp->format.compression == bgzf) |
3777 | 0 | return bgzf_thread_pool(fp->fp.bgzf, p->pool, p->qsize); |
3778 | | |
3779 | 0 | return 0; |
3780 | 0 | } |
3781 | | |
3782 | 0 | int sam_set_threads(htsFile *fp, int nthreads) { |
3783 | 0 | if (nthreads <= 0) |
3784 | 0 | return 0; |
3785 | | |
3786 | 0 | htsThreadPool p; |
3787 | 0 | p.pool = hts_tpool_init(nthreads); |
3788 | 0 | p.qsize = nthreads*2; |
3789 | |
|
3790 | 0 | int ret = sam_set_thread_pool(fp, &p); |
3791 | 0 | if (ret < 0) { |
3792 | 0 | if (p.pool) |
3793 | 0 | hts_tpool_destroy(p.pool); |
3794 | 0 | return ret; |
3795 | 0 | } |
3796 | | |
3797 | 0 | SAM_state *fd = (SAM_state *)fp->state; |
3798 | 0 | fd->own_pool = 1; |
3799 | |
|
3800 | 0 | return 0; |
3801 | 0 | } |
3802 | | |
3803 | 0 | #define UMI_TAGS 5 |
3804 | | typedef struct { |
3805 | | kstring_t name; |
3806 | | kstring_t comment; // NB: pointer into name, do not free |
3807 | | kstring_t seq; |
3808 | | kstring_t qual; |
3809 | | int casava; |
3810 | | int aux; |
3811 | | int rnum; |
3812 | | char BC[3]; // aux tag ID for barcode |
3813 | | char UMI[UMI_TAGS][3]; // aux tag list for UMIs. |
3814 | | khash_t(tag) *tags; // which aux tags to use (if empty, use all). |
3815 | | char nprefix; |
3816 | | int sra_names; |
3817 | | regex_t regex; |
3818 | | } fastq_state; |
3819 | | |
3820 | | // Initialise fastq state. |
3821 | | // Name char of '@' or '>' distinguishes fastq vs fasta variant |
3822 | 5.42k | static fastq_state *fastq_state_init(int name_char) { |
3823 | 5.42k | fastq_state *x = (fastq_state *)calloc(1, sizeof(*x)); |
3824 | 5.42k | if (!x) |
3825 | 0 | return NULL; |
3826 | 5.42k | strcpy(x->BC, "BC"); |
3827 | 5.42k | x->nprefix = name_char; |
3828 | | // Default Illumina naming convention |
3829 | 5.42k | char *re = "^[^:]+:[^:]+:[^:]+:[^:]+:[^:]+:[^:]+:[^:]+:([^:#/]+)"; |
3830 | 5.42k | if (regcomp(&x->regex, re, REG_EXTENDED) != 0) { |
3831 | 0 | free(x); |
3832 | 0 | return NULL; |
3833 | 0 | } |
3834 | | |
3835 | 5.42k | return x; |
3836 | 5.42k | } |
3837 | | |
3838 | 7.23k | void fastq_state_destroy(htsFile *fp) { |
3839 | 7.23k | if (fp->state) { |
3840 | 5.42k | fastq_state *x = (fastq_state *)fp->state; |
3841 | 5.42k | if (x->tags) |
3842 | 0 | kh_destroy(tag, x->tags); |
3843 | 5.42k | ks_free(&x->name); |
3844 | 5.42k | ks_free(&x->seq); |
3845 | 5.42k | ks_free(&x->qual); |
3846 | 5.42k | regfree(&x->regex); |
3847 | 5.42k | free(fp->state); |
3848 | 5.42k | } |
3849 | 7.23k | } |
3850 | | |
3851 | 0 | int fastq_state_set(samFile *fp, enum hts_fmt_option opt, ...) { |
3852 | 0 | va_list args; |
3853 | |
|
3854 | 0 | if (!fp) |
3855 | 0 | return -1; |
3856 | 0 | if (!fp->state) |
3857 | 0 | if (!(fp->state = fastq_state_init(fp->format.format == fastq_format |
3858 | 0 | ? '@' : '>'))) |
3859 | 0 | return -1; |
3860 | | |
3861 | 0 | fastq_state *x = (fastq_state *)fp->state; |
3862 | |
|
3863 | 0 | switch (opt) { |
3864 | 0 | case FASTQ_OPT_CASAVA: |
3865 | 0 | x->casava = 1; |
3866 | 0 | break; |
3867 | | |
3868 | 0 | case FASTQ_OPT_NAME2: |
3869 | 0 | x->sra_names = 1; |
3870 | 0 | break; |
3871 | | |
3872 | 0 | case FASTQ_OPT_AUX: { |
3873 | 0 | va_start(args, opt); |
3874 | 0 | x->aux = 1; |
3875 | 0 | char *tag = va_arg(args, char *); |
3876 | 0 | va_end(args); |
3877 | 0 | if (tag && strcmp(tag, "1") != 0) { |
3878 | 0 | if (!x->tags) |
3879 | 0 | if (!(x->tags = kh_init(tag))) |
3880 | 0 | return -1; |
3881 | | |
3882 | 0 | size_t i, tlen = strlen(tag); |
3883 | 0 | for (i = 0; i+3 <= tlen+1; i += 3) { |
3884 | 0 | if (tag[i+0] == ',' || tag[i+1] == ',' || |
3885 | 0 | !(tag[i+2] == ',' || tag[i+2] == '\0')) { |
3886 | 0 | hts_log_warning("Bad tag format '%.3s'; skipping option", tag+i); |
3887 | 0 | break; |
3888 | 0 | } |
3889 | 0 | int ret, tcode = tag[i+0]*256 + tag[i+1]; |
3890 | 0 | kh_put(tag, x->tags, tcode, &ret); |
3891 | 0 | if (ret < 0) |
3892 | 0 | return -1; |
3893 | 0 | } |
3894 | 0 | } |
3895 | 0 | break; |
3896 | 0 | } |
3897 | | |
3898 | 0 | case FASTQ_OPT_BARCODE: { |
3899 | 0 | va_start(args, opt); |
3900 | 0 | char *bc = va_arg(args, char *); |
3901 | 0 | va_end(args); |
3902 | 0 | strncpy(x->BC, bc, 2); |
3903 | 0 | x->BC[2] = 0; |
3904 | 0 | break; |
3905 | 0 | } |
3906 | | |
3907 | 0 | case FASTQ_OPT_UMI: { |
3908 | | // UMI tag: an empty string disables UMI by setting x->UMI[0] to \0\0\0 |
3909 | 0 | va_start(args, opt); |
3910 | 0 | char *bc = va_arg(args, char *), *bc_orig = bc; |
3911 | 0 | va_end(args); |
3912 | 0 | if (!bc || strcmp(bc, "1") == 0) |
3913 | 0 | bc = "RX"; |
3914 | 0 | int ntags = 0, err = 0; |
3915 | 0 | for (ntags = 0; *bc && ntags < UMI_TAGS; ntags++) { |
3916 | 0 | if (!isalpha_c(bc[0]) || !isalnum_c(bc[1])) { |
3917 | 0 | err = 1; |
3918 | 0 | break; |
3919 | 0 | } |
3920 | | |
3921 | 0 | strncpy(x->UMI[ntags], bc, 3); |
3922 | 0 | bc += 2; |
3923 | 0 | if (*bc && *bc != ',') { |
3924 | 0 | err = 1; |
3925 | 0 | break; |
3926 | 0 | } |
3927 | 0 | bc+=(*bc==','); |
3928 | 0 | x->UMI[ntags][2] = 0; |
3929 | 0 | } |
3930 | 0 | for (; ntags < UMI_TAGS; ntags++) |
3931 | 0 | x->UMI[ntags][0] = x->UMI[ntags][1] = x->UMI[ntags][2] = 0; |
3932 | | |
3933 | |
|
3934 | 0 | if (err) |
3935 | 0 | hts_log_warning("Bad UMI tag list '%s'", bc_orig); |
3936 | |
|
3937 | 0 | break; |
3938 | 0 | } |
3939 | | |
3940 | 0 | case FASTQ_OPT_UMI_REGEX: { |
3941 | 0 | va_start(args, opt); |
3942 | 0 | char *re = va_arg(args, char *); |
3943 | 0 | va_end(args); |
3944 | |
|
3945 | 0 | regfree(&x->regex); |
3946 | 0 | if (regcomp(&x->regex, re, REG_EXTENDED) != 0) { |
3947 | 0 | hts_log_error("Regular expression '%s' is not supported", re); |
3948 | 0 | return -1; |
3949 | 0 | } |
3950 | 0 | break; |
3951 | 0 | } |
3952 | | |
3953 | 0 | case FASTQ_OPT_RNUM: |
3954 | 0 | x->rnum = 1; |
3955 | 0 | break; |
3956 | | |
3957 | 0 | default: |
3958 | 0 | break; |
3959 | 0 | } |
3960 | 0 | return 0; |
3961 | 0 | } |
3962 | | |
3963 | 44.5M | static int fastq_parse1(htsFile *fp, bam1_t *b) { |
3964 | 44.5M | fastq_state *x = (fastq_state *)fp->state; |
3965 | 44.5M | size_t i, l, aux_start = 0; |
3966 | 44.5M | int ret = 0; |
3967 | | |
3968 | 44.5M | if (fp->format.format == fasta_format && fp->line.s) { |
3969 | | // For FASTA we've already read the >name line; steal it |
3970 | | // Not the most efficient, but we don't optimise for fasta reading. |
3971 | 44.5M | if (fp->line.l == 0) |
3972 | 3.67k | return -1; // EOF |
3973 | | |
3974 | 44.5M | free(x->name.s); |
3975 | 44.5M | x->name = fp->line; |
3976 | 44.5M | fp->line.l = fp->line.m = 0; |
3977 | 44.5M | fp->line.s = NULL; |
3978 | 44.5M | } else { |
3979 | | // Read a FASTQ format entry. |
3980 | 7.44k | ret = hts_getline(fp, KS_SEP_LINE, &x->name); |
3981 | 7.44k | if (ret == -1) |
3982 | 60 | return -1; // EOF |
3983 | 7.38k | else if (ret < -1) |
3984 | 159 | return ret; // ERR |
3985 | 7.44k | } |
3986 | | |
3987 | | // Name |
3988 | 44.5M | if (*x->name.s != x->nprefix) |
3989 | 75 | return -2; |
3990 | | |
3991 | | // Reverse the SRA strangeness of putting the run_name.number before |
3992 | | // the read name. |
3993 | 44.5M | i = 0; |
3994 | 44.5M | char *name = x->name.s+1; |
3995 | 44.5M | if (x->sra_names) { |
3996 | 0 | char *cp = strpbrk(x->name.s, " \t"); |
3997 | 0 | if (cp) { |
3998 | 0 | while (*cp == ' ' || *cp == '\t') |
3999 | 0 | cp++; |
4000 | 0 | *--cp = '@'; |
4001 | 0 | i = cp - x->name.s; |
4002 | 0 | name = cp+1; |
4003 | 0 | } |
4004 | 0 | } |
4005 | | |
4006 | 44.5M | l = x->name.l; |
4007 | 44.5M | char *s = x->name.s; |
4008 | 136M | while (i < l && !isspace_c(s[i])) |
4009 | 91.7M | i++; |
4010 | 44.5M | if (i < l) { |
4011 | 328k | s[i] = 0; |
4012 | 328k | x->name.l = i++; |
4013 | 328k | } |
4014 | | |
4015 | | // Comment; a kstring struct, but pointer into name line. (Do not free) |
4016 | 46.2M | while (i < l && isspace_c(s[i])) |
4017 | 1.69M | i++; |
4018 | 44.5M | x->comment.s = s+i; |
4019 | 44.5M | x->comment.l = l - i; |
4020 | | |
4021 | | // Seq |
4022 | 44.5M | x->seq.l = 0; |
4023 | 125M | for (;;) { |
4024 | 125M | if ((ret = hts_getline(fp, KS_SEP_LINE, &fp->line)) < 0) |
4025 | 4.92k | if (fp->format.format == fastq_format || ret < -1) |
4026 | 1.22k | return -2; |
4027 | 125M | if (ret == -1 || |
4028 | 125M | *fp->line.s == (fp->format.format == fastq_format ? '+' : '>')) |
4029 | 44.5M | break; |
4030 | 81.1M | if (kputsn(fp->line.s, fp->line.l, &x->seq) < 0) |
4031 | 0 | return -2; |
4032 | 81.1M | } |
4033 | | |
4034 | | // Qual |
4035 | 44.5M | if (fp->format.format == fastq_format) { |
4036 | 2.07k | size_t remainder = x->seq.l; |
4037 | 2.07k | x->qual.l = 0; |
4038 | 102k | do { |
4039 | 102k | if (hts_getline(fp, KS_SEP_LINE, &fp->line) < 0) |
4040 | 33 | return -2; |
4041 | 102k | if (fp->line.l > remainder) |
4042 | 45 | return -2; |
4043 | 102k | if (kputsn(fp->line.s, fp->line.l, &x->qual) < 0) |
4044 | 0 | return -2; |
4045 | 102k | remainder -= fp->line.l; |
4046 | 102k | } while (remainder > 0); |
4047 | | |
4048 | | // Decr qual |
4049 | 722k | for (i = 0; i < x->qual.l; i++) |
4050 | 720k | x->qual.s[i] -= '!'; |
4051 | 1.99k | } |
4052 | | |
4053 | 44.5M | int flag = BAM_FUNMAP; int pflag = BAM_FMUNMAP | BAM_FPAIRED; |
4054 | 44.5M | if (x->name.l > 2 && |
4055 | 8.42M | x->name.s[x->name.l-2] == '/' && |
4056 | 849k | isdigit_c(x->name.s[x->name.l-1])) { |
4057 | 832k | switch(x->name.s[x->name.l-1]) { |
4058 | 57.4k | case '1': flag |= BAM_FREAD1 | pflag; break; |
4059 | 594k | case '2': flag |= BAM_FREAD2 | pflag; break; |
4060 | 180k | default : flag |= BAM_FREAD1 | BAM_FREAD2 | pflag; break; |
4061 | 832k | } |
4062 | 832k | x->name.s[x->name.l-=2] = 0; |
4063 | 832k | } |
4064 | | |
4065 | | // Strip Illumina formatted UMI off read-name |
4066 | 44.5M | char UMI_seq[256]; // maximum length in spec |
4067 | 44.5M | size_t UMI_len = 0; |
4068 | 44.5M | if (x->UMI[0][0]) { |
4069 | 0 | regmatch_t match[3]; |
4070 | 0 | if (regexec(&x->regex, x->name.s, 2, match, 0) == 0 |
4071 | 0 | && match[0].rm_so >= 0 // whole regex |
4072 | 0 | && match[1].rm_so >= 0) { // bracketted UMI component |
4073 | 0 | UMI_len = match[1].rm_eo - match[1].rm_so; |
4074 | 0 | if (UMI_len > 255) { |
4075 | 0 | hts_log_error("SAM read name is too long"); |
4076 | 0 | return -2; |
4077 | 0 | } |
4078 | | |
4079 | | // The SAMTags spec recommends (but not requires) separating |
4080 | | // barcodes with hyphen ('-'). |
4081 | 0 | size_t i; |
4082 | 0 | for (i = 0; i < UMI_len; i++) |
4083 | 0 | UMI_seq[i] = isalpha_c(x->name.s[i+match[1].rm_so]) |
4084 | 0 | ? x->name.s[i+match[1].rm_so] |
4085 | 0 | : '-'; |
4086 | | |
4087 | | // Move any trailing #num earlier in the name |
4088 | 0 | if (UMI_len) { |
4089 | 0 | UMI_seq[UMI_len++] = 0; |
4090 | |
|
4091 | 0 | x->name.l = match[1].rm_so; |
4092 | 0 | if (x->name.l > 0 && x->name.s[x->name.l-1] == ':') |
4093 | 0 | x->name.l--; // remove colon too |
4094 | 0 | char *cp = x->name.s + match[1].rm_eo; |
4095 | 0 | while (*cp) |
4096 | 0 | x->name.s[x->name.l++] = *cp++; |
4097 | 0 | x->name.s[x->name.l] = 0; |
4098 | 0 | } |
4099 | 0 | } |
4100 | 0 | } |
4101 | | |
4102 | | // Convert to BAM |
4103 | 44.5M | ret = bam_set1(b, |
4104 | 44.5M | x->name.s + x->name.l - name, name, |
4105 | 44.5M | flag, |
4106 | 44.5M | -1, -1, 0, // ref '*', pos, mapq, |
4107 | 44.5M | 0, NULL, // no cigar, |
4108 | 44.5M | -1, -1, 0, // mate |
4109 | 44.5M | x->seq.l, x->seq.s, x->qual.s, |
4110 | 44.5M | 0); |
4111 | 44.5M | if (ret < 0) return -2; |
4112 | | |
4113 | | // Add UMI tag if removed from read-name above |
4114 | 44.5M | if (UMI_len) { |
4115 | 0 | if (bam_aux_append(b, x->UMI[0], 'Z', UMI_len, (uint8_t *)UMI_seq) < 0) |
4116 | 0 | ret = -2; |
4117 | 0 | } |
4118 | | |
4119 | | // Identify Illumina CASAVA strings. |
4120 | | // <read>:<is_filtered>:<control_bits>:<barcode_sequence> |
4121 | 44.5M | char *barcode = NULL; |
4122 | 44.5M | int barcode_len = 0; |
4123 | 44.5M | kstring_t *kc = &x->comment; |
4124 | 44.5M | char *endptr; |
4125 | 44.5M | if (x->casava && |
4126 | | // \d:[YN]:\d+:[ACGTN]+ |
4127 | 0 | kc->l > 6 && (kc->s[1] | kc->s[3]) == ':' && isdigit_c(kc->s[0]) && |
4128 | 0 | strtol(kc->s+4, &endptr, 10) >= 0 && endptr != kc->s+4 |
4129 | 0 | && *endptr == ':') { |
4130 | | |
4131 | | // read num |
4132 | 0 | switch(kc->s[0]) { |
4133 | 0 | case '1': b->core.flag |= BAM_FREAD1 | pflag; break; |
4134 | 0 | case '2': b->core.flag |= BAM_FREAD2 | pflag; break; |
4135 | 0 | default : b->core.flag |= BAM_FREAD1 | BAM_FREAD2 | pflag; break; |
4136 | 0 | } |
4137 | | |
4138 | 0 | if (kc->s[2] == 'Y') |
4139 | 0 | b->core.flag |= BAM_FQCFAIL; |
4140 | | |
4141 | | // Barcode, maybe numeric in which case we skip it |
4142 | 0 | if (!isdigit_c(endptr[1])) { |
4143 | 0 | barcode = endptr+1; |
4144 | 0 | for (i = barcode - kc->s; i < kc->l; i++) |
4145 | 0 | if (isspace_c(kc->s[i])) |
4146 | 0 | break; |
4147 | |
|
4148 | 0 | kc->s[i++] = 0; |
4149 | 0 | barcode_len = i - (barcode - kc->s); |
4150 | 0 | aux_start = i < kc->l ? i : kc->l; |
4151 | 0 | } |
4152 | 0 | } |
4153 | | |
4154 | 44.5M | if (ret >= 0 && barcode_len) |
4155 | 0 | if (bam_aux_append(b, x->BC, 'Z', barcode_len, (uint8_t *)barcode) < 0) |
4156 | 0 | ret = -2; |
4157 | | |
4158 | 44.5M | if (!x->aux) |
4159 | 44.5M | return ret; |
4160 | | |
4161 | | // Identify any SAM style aux tags in comments too. |
4162 | 0 | if (aux_parse(kc->s + aux_start, kc->s + kc->l, b, 1, x->tags) < 0) |
4163 | 0 | ret = -2; |
4164 | |
|
4165 | 0 | return ret; |
4166 | 44.5M | } |
4167 | | |
4168 | | // Internal component of sam_read1 below |
4169 | 7.39k | static inline int sam_read1_bam(htsFile *fp, sam_hdr_t *h, bam1_t *b) { |
4170 | 7.39k | int ret = bam_read1(fp->fp.bgzf, b); |
4171 | 7.39k | if (h && ret >= 0) { |
4172 | 5.17k | if (b->core.tid >= h->n_targets || b->core.tid < -1 || |
4173 | 5.02k | b->core.mtid >= h->n_targets || b->core.mtid < -1) { |
4174 | 245 | errno = ERANGE; |
4175 | 245 | return -3; |
4176 | 245 | } |
4177 | 5.17k | } |
4178 | 7.14k | return ret; |
4179 | 7.39k | } |
4180 | | |
4181 | | // Internal component of sam_read1 below |
4182 | 7.44k | static inline int sam_read1_cram(htsFile *fp, sam_hdr_t *h, bam1_t **b) { |
4183 | 7.44k | int ret = cram_get_bam_seq(fp->fp.cram, b); |
4184 | 7.44k | if (ret < 0) |
4185 | 7.44k | return cram_eof(fp->fp.cram) ? -1 : -2; |
4186 | | |
4187 | 0 | return ret; |
4188 | 7.44k | } |
4189 | | |
4190 | | // Internal component of sam_read1 below |
4191 | 417k | static inline int sam_read1_sam(htsFile *fp, sam_hdr_t *h, bam1_t *b) { |
4192 | 417k | int ret; |
4193 | | |
4194 | | // Consume 1st line after header parsing as it wasn't using peek |
4195 | 417k | if (fp->line.l != 0) { |
4196 | 51 | ret = sam_parse1(&fp->line, h, b); |
4197 | 51 | fp->line.l = 0; |
4198 | 51 | return ret; |
4199 | 51 | } |
4200 | | |
4201 | 417k | if (fp->state) { |
4202 | 0 | SAM_state *fd = (SAM_state *)fp->state; |
4203 | |
|
4204 | 0 | if (fp->format.compression == bgzf && fp->fp.bgzf->seeked) { |
4205 | | // We don't support multi-threaded SAM parsing with seeks yet. |
4206 | 0 | int ret; |
4207 | 0 | if ((ret = sam_state_destroy(fp)) < 0) { |
4208 | 0 | errno = -ret; |
4209 | 0 | return -2; |
4210 | 0 | } |
4211 | 0 | if (bgzf_seek(fp->fp.bgzf, fp->fp.bgzf->seeked, SEEK_SET) < 0) |
4212 | 0 | return -2; |
4213 | 0 | fp->fp.bgzf->seeked = 0; |
4214 | 0 | goto err_recover; |
4215 | 0 | } |
4216 | | |
4217 | 0 | if (!fd->h) { |
4218 | 0 | fd->h = h; |
4219 | 0 | fd->h->ref_count++; |
4220 | | // Ensure hrecs is initialised now as we don't want multiple |
4221 | | // threads trying to do this simultaneously. |
4222 | 0 | if (!fd->h->hrecs && sam_hdr_fill_hrecs(fd->h) < 0) |
4223 | 0 | return -2; |
4224 | | |
4225 | | // We can only do this once we've got a header |
4226 | 0 | if (pthread_create(&fd->dispatcher, NULL, sam_dispatcher_read, |
4227 | 0 | fp) != 0) |
4228 | 0 | return -2; |
4229 | 0 | fd->dispatcher_set = 1; |
4230 | 0 | } |
4231 | | |
4232 | 0 | if (fd->h != h) { |
4233 | 0 | hts_log_error("SAM multi-threaded decoding does not support changing header"); |
4234 | 0 | return -2; |
4235 | 0 | } |
4236 | | |
4237 | 0 | sp_bams *gb = fd->curr_bam; |
4238 | 0 | if (!gb) { |
4239 | 0 | if (fd->errcode) { |
4240 | | // In case reader failed |
4241 | 0 | errno = fd->errcode; |
4242 | 0 | return -2; |
4243 | 0 | } |
4244 | | |
4245 | 0 | pthread_mutex_lock(&fd->command_m); |
4246 | 0 | int cmd = fd->command; |
4247 | 0 | pthread_mutex_unlock(&fd->command_m); |
4248 | 0 | if (cmd == SAM_AT_EOF) |
4249 | 0 | return -1; |
4250 | | |
4251 | 0 | hts_tpool_result *r = hts_tpool_next_result_wait(fd->q); |
4252 | 0 | if (!r) |
4253 | 0 | return -2; |
4254 | 0 | fd->curr_bam = gb = (sp_bams *)hts_tpool_result_data(r); |
4255 | 0 | hts_tpool_delete_result(r, 0); |
4256 | 0 | } |
4257 | 0 | if (!gb) { |
4258 | 0 | pthread_mutex_lock(&fd->command_m); |
4259 | 0 | fd->command = SAM_AT_EOF; |
4260 | 0 | pthread_mutex_unlock(&fd->command_m); |
4261 | 0 | return fd->errcode ? -2 : -1; |
4262 | 0 | } |
4263 | 0 | bam1_t *b_array = (bam1_t *)gb->bams; |
4264 | 0 | if (fd->curr_idx < gb->nbams) |
4265 | 0 | if (!bam_copy1(b, &b_array[fd->curr_idx++])) |
4266 | 0 | return -2; |
4267 | 0 | if (fd->curr_idx == gb->nbams) { |
4268 | 0 | pthread_mutex_lock(&fd->lines_m); |
4269 | 0 | gb->next = fd->bams; |
4270 | 0 | fd->bams = gb; |
4271 | 0 | pthread_mutex_unlock(&fd->lines_m); |
4272 | |
|
4273 | 0 | fd->curr_bam = NULL; |
4274 | 0 | fd->curr_idx = 0; |
4275 | | // Consider prefetching next record? I.e. |
4276 | | // } else { |
4277 | | // __builtin_prefetch(&b_array[fd->curr_idx], 0, 3); |
4278 | 0 | } |
4279 | |
|
4280 | 0 | ret = 0; |
4281 | |
|
4282 | 417k | } else { |
4283 | 417k | err_recover: |
4284 | 417k | ret = hts_getline(fp, KS_SEP_LINE, &fp->line); |
4285 | 417k | if (ret < 0) return ret; |
4286 | | |
4287 | 410k | ret = sam_parse1(&fp->line, h, b); |
4288 | 410k | fp->line.l = 0; |
4289 | 410k | if (ret < 0) { |
4290 | 7.68k | hts_log_warning("Parse error at line %lld", (long long)fp->lineno); |
4291 | 7.68k | if (h && h->ignore_sam_err) goto err_recover; |
4292 | 7.68k | } |
4293 | 410k | } |
4294 | | |
4295 | 410k | return ret; |
4296 | 417k | } |
4297 | | |
4298 | | // Returns 0 on success, |
4299 | | // -1 on EOF, |
4300 | | // <-1 on error |
4301 | | int sam_read1(htsFile *fp, sam_hdr_t *h, bam1_t *b) |
4302 | 45.0M | { |
4303 | 45.0M | int ret, pass_filter; |
4304 | | |
4305 | 45.0M | do { |
4306 | 45.0M | switch (fp->format.format) { |
4307 | 7.39k | case bam: |
4308 | 7.39k | ret = sam_read1_bam(fp, h, b); |
4309 | 7.39k | break; |
4310 | | |
4311 | 7.44k | case cram: |
4312 | 7.44k | ret = sam_read1_cram(fp, h, &b); |
4313 | 7.44k | break; |
4314 | | |
4315 | 417k | case sam: |
4316 | 417k | ret = sam_read1_sam(fp, h, b); |
4317 | 417k | break; |
4318 | | |
4319 | 44.5M | case fasta_format: |
4320 | 44.5M | case fastq_format: { |
4321 | 44.5M | fastq_state *x = (fastq_state *)fp->state; |
4322 | 44.5M | if (!x) { |
4323 | 5.42k | if (!(fp->state = fastq_state_init(fp->format.format |
4324 | 5.42k | == fastq_format ? '@' : '>'))) |
4325 | 0 | return -2; |
4326 | 5.42k | } |
4327 | | |
4328 | 44.5M | return fastq_parse1(fp, b); |
4329 | 44.5M | } |
4330 | | |
4331 | 0 | case empty_format: |
4332 | 0 | errno = EPIPE; |
4333 | 0 | return -3; |
4334 | | |
4335 | 0 | default: |
4336 | 0 | errno = EFTYPE; |
4337 | 0 | return -3; |
4338 | 45.0M | } |
4339 | | |
4340 | 432k | pass_filter = (ret >= 0 && fp->filter) |
4341 | 432k | ? sam_passes_filter(h, b, fp->filter) |
4342 | 432k | : 1; |
4343 | 432k | } while (pass_filter == 0); |
4344 | | |
4345 | 432k | return pass_filter < 0 ? -2 : ret; |
4346 | 45.0M | } |
4347 | | |
4348 | | // With gcc, -O3 or -ftree-loop-vectorize is really key here as otherwise |
4349 | | // this code isn't vectorised and runs far slower than is necessary (even |
4350 | | // with the restrict keyword being used). |
4351 | | static inline void HTS_OPT3 |
4352 | 1.19k | add33(uint8_t *a, const uint8_t * b, int32_t len) { |
4353 | 1.19k | uint32_t i; |
4354 | 246k | for (i = 0; i < len; i++) |
4355 | 245k | a[i] = b[i]+33; |
4356 | 1.19k | } |
4357 | | |
4358 | | static int sam_format1_append(const bam_hdr_t *h, const bam1_t *b, kstring_t *str) |
4359 | 14.8M | { |
4360 | 14.8M | int i, r = 0; |
4361 | 14.8M | uint8_t *s, *end; |
4362 | 14.8M | const bam1_core_t *c = &b->core; |
4363 | | |
4364 | 14.8M | if (c->l_qname == 0) |
4365 | 0 | return -1; |
4366 | 14.8M | kputsn_chk_(&r, bam_get_qname(b), c->l_qname-1-c->l_extranul, str); |
4367 | 14.8M | kputc_chk_(&r, '\t', str); // query name |
4368 | 14.8M | kputw_chk(&r, c->flag, str); kputc_chk_(&r, '\t', str); // flag |
4369 | 14.8M | if (c->tid >= 0) { // chr |
4370 | 17.2k | kputs_chk(&r, h->target_name[c->tid] , str); |
4371 | 17.2k | kputc_chk_(&r, '\t', str); |
4372 | 14.8M | } else kputsn_chk_(&r, "*\t", 2, str); |
4373 | 14.8M | kputll_chk(&r, c->pos + 1, str); kputc_chk_(&r, '\t', str); // pos |
4374 | 14.8M | kputw_chk(&r, c->qual, str); kputc_chk_(&r, '\t', str); // qual |
4375 | 14.8M | if (c->n_cigar) { // cigar |
4376 | 18.8k | uint32_t *cigar = bam_get_cigar(b); |
4377 | 5.19M | for (i = 0; i < c->n_cigar; ++i) { |
4378 | 5.17M | kputw_chk(&r, bam_cigar_oplen(cigar[i]), str); |
4379 | 5.17M | kputc_chk_(&r, bam_cigar_opchr(cigar[i]), str); |
4380 | 5.17M | } |
4381 | 14.8M | } else kputc_chk_(&r, '*', str); |
4382 | 14.8M | kputc_chk_(&r, '\t', str); |
4383 | 14.8M | if (c->mtid < 0) kputsn_chk_(&r, "*\t", 2, str); // mate chr |
4384 | 6.30k | else if (c->mtid == c->tid) kputsn_chk_(&r, "=\t", 2, str); |
4385 | 3.85k | else { |
4386 | 3.85k | kputs_chk(&r, h->target_name[c->mtid], str); |
4387 | 3.85k | kputc_chk_(&r, '\t', str); |
4388 | 3.85k | } |
4389 | 14.8M | kputll_chk(&r, c->mpos + 1, str); kputc_chk_(&r, '\t', str); // mate pos |
4390 | 14.8M | kputll_chk(&r, c->isize, str); kputc_chk_(&r, '\t', str); // template len |
4391 | 14.8M | if (c->l_qseq) { // seq and qual |
4392 | 524k | uint8_t *s = bam_get_seq(b); |
4393 | 524k | if (ks_resize(str, str->l+2+2*c->l_qseq) < 0) goto mem_err; |
4394 | 524k | char *cp = str->s + str->l; |
4395 | | |
4396 | | // Sequence, 2 bases at a time |
4397 | 524k | nibble2base(s, cp, c->l_qseq); |
4398 | 524k | cp[c->l_qseq] = '\t'; |
4399 | 524k | cp += c->l_qseq+1; |
4400 | | |
4401 | | // Quality |
4402 | 524k | s = bam_get_qual(b); |
4403 | 524k | i = 0; |
4404 | 524k | if (s[0] == 0xff) { |
4405 | 523k | cp[i++] = '*'; |
4406 | 523k | } else { |
4407 | 1.19k | add33((uint8_t *)cp, s, c->l_qseq); // cp[i] = s[i]+33; |
4408 | 1.19k | i = c->l_qseq; |
4409 | 1.19k | } |
4410 | 524k | cp[i] = 0; |
4411 | 524k | cp += i; |
4412 | 524k | str->l = cp - str->s; |
4413 | 14.3M | } else kputsn_chk_(&r, "*\t*", 3, str); |
4414 | | |
4415 | 14.8M | s = bam_get_aux(b); // aux |
4416 | 14.8M | end = b->data + b->l_data; |
4417 | | |
4418 | 16.1M | while (end - s >= 4) { |
4419 | 1.23M | kputc_chk_(&r, '\t', str); |
4420 | 1.23M | if ((s = (uint8_t *)sam_format_aux1(s, s[2], s+3, end, str)) == NULL) |
4421 | 1.54k | goto bad_aux; |
4422 | 1.23M | } |
4423 | 14.8M | kputsn_chk(&r, "", 0, str); // nul terminate |
4424 | 14.8M | if (r) goto mem_err; |
4425 | | |
4426 | 14.8M | return str->l; |
4427 | | |
4428 | 1.54k | bad_aux: |
4429 | 1.54k | hts_log_error("Corrupted aux data for read %.*s flag %d", |
4430 | 1.54k | b->core.l_qname, bam_get_qname(b), b->core.flag); |
4431 | 1.54k | errno = EINVAL; |
4432 | 1.54k | return -1; |
4433 | | |
4434 | 0 | mem_err: |
4435 | 0 | hts_log_error("Out of memory"); |
4436 | 0 | errno = ENOMEM; |
4437 | 0 | return -1; |
4438 | 14.8M | } |
4439 | | |
4440 | | int sam_format1(const bam_hdr_t *h, const bam1_t *b, kstring_t *str) |
4441 | 14.8M | { |
4442 | 14.8M | str->l = 0; |
4443 | 14.8M | return sam_format1_append(h, b, str); |
4444 | 14.8M | } |
4445 | | |
4446 | | static inline uint8_t *skip_aux(uint8_t *s, uint8_t *end); |
4447 | | int fastq_format1(fastq_state *x, const bam1_t *b, kstring_t *str) |
4448 | 0 | { |
4449 | 0 | unsigned flag = b->core.flag; |
4450 | 0 | int i, e = 0, len = b->core.l_qseq; |
4451 | 0 | uint8_t *seq, *qual; |
4452 | |
|
4453 | 0 | str->l = 0; |
4454 | | |
4455 | | // Name |
4456 | 0 | if (kputc(x->nprefix, str) == EOF || kputs(bam_get_qname(b), str) == EOF) |
4457 | 0 | return -1; |
4458 | | |
4459 | | // UMI tag |
4460 | 0 | if (x && *x->UMI[0]) { |
4461 | | // Temporary copy of '#num' if present |
4462 | 0 | char plex[256]; |
4463 | 0 | size_t len = str->l; |
4464 | 0 | while (len && str->s[len] != ':' && str->s[len] != '#') |
4465 | 0 | len--; |
4466 | |
|
4467 | 0 | if (str->s[len] == '#' && str->l - len < 255) { |
4468 | 0 | memcpy(plex, &str->s[len], str->l - len); |
4469 | 0 | plex[str->l - len] = 0; |
4470 | 0 | str->l = len; |
4471 | 0 | } else { |
4472 | 0 | *plex = 0; |
4473 | 0 | } |
4474 | |
|
4475 | 0 | uint8_t *bc = NULL; |
4476 | 0 | int n; |
4477 | 0 | for (n = 0; !bc && n < UMI_TAGS; n++) |
4478 | 0 | bc = bam_aux_getZ(b, x->UMI[n]); |
4479 | 0 | if (bc) { |
4480 | 0 | int err = kputc(':', str) < 0; |
4481 | | // Replace any non-alpha with '+' |
4482 | 0 | while (*++bc) |
4483 | 0 | err |= kputc(isalpha_c(*bc) ? toupper_c(*bc) : '+', str) < 0; |
4484 | 0 | if (err) |
4485 | 0 | return -1; |
4486 | 0 | } |
4487 | | |
4488 | 0 | if (*plex && kputs(plex, str) < 0) |
4489 | 0 | return -1; |
4490 | 0 | } |
4491 | | |
4492 | | // /1 or /2 suffix |
4493 | 0 | if (x && x->rnum && (flag & BAM_FPAIRED)) { |
4494 | 0 | int r12 = flag & (BAM_FREAD1 | BAM_FREAD2); |
4495 | 0 | if (r12 == BAM_FREAD1) { |
4496 | 0 | if (kputs("/1", str) == EOF) |
4497 | 0 | return -1; |
4498 | 0 | } else if (r12 == BAM_FREAD2) { |
4499 | 0 | if (kputs("/2", str) == EOF) |
4500 | 0 | return -1; |
4501 | 0 | } |
4502 | 0 | } |
4503 | | |
4504 | | // Illumina CASAVA tag. |
4505 | | // This is <rnum>:<Y/N qcfail>:<control-bits>:<barcode-or-zero> |
4506 | 0 | if (x && x->casava) { |
4507 | 0 | int rnum = (flag & BAM_FREAD1)? 1 : (flag & BAM_FREAD2)? 2 : 0; |
4508 | 0 | char filtered = (flag & BAM_FQCFAIL)? 'Y' : 'N'; |
4509 | 0 | uint8_t *bc = bam_aux_getZ(b, x->BC); |
4510 | 0 | if (ksprintf(str, " %d:%c:0:%s", rnum, filtered, |
4511 | 0 | bc ? (char *)bc+1 : "0") < 0) |
4512 | 0 | return -1; |
4513 | | |
4514 | 0 | if (bc && !isupper_c(bc[1]) && !islower_c(bc[1])) { |
4515 | 0 | hts_log_warning("BC tag starts with non-sequence base; using '0'"); |
4516 | | // Stop the barcode we just added and add "0" |
4517 | 0 | str->l -= strlen((char *)bc+1); |
4518 | 0 | if (kputc('0', str) < 0) |
4519 | 0 | return -1; |
4520 | 0 | bc = NULL; |
4521 | 0 | } |
4522 | | |
4523 | | // Replace any non-alpha with '+'. Ie seq-seq to seq+seq |
4524 | 0 | if (bc) { |
4525 | 0 | int l = strlen((char *)bc+1); |
4526 | 0 | char *c = (char *)str->s + str->l - l; |
4527 | 0 | for (i = 0; i < l; i++) { |
4528 | 0 | if (!isalpha_c(c[i])) |
4529 | 0 | c[i] = '+'; |
4530 | 0 | else if (islower_c(c[i])) |
4531 | 0 | c[i] = toupper_c(c[i]); |
4532 | 0 | } |
4533 | 0 | } |
4534 | 0 | } |
4535 | | |
4536 | | // Aux tags |
4537 | 0 | if (x && x->aux) { |
4538 | 0 | uint8_t *s = bam_get_aux(b), *end = b->data + b->l_data; |
4539 | 0 | while (s && end - s >= 4) { |
4540 | 0 | int tt = s[0]*256 + s[1]; |
4541 | 0 | if (x->tags == NULL || |
4542 | 0 | kh_get(tag, x->tags, tt) != kh_end(x->tags)) { |
4543 | 0 | e |= kputc_('\t', str) < 0; |
4544 | 0 | if (!(s = (uint8_t *)sam_format_aux1(s, s[2], s+3, end, str))) |
4545 | 0 | return -1; |
4546 | 0 | } else { |
4547 | 0 | s = skip_aux(s+2, end); |
4548 | 0 | } |
4549 | 0 | } |
4550 | 0 | e |= kputsn("", 0, str) < 0; // nul terminate |
4551 | 0 | } |
4552 | | |
4553 | 0 | if (ks_resize(str, str->l + 1 + len+1 + 2 + len+1 + 1) < 0) return -1; |
4554 | 0 | e |= kputc_('\n', str) < 0; |
4555 | | |
4556 | | // Seq line |
4557 | 0 | seq = bam_get_seq(b); |
4558 | 0 | if (flag & BAM_FREVERSE) |
4559 | 0 | for (i = len-1; i >= 0; i--) |
4560 | 0 | e |= kputc_("!TGKCYSBAWRDMHVN"[bam_seqi(seq, i)], str) < 0; |
4561 | 0 | else |
4562 | 0 | for (i = 0; i < len; i++) |
4563 | 0 | e |= kputc_(seq_nt16_str[bam_seqi(seq, i)], str) < 0; |
4564 | | |
4565 | | |
4566 | | // Qual line |
4567 | 0 | if (x->nprefix == '@') { |
4568 | 0 | e |= kputsn("\n+\n", 3, str) < 0; |
4569 | 0 | qual = bam_get_qual(b); |
4570 | 0 | if (qual[0] == 0xff) |
4571 | 0 | for (i = 0; i < len; i++) |
4572 | 0 | e |= kputc_('B', str) < 0; |
4573 | 0 | else if (flag & BAM_FREVERSE) |
4574 | 0 | for (i = len-1; i >= 0; i--) |
4575 | 0 | e |= kputc_(33 + qual[i], str) < 0; |
4576 | 0 | else |
4577 | 0 | for (i = 0; i < len; i++) |
4578 | 0 | e |= kputc_(33 + qual[i], str) < 0; |
4579 | |
|
4580 | 0 | } |
4581 | 0 | e |= kputc('\n', str) < 0; |
4582 | |
|
4583 | 0 | return e ? -1 : str->l; |
4584 | 0 | } |
4585 | | |
4586 | | // Sadly we need to be able to modify the bam_hdr here so we can |
4587 | | // reference count the structure. |
4588 | | int sam_write1(htsFile *fp, const sam_hdr_t *h, const bam1_t *b) |
4589 | 44.9M | { |
4590 | 44.9M | switch (fp->format.format) { |
4591 | 0 | case binary_format: |
4592 | 0 | fp->format.category = sequence_data; |
4593 | 0 | fp->format.format = bam; |
4594 | | /* fall-through */ |
4595 | 15.0M | case bam: |
4596 | 15.0M | return bam_write_idx1(fp, h, b); |
4597 | | |
4598 | 15.0M | case cram: |
4599 | 15.0M | return cram_put_bam_seq(fp->fp.cram, (bam1_t *)b); |
4600 | | |
4601 | 0 | case text_format: |
4602 | 0 | fp->format.category = sequence_data; |
4603 | 0 | fp->format.format = sam; |
4604 | | /* fall-through */ |
4605 | 14.8M | case sam: |
4606 | 14.8M | if (fp->state) { |
4607 | 0 | SAM_state *fd = (SAM_state *)fp->state; |
4608 | | |
4609 | | // Threaded output |
4610 | 0 | if (!fd->h) { |
4611 | | // NB: discard const. We don't actually modify sam_hdr_t here, |
4612 | | // just data pointed to by it (which is a bit weasely still), |
4613 | | // but out cached pointer must be non-const as we want to |
4614 | | // destroy it later on and sam_hdr_destroy takes non-const. |
4615 | | // |
4616 | | // We do this because some tools do sam_hdr_destroy; sam_close |
4617 | | // while others do sam_close; sam_hdr_destroy. The former is |
4618 | | // an issue as we need the header still when flushing. |
4619 | 0 | fd->h = (sam_hdr_t *)h; |
4620 | 0 | fd->h->ref_count++; |
4621 | |
|
4622 | 0 | if (pthread_create(&fd->dispatcher, NULL, sam_dispatcher_write, |
4623 | 0 | fp) != 0) |
4624 | 0 | return -2; |
4625 | 0 | fd->dispatcher_set = 1; |
4626 | 0 | } |
4627 | | |
4628 | 0 | if (fd->h != h) { |
4629 | 0 | hts_log_error("SAM multi-threaded decoding does not support changing header"); |
4630 | 0 | return -2; |
4631 | 0 | } |
4632 | | |
4633 | | // Find a suitable BAM array to copy to |
4634 | 0 | sp_bams *gb = fd->curr_bam; |
4635 | 0 | if (!gb) { |
4636 | 0 | pthread_mutex_lock(&fd->lines_m); |
4637 | 0 | if (fd->bams) { |
4638 | 0 | fd->curr_bam = gb = fd->bams; |
4639 | 0 | fd->bams = gb->next; |
4640 | 0 | gb->next = NULL; |
4641 | 0 | gb->nbams = 0; |
4642 | 0 | gb->bam_mem = 0; |
4643 | 0 | pthread_mutex_unlock(&fd->lines_m); |
4644 | 0 | } else { |
4645 | 0 | pthread_mutex_unlock(&fd->lines_m); |
4646 | 0 | if (!(gb = calloc(1, sizeof(*gb)))) return -1; |
4647 | 0 | if (!(gb->bams = calloc(SAM_NBAM, sizeof(*gb->bams)))) { |
4648 | 0 | free(gb); |
4649 | 0 | return -1; |
4650 | 0 | } |
4651 | 0 | gb->nbams = 0; |
4652 | 0 | gb->abams = SAM_NBAM; |
4653 | 0 | gb->bam_mem = 0; |
4654 | 0 | gb->fd = fd; |
4655 | 0 | fd->curr_idx = 0; |
4656 | 0 | fd->curr_bam = gb; |
4657 | 0 | } |
4658 | 0 | } |
4659 | | |
4660 | 0 | if (!bam_copy1(&gb->bams[gb->nbams++], b)) |
4661 | 0 | return -2; |
4662 | 0 | gb->bam_mem += b->l_data + sizeof(*b); |
4663 | | |
4664 | | // Dispatch if full |
4665 | 0 | if (gb->nbams == SAM_NBAM || gb->bam_mem > SAM_NBYTES*0.8) { |
4666 | 0 | gb->serial = fd->serial++; |
4667 | 0 | pthread_mutex_lock(&fd->command_m); |
4668 | 0 | if (fd->errcode != 0) { |
4669 | 0 | pthread_mutex_unlock(&fd->command_m); |
4670 | 0 | return -fd->errcode; |
4671 | 0 | } |
4672 | 0 | if (hts_tpool_dispatch3(fd->p, fd->q, sam_format_worker, gb, |
4673 | 0 | cleanup_sp_bams, |
4674 | 0 | cleanup_sp_lines, 0) < 0) { |
4675 | 0 | pthread_mutex_unlock(&fd->command_m); |
4676 | 0 | return -1; |
4677 | 0 | } |
4678 | 0 | pthread_mutex_unlock(&fd->command_m); |
4679 | 0 | fd->curr_bam = NULL; |
4680 | 0 | } |
4681 | | |
4682 | | // Dummy value as we don't know how long it really is. |
4683 | | // We could track file sizes via a SAM_state field, but I don't think |
4684 | | // it is necessary. |
4685 | 0 | return 1; |
4686 | 14.8M | } else { |
4687 | 14.8M | if (sam_format1(h, b, &fp->line) < 0) return -1; |
4688 | 14.8M | if (kputc('\n', &fp->line) < 0) return -1; |
4689 | 14.8M | if (fp->is_bgzf) { |
4690 | 0 | if (bgzf_flush_try(fp->fp.bgzf, fp->line.l) < 0) |
4691 | 0 | return -1; |
4692 | 0 | if ( bgzf_write(fp->fp.bgzf, fp->line.s, fp->line.l) != fp->line.l ) return -1; |
4693 | 14.8M | } else { |
4694 | 14.8M | if ( hwrite(fp->fp.hfile, fp->line.s, fp->line.l) != fp->line.l ) return -1; |
4695 | 14.8M | } |
4696 | | |
4697 | 14.8M | if (fp->idx) { |
4698 | 0 | if (fp->format.compression == bgzf) { |
4699 | 0 | if (bgzf_idx_push(fp->fp.bgzf, fp->idx, b->core.tid, b->core.pos, bam_endpos(b), |
4700 | 0 | bgzf_tell(fp->fp.bgzf), !(b->core.flag&BAM_FUNMAP)) < 0) { |
4701 | 0 | hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed", |
4702 | 0 | bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), b->core.flag, b->core.pos+1); |
4703 | 0 | return -1; |
4704 | 0 | } |
4705 | 0 | } else { |
4706 | 0 | if (hts_idx_push(fp->idx, b->core.tid, b->core.pos, bam_endpos(b), |
4707 | 0 | bgzf_tell(fp->fp.bgzf), !(b->core.flag&BAM_FUNMAP)) < 0) { |
4708 | 0 | hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed", |
4709 | 0 | bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), b->core.flag, b->core.pos+1); |
4710 | 0 | return -1; |
4711 | 0 | } |
4712 | 0 | } |
4713 | 0 | } |
4714 | | |
4715 | 14.8M | return fp->line.l; |
4716 | 14.8M | } |
4717 | | |
4718 | | |
4719 | 0 | case fasta_format: |
4720 | 0 | case fastq_format: { |
4721 | 0 | fastq_state *x = (fastq_state *)fp->state; |
4722 | 0 | if (!x) { |
4723 | 0 | if (!(fp->state = fastq_state_init(fp->format.format |
4724 | 0 | == fastq_format ? '@' : '>'))) |
4725 | 0 | return -2; |
4726 | 0 | } |
4727 | | |
4728 | 0 | if (fastq_format1(fp->state, b, &fp->line) < 0) |
4729 | 0 | return -1; |
4730 | 0 | if (fp->is_bgzf) { |
4731 | 0 | if (bgzf_flush_try(fp->fp.bgzf, fp->line.l) < 0) |
4732 | 0 | return -1; |
4733 | 0 | if (bgzf_write(fp->fp.bgzf, fp->line.s, fp->line.l) != fp->line.l) |
4734 | 0 | return -1; |
4735 | 0 | } else { |
4736 | 0 | if (hwrite(fp->fp.hfile, fp->line.s, fp->line.l) != fp->line.l) |
4737 | 0 | return -1; |
4738 | 0 | } |
4739 | 0 | return fp->line.l; |
4740 | 0 | } |
4741 | | |
4742 | 0 | default: |
4743 | 0 | errno = EBADF; |
4744 | 0 | return -1; |
4745 | 44.9M | } |
4746 | 44.9M | } |
4747 | | |
4748 | | /************************ |
4749 | | *** Auxiliary fields *** |
4750 | | ************************/ |
4751 | | #ifndef HTS_LITTLE_ENDIAN |
4752 | | static int aux_to_le(char type, uint8_t *out, const uint8_t *in, size_t len) { |
4753 | | int tsz = aux_type2size(type); |
4754 | | |
4755 | | if (tsz >= 2 && tsz <= 8 && (len & (tsz - 1)) != 0) return -1; |
4756 | | |
4757 | | switch (tsz) { |
4758 | | case 'H': case 'Z': case 1: // Trivial |
4759 | | memcpy(out, in, len); |
4760 | | break; |
4761 | | |
4762 | | #define aux_val_to_le(type_t, store_le) do { \ |
4763 | | type_t v; \ |
4764 | | size_t i; \ |
4765 | | for (i = 0; i < len; i += sizeof(type_t), out += sizeof(type_t)) { \ |
4766 | | memcpy(&v, in + i, sizeof(type_t)); \ |
4767 | | store_le(v, out); \ |
4768 | | } \ |
4769 | | } while (0) |
4770 | | |
4771 | | case 2: aux_val_to_le(uint16_t, u16_to_le); break; |
4772 | | case 4: aux_val_to_le(uint32_t, u32_to_le); break; |
4773 | | case 8: aux_val_to_le(uint64_t, u64_to_le); break; |
4774 | | |
4775 | | #undef aux_val_to_le |
4776 | | |
4777 | | case 'B': { // Recurse! |
4778 | | uint32_t n; |
4779 | | if (len < 5) return -1; |
4780 | | memcpy(&n, in + 1, 4); |
4781 | | out[0] = in[0]; |
4782 | | u32_to_le(n, out + 1); |
4783 | | return aux_to_le(in[0], out + 5, in + 5, len - 5); |
4784 | | } |
4785 | | |
4786 | | default: // Unknown type code |
4787 | | return -1; |
4788 | | } |
4789 | | |
4790 | | |
4791 | | |
4792 | | return 0; |
4793 | | } |
4794 | | #endif |
4795 | | |
4796 | | int bam_aux_append(bam1_t *b, const char tag[2], char type, int len, const uint8_t *data) |
4797 | 0 | { |
4798 | 0 | uint32_t new_len; |
4799 | |
|
4800 | 0 | assert(b->l_data >= 0); |
4801 | 0 | new_len = b->l_data + 3 + len; |
4802 | 0 | if (new_len > INT32_MAX || new_len < b->l_data) goto nomem; |
4803 | | |
4804 | 0 | if (realloc_bam_data(b, new_len) < 0) return -1; |
4805 | | |
4806 | 0 | b->data[b->l_data] = tag[0]; |
4807 | 0 | b->data[b->l_data + 1] = tag[1]; |
4808 | 0 | b->data[b->l_data + 2] = type; |
4809 | |
|
4810 | 0 | #ifdef HTS_LITTLE_ENDIAN |
4811 | 0 | memcpy(b->data + b->l_data + 3, data, len); |
4812 | | #else |
4813 | | if (aux_to_le(type, b->data + b->l_data + 3, data, len) != 0) { |
4814 | | errno = EINVAL; |
4815 | | return -1; |
4816 | | } |
4817 | | #endif |
4818 | |
|
4819 | 0 | b->l_data = new_len; |
4820 | |
|
4821 | 0 | return 0; |
4822 | | |
4823 | 0 | nomem: |
4824 | 0 | errno = ENOMEM; |
4825 | 0 | return -1; |
4826 | 0 | } |
4827 | | |
4828 | | static inline uint8_t *skip_aux(uint8_t *s, uint8_t *end) |
4829 | 3.55M | { |
4830 | 3.55M | int64_t size; |
4831 | 3.55M | uint32_t n; |
4832 | 3.55M | if (s >= end) return end; |
4833 | 3.55M | size = aux_type2size(*s); ++s; // skip type |
4834 | 3.55M | switch (size) { |
4835 | 735k | case 'Z': |
4836 | 742k | case 'H': |
4837 | 742k | s = memchr(s, 0, end-s); |
4838 | 742k | return s ? s+1 : end; |
4839 | 168k | case 'B': |
4840 | 168k | if (end - s < 5) return NULL; |
4841 | 168k | size = aux_type2Bsize(*s); ++s; |
4842 | 168k | n = le_to_u32(s); |
4843 | 168k | s += 4; |
4844 | 168k | if (size < 1 || end - s < size * n) return NULL; |
4845 | 168k | return s + size * n; |
4846 | 613 | case 0: |
4847 | 613 | return NULL; |
4848 | 2.63M | default: |
4849 | 2.63M | if (end - s < size) return NULL; |
4850 | 2.63M | return s + size; |
4851 | 3.55M | } |
4852 | 3.55M | } |
4853 | | |
4854 | | uint8_t *bam_aux_first(const bam1_t *b) |
4855 | 15.2M | { |
4856 | 15.2M | uint8_t *s = bam_get_aux(b); |
4857 | 15.2M | uint8_t *end = b->data + b->l_data; |
4858 | 15.2M | if (end - s <= 2) { errno = ENOENT; return NULL; } |
4859 | | |
4860 | | // Check the tag value is valid and complete |
4861 | 406k | uint8_t *e = skip_aux(s+2, end); |
4862 | 406k | if (e == NULL) |
4863 | 620 | goto bad_aux; |
4864 | 406k | if ((s[2] == 'Z' || s[2] == 'H') && *(e - 1) != '\0') |
4865 | 9 | goto bad_aux; |
4866 | | |
4867 | 406k | return s+2; |
4868 | | |
4869 | 629 | bad_aux: |
4870 | 629 | hts_log_error("Corrupted aux data for read %s flag %d", |
4871 | 629 | bam_get_qname(b), b->core.flag); |
4872 | 629 | errno = EINVAL; |
4873 | 629 | return NULL; |
4874 | 406k | } |
4875 | | |
4876 | | uint8_t *bam_aux_next(const bam1_t *b, const uint8_t *s) |
4877 | 1.55M | { |
4878 | 1.55M | uint8_t *end = b->data + b->l_data; |
4879 | 1.55M | uint8_t *next = s? skip_aux((uint8_t *) s, end) : end; |
4880 | 1.55M | if (next == NULL) goto bad_aux; |
4881 | 1.55M | if (end - next <= 2) { errno = ENOENT; return NULL; } |
4882 | | |
4883 | | // Check the tag value is valid and complete |
4884 | 1.36M | uint8_t *e = skip_aux(next+2, end); |
4885 | 1.36M | if (e == NULL) |
4886 | 145 | goto bad_aux; |
4887 | 1.36M | if ((next[2] == 'Z' || next[2] == 'H') && *(e - 1) != '\0') |
4888 | 10 | goto bad_aux; |
4889 | | |
4890 | 1.36M | return next+2; |
4891 | | |
4892 | 155 | bad_aux: |
4893 | 155 | hts_log_error("Corrupted aux data for read %s flag %d", |
4894 | 155 | bam_get_qname(b), b->core.flag); |
4895 | 155 | errno = EINVAL; |
4896 | 155 | return NULL; |
4897 | 1.36M | } |
4898 | | |
4899 | | uint8_t *bam_aux_get(const bam1_t *b, const char tag[2]) |
4900 | 15.2M | { |
4901 | 15.2M | uint8_t *s; |
4902 | 16.8M | for (s = bam_aux_first(b); s; s = bam_aux_next(b, s)) |
4903 | 1.77M | if (s[-2] == tag[0] && s[-1] == tag[1]) { |
4904 | | // Check the tag value is valid and complete |
4905 | 216k | uint8_t *e = skip_aux(s, b->data + b->l_data); |
4906 | 216k | if (e == NULL) goto bad_aux; |
4907 | 216k | if ((*s == 'Z' || *s == 'H') && *(e - 1) != '\0') goto bad_aux; |
4908 | | |
4909 | 216k | return s; |
4910 | 216k | } |
4911 | | |
4912 | | // errno now as set by bam_aux_first()/bam_aux_next() |
4913 | 15.0M | return NULL; |
4914 | | |
4915 | 0 | bad_aux: |
4916 | 0 | hts_log_error("Corrupted aux data for read %s flag %d", |
4917 | 0 | bam_get_qname(b), b->core.flag); |
4918 | 0 | errno = EINVAL; |
4919 | 0 | return NULL; |
4920 | 15.2M | } |
4921 | | |
4922 | | // As per bam_aux_get, but treats any tag not of type Z as absent. |
4923 | | // TODO: consider extending the public API with this functionality too. |
4924 | 0 | static uint8_t *bam_aux_getZ(const bam1_t *b, const char tag[2]) { |
4925 | 0 | uint8_t *s = bam_aux_get(b, tag); |
4926 | 0 | return s && *s == 'Z' ? s : NULL; |
4927 | 0 | } |
4928 | | |
4929 | | int bam_aux_del(bam1_t *b, uint8_t *s) |
4930 | 0 | { |
4931 | 0 | s = bam_aux_remove(b, s); |
4932 | 0 | return (s || errno == ENOENT)? 0 : -1; |
4933 | 0 | } |
4934 | | |
4935 | | uint8_t *bam_aux_remove(bam1_t *b, uint8_t *s) |
4936 | 0 | { |
4937 | 0 | uint8_t *end = b->data + b->l_data; |
4938 | 0 | uint8_t *next = skip_aux(s, end); |
4939 | 0 | if (next == NULL) goto bad_aux; |
4940 | | |
4941 | 0 | b->l_data -= next - (s-2); |
4942 | 0 | if (next >= end) { errno = ENOENT; return NULL; } |
4943 | | |
4944 | 0 | memmove(s-2, next, end - next); |
4945 | 0 | return s; |
4946 | | |
4947 | 0 | bad_aux: |
4948 | 0 | hts_log_error("Corrupted aux data for read %s flag %d", |
4949 | 0 | bam_get_qname(b), b->core.flag); |
4950 | 0 | errno = EINVAL; |
4951 | 0 | return NULL; |
4952 | 0 | } |
4953 | | |
4954 | | int bam_aux_update_str(bam1_t *b, const char tag[2], int len, const char *data) |
4955 | 0 | { |
4956 | | // FIXME: This is not at all efficient! |
4957 | 0 | size_t ln = len >= 0 ? len : strlen(data) + 1; |
4958 | 0 | size_t old_ln = 0; |
4959 | 0 | int need_nul = ln == 0 || data[ln - 1] != '\0'; |
4960 | 0 | int save_errno = errno; |
4961 | 0 | int new_tag = 0; |
4962 | 0 | uint8_t *s = bam_aux_get(b,tag), *e; |
4963 | |
|
4964 | 0 | if (s) { // Replacing existing tag |
4965 | 0 | char type = *s; |
4966 | 0 | if (type != 'Z') { |
4967 | 0 | hts_log_error("Called bam_aux_update_str for type '%c' instead of 'Z'", type); |
4968 | 0 | errno = EINVAL; |
4969 | 0 | return -1; |
4970 | 0 | } |
4971 | 0 | s++; |
4972 | 0 | e = memchr(s, '\0', b->data + b->l_data - s); |
4973 | 0 | old_ln = (e ? e - s : b->data + b->l_data - s) + 1; |
4974 | 0 | s -= 3; |
4975 | 0 | } else { |
4976 | 0 | if (errno != ENOENT) { // Invalid aux data, give up |
4977 | 0 | return -1; |
4978 | 0 | } else { // Tag doesn't exist - put it on the end |
4979 | 0 | errno = save_errno; |
4980 | 0 | s = b->data + b->l_data; |
4981 | 0 | new_tag = 3; |
4982 | 0 | } |
4983 | 0 | } |
4984 | | |
4985 | 0 | if (old_ln < ln + need_nul + new_tag) { |
4986 | 0 | ptrdiff_t s_offset = s - b->data; |
4987 | 0 | if (possibly_expand_bam_data(b, ln + need_nul + new_tag - old_ln) < 0) |
4988 | 0 | return -1; |
4989 | 0 | s = b->data + s_offset; |
4990 | 0 | } |
4991 | 0 | if (!new_tag) { |
4992 | 0 | memmove(s + 3 + ln + need_nul, |
4993 | 0 | s + 3 + old_ln, |
4994 | 0 | b->l_data - (s + 3 - b->data) - old_ln); |
4995 | 0 | } |
4996 | 0 | b->l_data += new_tag + ln + need_nul - old_ln; |
4997 | |
|
4998 | 0 | s[0] = tag[0]; |
4999 | 0 | s[1] = tag[1]; |
5000 | 0 | s[2] = 'Z'; |
5001 | 0 | memmove(s+3,data,ln); |
5002 | 0 | if (need_nul) s[3 + ln] = '\0'; |
5003 | 0 | return 0; |
5004 | 0 | } |
5005 | | |
5006 | | int bam_aux_update_int(bam1_t *b, const char tag[2], int64_t val) |
5007 | 0 | { |
5008 | 0 | uint32_t sz, old_sz = 0, new = 0; |
5009 | 0 | uint8_t *s, type; |
5010 | |
|
5011 | 0 | if (val < INT32_MIN || val > UINT32_MAX) { |
5012 | 0 | errno = EOVERFLOW; |
5013 | 0 | return -1; |
5014 | 0 | } |
5015 | 0 | if (val < INT16_MIN) { type = 'i'; sz = 4; } |
5016 | 0 | else if (val < INT8_MIN) { type = 's'; sz = 2; } |
5017 | 0 | else if (val < 0) { type = 'c'; sz = 1; } |
5018 | 0 | else if (val < UINT8_MAX) { type = 'C'; sz = 1; } |
5019 | 0 | else if (val < UINT16_MAX) { type = 'S'; sz = 2; } |
5020 | 0 | else { type = 'I'; sz = 4; } |
5021 | |
|
5022 | 0 | s = bam_aux_get(b, tag); |
5023 | 0 | if (s) { // Tag present - how big was the old one? |
5024 | 0 | switch (*s) { |
5025 | 0 | case 'c': case 'C': old_sz = 1; break; |
5026 | 0 | case 's': case 'S': old_sz = 2; break; |
5027 | 0 | case 'i': case 'I': old_sz = 4; break; |
5028 | 0 | default: errno = EINVAL; return -1; // Not an integer |
5029 | 0 | } |
5030 | 0 | } else { |
5031 | 0 | if (errno == ENOENT) { // Tag doesn't exist - add a new one |
5032 | 0 | s = b->data + b->l_data; |
5033 | 0 | new = 1; |
5034 | 0 | } else { // Invalid aux data, give up. |
5035 | 0 | return -1; |
5036 | 0 | } |
5037 | 0 | } |
5038 | | |
5039 | 0 | if (new || old_sz < sz) { |
5040 | | // Make room for new tag |
5041 | 0 | ptrdiff_t s_offset = s - b->data; |
5042 | 0 | if (possibly_expand_bam_data(b, (new ? 3 : 0) + sz - old_sz) < 0) |
5043 | 0 | return -1; |
5044 | 0 | s = b->data + s_offset; |
5045 | 0 | if (new) { // Add tag id |
5046 | 0 | *s++ = tag[0]; |
5047 | 0 | *s++ = tag[1]; |
5048 | 0 | } else { // Shift following data so we have space |
5049 | 0 | memmove(s + sz, s + old_sz, b->l_data - s_offset - old_sz); |
5050 | 0 | } |
5051 | 0 | } else { |
5052 | | // Reuse old space. Data value may be bigger than necessary but |
5053 | | // we avoid having to move everything else |
5054 | 0 | sz = old_sz; |
5055 | 0 | type = (val < 0 ? "\0cs\0i" : "\0CS\0I")[old_sz]; |
5056 | 0 | assert(type > 0); |
5057 | 0 | } |
5058 | 0 | *s++ = type; |
5059 | 0 | #ifdef HTS_LITTLE_ENDIAN |
5060 | 0 | memcpy(s, &val, sz); |
5061 | | #else |
5062 | | switch (sz) { |
5063 | | case 4: u32_to_le(val, s); break; |
5064 | | case 2: u16_to_le(val, s); break; |
5065 | | default: *s = val; break; |
5066 | | } |
5067 | | #endif |
5068 | 0 | b->l_data += (new ? 3 : 0) + sz - old_sz; |
5069 | 0 | return 0; |
5070 | 0 | } |
5071 | | |
5072 | | int bam_aux_update_float(bam1_t *b, const char tag[2], float val) |
5073 | 0 | { |
5074 | 0 | uint8_t *s = bam_aux_get(b, tag); |
5075 | 0 | int shrink = 0, new = 0; |
5076 | |
|
5077 | 0 | if (s) { // Tag present - what was it? |
5078 | 0 | switch (*s) { |
5079 | 0 | case 'f': break; |
5080 | 0 | case 'd': shrink = 1; break; |
5081 | 0 | default: errno = EINVAL; return -1; // Not a float |
5082 | 0 | } |
5083 | 0 | } else { |
5084 | 0 | if (errno == ENOENT) { // Tag doesn't exist - add a new one |
5085 | 0 | new = 1; |
5086 | 0 | } else { // Invalid aux data, give up. |
5087 | 0 | return -1; |
5088 | 0 | } |
5089 | 0 | } |
5090 | | |
5091 | 0 | if (new) { // Ensure there's room |
5092 | 0 | if (possibly_expand_bam_data(b, 3 + 4) < 0) |
5093 | 0 | return -1; |
5094 | 0 | s = b->data + b->l_data; |
5095 | 0 | *s++ = tag[0]; |
5096 | 0 | *s++ = tag[1]; |
5097 | 0 | } else if (shrink) { // Convert non-standard double tag to float |
5098 | 0 | memmove(s + 5, s + 9, b->l_data - ((s + 9) - b->data)); |
5099 | 0 | b->l_data -= 4; |
5100 | 0 | } |
5101 | 0 | *s++ = 'f'; |
5102 | 0 | float_to_le(val, s); |
5103 | 0 | if (new) b->l_data += 7; |
5104 | |
|
5105 | 0 | return 0; |
5106 | 0 | } |
5107 | | |
5108 | | int bam_aux_update_array(bam1_t *b, const char tag[2], |
5109 | | uint8_t type, uint32_t items, void *data) |
5110 | 0 | { |
5111 | 0 | uint8_t *s = bam_aux_get(b, tag); |
5112 | 0 | size_t old_sz = 0, new_sz; |
5113 | 0 | int new = 0; |
5114 | |
|
5115 | 0 | if (s) { // Tag present |
5116 | 0 | if (*s != 'B') { errno = EINVAL; return -1; } |
5117 | 0 | old_sz = aux_type2Bsize(s[1]); |
5118 | 0 | if (old_sz < 1) { errno = EINVAL; return -1; } |
5119 | 0 | old_sz *= le_to_u32(s + 2); |
5120 | 0 | } else { |
5121 | 0 | if (errno == ENOENT) { // Tag doesn't exist - add a new one |
5122 | 0 | s = b->data + b->l_data; |
5123 | 0 | new = 1; |
5124 | 0 | } else { // Invalid aux data, give up. |
5125 | 0 | return -1; |
5126 | 0 | } |
5127 | 0 | } |
5128 | | |
5129 | 0 | new_sz = aux_type2Bsize(type); |
5130 | 0 | if (new_sz < 1) { errno = EINVAL; return -1; } |
5131 | 0 | if (items > INT32_MAX / new_sz) { errno = ENOMEM; return -1; } |
5132 | 0 | new_sz *= items; |
5133 | |
|
5134 | 0 | if (new || old_sz < new_sz) { |
5135 | | // Make room for new tag |
5136 | 0 | ptrdiff_t s_offset = s - b->data; |
5137 | 0 | if (possibly_expand_bam_data(b, (new ? 8 : 0) + new_sz - old_sz) < 0) |
5138 | 0 | return -1; |
5139 | 0 | s = b->data + s_offset; |
5140 | 0 | } |
5141 | 0 | if (new) { // Add tag id and type |
5142 | 0 | *s++ = tag[0]; |
5143 | 0 | *s++ = tag[1]; |
5144 | 0 | *s = 'B'; |
5145 | 0 | b->l_data += 8 + new_sz; |
5146 | 0 | } else if (old_sz != new_sz) { // shift following data if necessary |
5147 | 0 | memmove(s + 6 + new_sz, s + 6 + old_sz, |
5148 | 0 | b->l_data - ((s + 6 + old_sz) - b->data)); |
5149 | 0 | b->l_data -= old_sz; |
5150 | 0 | b->l_data += new_sz; |
5151 | 0 | } |
5152 | |
|
5153 | 0 | s[1] = type; |
5154 | 0 | u32_to_le(items, s + 2); |
5155 | 0 | if (new_sz > 0) { |
5156 | 0 | #ifdef HTS_LITTLE_ENDIAN |
5157 | 0 | memcpy(s + 6, data, new_sz); |
5158 | | #else |
5159 | | return aux_to_le(type, s + 6, data, new_sz); |
5160 | | #endif |
5161 | 0 | } |
5162 | 0 | return 0; |
5163 | 0 | } |
5164 | | |
5165 | | static inline int64_t get_int_aux_val(uint8_t type, const uint8_t *s, |
5166 | | uint32_t idx) |
5167 | 0 | { |
5168 | 0 | switch (type) { |
5169 | 0 | case 'c': return le_to_i8(s + idx); |
5170 | 0 | case 'C': return s[idx]; |
5171 | 0 | case 's': return le_to_i16(s + 2 * idx); |
5172 | 0 | case 'S': return le_to_u16(s + 2 * idx); |
5173 | 0 | case 'i': return le_to_i32(s + 4 * idx); |
5174 | 0 | case 'I': return le_to_u32(s + 4 * idx); |
5175 | 0 | default: |
5176 | 0 | errno = EINVAL; |
5177 | 0 | return 0; |
5178 | 0 | } |
5179 | 0 | } |
5180 | | |
5181 | | int64_t bam_aux2i(const uint8_t *s) |
5182 | 0 | { |
5183 | 0 | int type; |
5184 | 0 | type = *s++; |
5185 | 0 | return get_int_aux_val(type, s, 0); |
5186 | 0 | } |
5187 | | |
5188 | | double bam_aux2f(const uint8_t *s) |
5189 | 0 | { |
5190 | 0 | int type; |
5191 | 0 | type = *s++; |
5192 | 0 | if (type == 'd') return le_to_double(s); |
5193 | 0 | else if (type == 'f') return le_to_float(s); |
5194 | 0 | else return get_int_aux_val(type, s, 0); |
5195 | 0 | } |
5196 | | |
5197 | | char bam_aux2A(const uint8_t *s) |
5198 | 0 | { |
5199 | 0 | int type; |
5200 | 0 | type = *s++; |
5201 | 0 | if (type == 'A') return *(char*)s; |
5202 | 0 | errno = EINVAL; |
5203 | 0 | return 0; |
5204 | 0 | } |
5205 | | |
5206 | | char *bam_aux2Z(const uint8_t *s) |
5207 | 0 | { |
5208 | 0 | int type; |
5209 | 0 | type = *s++; |
5210 | 0 | if (type == 'Z' || type == 'H') return (char*)s; |
5211 | 0 | errno = EINVAL; |
5212 | 0 | return 0; |
5213 | 0 | } |
5214 | | |
5215 | | uint32_t bam_auxB_len(const uint8_t *s) |
5216 | 0 | { |
5217 | 0 | if (s[0] != 'B') { |
5218 | 0 | errno = EINVAL; |
5219 | 0 | return 0; |
5220 | 0 | } |
5221 | 0 | return le_to_u32(s + 2); |
5222 | 0 | } |
5223 | | |
5224 | | int64_t bam_auxB2i(const uint8_t *s, uint32_t idx) |
5225 | 0 | { |
5226 | 0 | uint32_t len = bam_auxB_len(s); |
5227 | 0 | if (idx >= len) { |
5228 | 0 | errno = ERANGE; |
5229 | 0 | return 0; |
5230 | 0 | } |
5231 | 0 | return get_int_aux_val(s[1], s + 6, idx); |
5232 | 0 | } |
5233 | | |
5234 | | double bam_auxB2f(const uint8_t *s, uint32_t idx) |
5235 | 0 | { |
5236 | 0 | uint32_t len = bam_auxB_len(s); |
5237 | 0 | if (idx >= len) { |
5238 | 0 | errno = ERANGE; |
5239 | 0 | return 0.0; |
5240 | 0 | } |
5241 | 0 | if (s[1] == 'f') return le_to_float(s + 6 + 4 * idx); |
5242 | 0 | else return get_int_aux_val(s[1], s + 6, idx); |
5243 | 0 | } |
5244 | | |
5245 | | int sam_open_mode(char *mode, const char *fn, const char *format) |
5246 | 0 | { |
5247 | | // TODO Parse "bam5" etc for compression level |
5248 | 0 | if (format == NULL) { |
5249 | | // Try to pick a format based on the filename extension |
5250 | 0 | char extension[HTS_MAX_EXT_LEN]; |
5251 | 0 | if (find_file_extension(fn, extension) < 0) return -1; |
5252 | 0 | return sam_open_mode(mode, fn, extension); |
5253 | 0 | } |
5254 | 0 | else if (strcasecmp(format, "bam") == 0) strcpy(mode, "b"); |
5255 | 0 | else if (strcasecmp(format, "cram") == 0) strcpy(mode, "c"); |
5256 | 0 | else if (strcasecmp(format, "sam") == 0) strcpy(mode, ""); |
5257 | 0 | else if (strcasecmp(format, "sam.gz") == 0) strcpy(mode, "z"); |
5258 | 0 | else if (strcasecmp(format, "fastq") == 0 || |
5259 | 0 | strcasecmp(format, "fq") == 0) strcpy(mode, "f"); |
5260 | 0 | else if (strcasecmp(format, "fastq.gz") == 0 || |
5261 | 0 | strcasecmp(format, "fq.gz") == 0) strcpy(mode, "fz"); |
5262 | 0 | else if (strcasecmp(format, "fasta") == 0 || |
5263 | 0 | strcasecmp(format, "fa") == 0) strcpy(mode, "F"); |
5264 | 0 | else if (strcasecmp(format, "fasta.gz") == 0 || |
5265 | 0 | strcasecmp(format, "fa.gz") == 0) strcpy(mode, "Fz"); |
5266 | 0 | else return -1; |
5267 | | |
5268 | 0 | return 0; |
5269 | 0 | } |
5270 | | |
5271 | | // A version of sam_open_mode that can handle ,key=value options. |
5272 | | // The format string is allocated and returned, to be freed by the caller. |
5273 | | // Prefix should be "r" or "w", |
5274 | | char *sam_open_mode_opts(const char *fn, |
5275 | | const char *mode, |
5276 | | const char *format) |
5277 | 0 | { |
5278 | 0 | char *mode_opts = malloc((format ? strlen(format) : 1) + |
5279 | 0 | (mode ? strlen(mode) : 1) + 12); |
5280 | 0 | char *cp; |
5281 | 0 | const char *opts; |
5282 | 0 | int format_len; |
5283 | |
|
5284 | 0 | if (!mode_opts) |
5285 | 0 | return NULL; |
5286 | | |
5287 | 0 | strcpy(mode_opts, mode ? mode : "r"); |
5288 | 0 | cp = mode_opts + strlen(mode_opts); |
5289 | |
|
5290 | 0 | if (format == NULL) { |
5291 | | // Try to pick a format based on the filename extension |
5292 | 0 | char extension[HTS_MAX_EXT_LEN]; |
5293 | 0 | if (find_file_extension(fn, extension) < 0) { |
5294 | 0 | free(mode_opts); |
5295 | 0 | return NULL; |
5296 | 0 | } |
5297 | 0 | if (sam_open_mode(cp, fn, extension) == 0) { |
5298 | 0 | return mode_opts; |
5299 | 0 | } else { |
5300 | 0 | free(mode_opts); |
5301 | 0 | return NULL; |
5302 | 0 | } |
5303 | 0 | } |
5304 | | |
5305 | 0 | if ((opts = strchr(format, ','))) { |
5306 | 0 | format_len = opts-format; |
5307 | 0 | } else { |
5308 | 0 | opts=""; |
5309 | 0 | format_len = strlen(format); |
5310 | 0 | } |
5311 | |
|
5312 | 0 | if (strncmp(format, "bam", format_len) == 0) { |
5313 | 0 | *cp++ = 'b'; |
5314 | 0 | } else if (strncmp(format, "cram", format_len) == 0) { |
5315 | 0 | *cp++ = 'c'; |
5316 | 0 | } else if (strncmp(format, "cram2", format_len) == 0) { |
5317 | 0 | *cp++ = 'c'; |
5318 | 0 | strcpy(cp, ",VERSION=2.1"); |
5319 | 0 | cp += 12; |
5320 | 0 | } else if (strncmp(format, "cram3", format_len) == 0) { |
5321 | 0 | *cp++ = 'c'; |
5322 | 0 | strcpy(cp, ",VERSION=3.0"); |
5323 | 0 | cp += 12; |
5324 | 0 | } else if (strncmp(format, "sam", format_len) == 0) { |
5325 | 0 | ; // format mode="" |
5326 | 0 | } else if (strncmp(format, "sam.gz", format_len) == 0) { |
5327 | 0 | *cp++ = 'z'; |
5328 | 0 | } else if (strncmp(format, "fastq", format_len) == 0 || |
5329 | 0 | strncmp(format, "fq", format_len) == 0) { |
5330 | 0 | *cp++ = 'f'; |
5331 | 0 | } else if (strncmp(format, "fastq.gz", format_len) == 0 || |
5332 | 0 | strncmp(format, "fq.gz", format_len) == 0) { |
5333 | 0 | *cp++ = 'f'; |
5334 | 0 | *cp++ = 'z'; |
5335 | 0 | } else if (strncmp(format, "fasta", format_len) == 0 || |
5336 | 0 | strncmp(format, "fa", format_len) == 0) { |
5337 | 0 | *cp++ = 'F'; |
5338 | 0 | } else if (strncmp(format, "fasta.gz", format_len) == 0 || |
5339 | 0 | strncmp(format, "fa", format_len) == 0) { |
5340 | 0 | *cp++ = 'F'; |
5341 | 0 | *cp++ = 'z'; |
5342 | 0 | } else { |
5343 | 0 | free(mode_opts); |
5344 | 0 | return NULL; |
5345 | 0 | } |
5346 | | |
5347 | 0 | strcpy(cp, opts); |
5348 | |
|
5349 | 0 | return mode_opts; |
5350 | 0 | } |
5351 | | |
5352 | 0 | #define STRNCMP(a,b,n) (strncasecmp((a),(b),(n)) || strlen(a)!=(n)) |
5353 | | int bam_str2flag(const char *str) |
5354 | 0 | { |
5355 | 0 | char *end, *beg = (char*) str; |
5356 | 0 | long int flag = strtol(str, &end, 0); |
5357 | 0 | if ( end!=str ) return flag; // the conversion was successful |
5358 | 0 | flag = 0; |
5359 | 0 | while ( *str ) |
5360 | 0 | { |
5361 | 0 | end = beg; |
5362 | 0 | while ( *end && *end!=',' ) end++; |
5363 | 0 | if ( !STRNCMP("PAIRED",beg,end-beg) ) flag |= BAM_FPAIRED; |
5364 | 0 | else if ( !STRNCMP("PROPER_PAIR",beg,end-beg) ) flag |= BAM_FPROPER_PAIR; |
5365 | 0 | else if ( !STRNCMP("UNMAP",beg,end-beg) ) flag |= BAM_FUNMAP; |
5366 | 0 | else if ( !STRNCMP("MUNMAP",beg,end-beg) ) flag |= BAM_FMUNMAP; |
5367 | 0 | else if ( !STRNCMP("REVERSE",beg,end-beg) ) flag |= BAM_FREVERSE; |
5368 | 0 | else if ( !STRNCMP("MREVERSE",beg,end-beg) ) flag |= BAM_FMREVERSE; |
5369 | 0 | else if ( !STRNCMP("READ1",beg,end-beg) ) flag |= BAM_FREAD1; |
5370 | 0 | else if ( !STRNCMP("READ2",beg,end-beg) ) flag |= BAM_FREAD2; |
5371 | 0 | else if ( !STRNCMP("SECONDARY",beg,end-beg) ) flag |= BAM_FSECONDARY; |
5372 | 0 | else if ( !STRNCMP("QCFAIL",beg,end-beg) ) flag |= BAM_FQCFAIL; |
5373 | 0 | else if ( !STRNCMP("DUP",beg,end-beg) ) flag |= BAM_FDUP; |
5374 | 0 | else if ( !STRNCMP("SUPPLEMENTARY",beg,end-beg) ) flag |= BAM_FSUPPLEMENTARY; |
5375 | 0 | else return -1; |
5376 | 0 | if ( !*end ) break; |
5377 | 0 | beg = end + 1; |
5378 | 0 | } |
5379 | 0 | return flag; |
5380 | 0 | } |
5381 | | |
5382 | | char *bam_flag2str(int flag) |
5383 | 0 | { |
5384 | 0 | kstring_t str = {0,0,0}; |
5385 | 0 | int nomem = 0; |
5386 | 0 | if ( flag&BAM_FPAIRED ) |
5387 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","PAIRED"); |
5388 | |
|
5389 | 0 | if ( flag&BAM_FPROPER_PAIR ) |
5390 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","PROPER_PAIR"); |
5391 | |
|
5392 | 0 | if ( flag&BAM_FUNMAP ) |
5393 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","UNMAP"); |
5394 | |
|
5395 | 0 | if ( flag&BAM_FMUNMAP ) |
5396 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","MUNMAP"); |
5397 | |
|
5398 | 0 | if ( flag&BAM_FREVERSE ) |
5399 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","REVERSE"); |
5400 | |
|
5401 | 0 | if ( flag&BAM_FMREVERSE ) |
5402 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","MREVERSE"); |
5403 | |
|
5404 | 0 | if ( flag&BAM_FREAD1 ) |
5405 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","READ1"); |
5406 | |
|
5407 | 0 | if ( flag&BAM_FREAD2 ) |
5408 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","READ2"); |
5409 | |
|
5410 | 0 | if ( flag&BAM_FSECONDARY ) |
5411 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","SECONDARY"); |
5412 | |
|
5413 | 0 | if ( flag&BAM_FQCFAIL ) |
5414 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","QCFAIL"); |
5415 | |
|
5416 | 0 | if ( flag&BAM_FDUP ) |
5417 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","DUP"); |
5418 | |
|
5419 | 0 | if ( flag&BAM_FSUPPLEMENTARY ) |
5420 | 0 | ksprintf_chk(&nomem, &str,"%s%s", str.l?",":"","SUPPLEMENTARY"); |
5421 | |
|
5422 | 0 | if ( str.l == 0 ) |
5423 | 0 | kputsn_chk(&nomem, "", 0, &str); |
5424 | |
|
5425 | 0 | if (nomem) { |
5426 | 0 | ks_free(&str); |
5427 | 0 | return NULL; |
5428 | 0 | } |
5429 | 0 | return str.s; |
5430 | 0 | } |
5431 | | |
5432 | | |
5433 | | /************************** |
5434 | | *** Pileup and Mpileup *** |
5435 | | **************************/ |
5436 | | |
5437 | | #if !defined(BAM_NO_PILEUP) |
5438 | | |
5439 | | #include <assert.h> |
5440 | | |
5441 | | /******************* |
5442 | | *** Memory pool *** |
5443 | | *******************/ |
5444 | | |
5445 | | typedef struct { |
5446 | | int k; |
5447 | | hts_pos_t x, y, end; |
5448 | | } cstate_t; |
5449 | | |
5450 | | static cstate_t g_cstate_null = { -1, 0, 0, 0 }; |
5451 | | |
5452 | | typedef struct __linkbuf_t { |
5453 | | bam1_t b; |
5454 | | hts_pos_t beg, end; |
5455 | | cstate_t s; |
5456 | | struct __linkbuf_t *next; |
5457 | | bam_pileup_cd cd; |
5458 | | } lbnode_t; |
5459 | | |
5460 | | typedef struct { |
5461 | | int cnt, n, max; |
5462 | | lbnode_t **buf; |
5463 | | } mempool_t; |
5464 | | |
5465 | | static mempool_t *mp_init(void) |
5466 | 0 | { |
5467 | 0 | mempool_t *mp; |
5468 | 0 | mp = (mempool_t*)calloc(1, sizeof(mempool_t)); |
5469 | 0 | return mp; |
5470 | 0 | } |
5471 | | static void mp_destroy(mempool_t *mp) |
5472 | 0 | { |
5473 | 0 | int k; |
5474 | 0 | for (k = 0; k < mp->n; ++k) { |
5475 | 0 | free(mp->buf[k]->b.data); |
5476 | 0 | free(mp->buf[k]); |
5477 | 0 | } |
5478 | 0 | free(mp->buf); |
5479 | 0 | free(mp); |
5480 | 0 | } |
5481 | | static inline lbnode_t *mp_alloc(mempool_t *mp) |
5482 | 0 | { |
5483 | 0 | ++mp->cnt; |
5484 | 0 | if (mp->n == 0) return (lbnode_t*)calloc(1, sizeof(lbnode_t)); |
5485 | 0 | else return mp->buf[--mp->n]; |
5486 | 0 | } |
5487 | | static inline void mp_free(mempool_t *mp, lbnode_t *p) |
5488 | 0 | { |
5489 | 0 | --mp->cnt; p->next = 0; // clear lbnode_t::next here |
5490 | 0 | if (mp->n == mp->max) { |
5491 | 0 | mp->max = mp->max? mp->max<<1 : 256; |
5492 | 0 | mp->buf = hts_realloc_p(mp->buf, sizeof(lbnode_t*), mp->max); |
5493 | 0 | } |
5494 | 0 | mp->buf[mp->n++] = p; |
5495 | 0 | } |
5496 | | |
5497 | | /********************** |
5498 | | *** CIGAR resolver *** |
5499 | | **********************/ |
5500 | | |
5501 | | // Lookup variables, so we can do "if (MEX & (1<<op))" instead of |
5502 | | // "if (op==BAM_CMATCH || op==BAM_CEQUAL || op==BAM_CDIFF)". |
5503 | | static const int MEX = (1<<BAM_CMATCH) | (1<<BAM_CEQUAL) | (1<<BAM_CDIFF); |
5504 | | static const int MEXDN = MEX | (1<<BAM_CDEL) | (1<<BAM_CREF_SKIP); |
5505 | | static const int IS = (1<<BAM_CINS) | (1<<BAM_CSOFT_CLIP); |
5506 | | |
5507 | | /* s->k: the index of the CIGAR operator that has just been processed. |
5508 | | s->x: the reference coordinate of the start of s->k |
5509 | | s->y: the query coordinate of the start of s->k |
5510 | | |
5511 | | Returns 1 on success |
5512 | | 0 on error |
5513 | | */ |
5514 | | static inline int resolve_cigar2(bam_pileup1_t *p, hts_pos_t pos, cstate_t *s) |
5515 | 0 | { |
5516 | 0 | #define _cop(c) ((c)&BAM_CIGAR_MASK) |
5517 | 0 | #define _cln(c) ((c)>>BAM_CIGAR_SHIFT) |
5518 | |
|
5519 | 0 | hts_pos_t indel; |
5520 | 0 | bam1_t *b = p->b; |
5521 | 0 | bam1_core_t *c = &b->core; |
5522 | 0 | uint32_t *cigar = bam_get_cigar(b); |
5523 | 0 | int k; |
5524 | | |
5525 | | // determine the current CIGAR operation |
5526 | | //fprintf(stderr, "%s\tpos=%ld\tend=%ld\t(%d,%ld,%ld)\n", bam_get_qname(b), pos, s->end, s->k, s->x, s->y); |
5527 | 0 | if (s->k == -1) { // never processed |
5528 | 0 | p->qpos = 0; |
5529 | 0 | if (c->n_cigar == 1 && (MEX & (1<<_cop(cigar[0])))) { |
5530 | | // just one M/=/X operation, save a loop |
5531 | 0 | s->k = 0, s->x = c->pos, s->y = 0; |
5532 | 0 | } else { // find the first reference base (match, mismatch or deletion) |
5533 | 0 | for (k = 0, s->x = c->pos, s->y = 0; k < c->n_cigar; ++k) { |
5534 | 0 | const int op = _cop(cigar[k]); |
5535 | 0 | if (bam_cigar_type(op) & 2) // consumes ref |
5536 | 0 | break; |
5537 | 0 | else if (bam_cigar_type(op) & 1) // consumes query |
5538 | 0 | s->y += _cln(cigar[k]); |
5539 | 0 | } |
5540 | 0 | assert(k < c->n_cigar); |
5541 | 0 | s->k = k; |
5542 | 0 | } |
5543 | |
|
5544 | 0 | } else { // the read has been processed before |
5545 | 0 | const int l = _cln(cigar[s->k]); |
5546 | 0 | if (pos - s->x >= l) { // jump to the next operation |
5547 | | // otherwise a bug: this function should not be called in this case |
5548 | 0 | assert(s->k+1 < c->n_cigar); |
5549 | | |
5550 | | // Update cstate_t ref and query positions for the next CIGAR op |
5551 | 0 | if (MEX & (1 << _cop(cigar[s->k]))) |
5552 | 0 | s->y += l; |
5553 | 0 | s->x += l; |
5554 | |
|
5555 | 0 | if (MEXDN & (1 << _cop(cigar[s->k+1]))) { // next op consumes ref |
5556 | | // jump to the next without a loop |
5557 | 0 | ++s->k; |
5558 | 0 | } else { // find the next M/D/N/=/X |
5559 | 0 | for (k = s->k + 1; k < c->n_cigar; ++k) { |
5560 | 0 | const int op = _cop(cigar[k]); |
5561 | 0 | if (MEXDN & (1 << op)) |
5562 | 0 | break; |
5563 | 0 | else if (IS & (1<<op)) |
5564 | 0 | s->y += _cln(cigar[k]); |
5565 | 0 | } |
5566 | 0 | s->k = k; |
5567 | 0 | } |
5568 | 0 | assert(s->k < c->n_cigar); // otherwise a bug |
5569 | 0 | } // else, do nothing |
5570 | 0 | } |
5571 | | |
5572 | | // collect pileup information |
5573 | 0 | { |
5574 | 0 | const int op = _cop(cigar[s->k]); |
5575 | 0 | const int l = _cln(cigar[s->k]); |
5576 | 0 | p->is_del = indel = p->is_refskip = 0; |
5577 | | |
5578 | | // peek the next operation |
5579 | 0 | if (s->x + l - 1 == pos && s->k + 1 < c->n_cigar) { |
5580 | 0 | const int op_next = _cop(cigar[s->k+1]); |
5581 | 0 | const int l_next = _cln(cigar[s->k+1]); |
5582 | 0 | if (op_next == BAM_CDEL && op != BAM_CDEL) { |
5583 | | // At start of a new deletion, merge e.g. 1D2D to 3D. |
5584 | | // Within a deletion (the 2D in 1D2D) we keep indel=0 |
5585 | | // and rely on is_del=1 as we would for 3D. |
5586 | 0 | indel = -l_next; |
5587 | 0 | for (k = s->k+2; k < c->n_cigar; ++k) { |
5588 | 0 | const int op2 = _cop(cigar[k]); |
5589 | 0 | if (op2 == BAM_CDEL) |
5590 | 0 | indel -= _cln(cigar[k]); |
5591 | 0 | else |
5592 | 0 | break; |
5593 | 0 | } |
5594 | 0 | } else if (op_next == BAM_CINS) { |
5595 | 0 | indel = l_next; |
5596 | 0 | for (k = s->k+2; k < c->n_cigar; ++k) { |
5597 | 0 | const int op2 = _cop(cigar[k]); |
5598 | 0 | if (op2 == BAM_CINS) |
5599 | 0 | indel += _cln(cigar[k]); |
5600 | 0 | else if (op2 != BAM_CPAD) |
5601 | 0 | break; |
5602 | 0 | } |
5603 | 0 | } else if (op_next == BAM_CPAD && s->k + 2 < c->n_cigar) { |
5604 | 0 | for (k = s->k + 2; k < c->n_cigar; ++k) { |
5605 | 0 | const int op2 = _cop(cigar[k]); |
5606 | 0 | if (op2 == BAM_CINS) |
5607 | 0 | indel += _cln(cigar[k]); |
5608 | 0 | else if (bam_cigar_type(op2) & 2) // consumes ref |
5609 | 0 | break; |
5610 | 0 | } |
5611 | 0 | } |
5612 | 0 | } |
5613 | 0 | if (MEX & (1<<op)) { |
5614 | | // Could overflow if pos - s->x pushes s->y from +ve to -ve. |
5615 | | // For this to happen we need over 2billion bases in our SEQ. |
5616 | | // We rely on b->core.l_qseq having been sanity checked first. |
5617 | 0 | p->qpos = s->y + (pos - s->x); |
5618 | 0 | } else if (op == BAM_CDEL || op == BAM_CREF_SKIP) { |
5619 | 0 | p->is_del = 1; // FIXME: distinguish D and N!!!!! |
5620 | 0 | p->qpos = s->y; |
5621 | 0 | p->is_refskip = (op == BAM_CREF_SKIP); |
5622 | 0 | } // cannot be other operations; otherwise a bug |
5623 | 0 | p->is_head = (pos == c->pos); |
5624 | 0 | p->is_tail = (pos == s->end); |
5625 | 0 | } |
5626 | 0 | p->cigar_ind = s->k; |
5627 | | |
5628 | | // Check for overflows and write our 64-bit values back to their 32-bit |
5629 | | // locations. |
5630 | 0 | int ret = 1; |
5631 | 0 | if (s->y > INT_MAX) |
5632 | 0 | ret = 0; |
5633 | |
|
5634 | 0 | if (indel >= INT_MIN && indel <= INT_MAX) |
5635 | 0 | p->indel = indel; |
5636 | 0 | else |
5637 | 0 | ret = 0; |
5638 | |
|
5639 | 0 | return ret; |
5640 | 0 | } |
5641 | | |
5642 | | /******************************* |
5643 | | *** Expansion of insertions *** |
5644 | | *******************************/ |
5645 | | |
5646 | | /* |
5647 | | * Fills out the kstring with the padded insertion sequence for the current |
5648 | | * location in 'p'. If this is not an insertion site, the string is blank. |
5649 | | * |
5650 | | * This variant handles base modifications, but only when "m" is non-NULL. |
5651 | | * |
5652 | | * Returns the number of inserted base on success, with string length being |
5653 | | * accessible via ins->l; |
5654 | | * -1 on failure. |
5655 | | */ |
5656 | | int bam_plp_insertion_mod(const bam_pileup1_t *p, |
5657 | | hts_base_mod_state *m, |
5658 | 0 | kstring_t *ins, int *del_len) { |
5659 | 0 | int j, k, indel, nb = 0; |
5660 | 0 | uint32_t *cigar; |
5661 | |
|
5662 | 0 | if (p->indel <= 0) { |
5663 | 0 | if (ks_resize(ins, 1) < 0) |
5664 | 0 | return -1; |
5665 | 0 | ins->l = 0; |
5666 | 0 | ins->s[0] = '\0'; |
5667 | 0 | return 0; |
5668 | 0 | } |
5669 | | |
5670 | 0 | if (del_len) |
5671 | 0 | *del_len = 0; |
5672 | | |
5673 | | // Measure indel length including pads |
5674 | 0 | indel = 0; |
5675 | 0 | k = p->cigar_ind+1; |
5676 | 0 | cigar = bam_get_cigar(p->b); |
5677 | 0 | while (k < p->b->core.n_cigar) { |
5678 | 0 | switch (cigar[k] & BAM_CIGAR_MASK) { |
5679 | 0 | case BAM_CPAD: |
5680 | 0 | case BAM_CINS: |
5681 | 0 | indel += (cigar[k] >> BAM_CIGAR_SHIFT); |
5682 | 0 | break; |
5683 | 0 | default: |
5684 | 0 | k = p->b->core.n_cigar; |
5685 | 0 | break; |
5686 | 0 | } |
5687 | 0 | k++; |
5688 | 0 | } |
5689 | 0 | nb = ins->l = indel; |
5690 | | |
5691 | | // Produce sequence |
5692 | 0 | if (ks_resize(ins, indel+1) < 0) |
5693 | 0 | return -1; |
5694 | 0 | indel = 0; |
5695 | 0 | k = p->cigar_ind+1; |
5696 | 0 | j = 1; |
5697 | 0 | while (k < p->b->core.n_cigar) { |
5698 | 0 | int l, c; |
5699 | 0 | switch (cigar[k] & BAM_CIGAR_MASK) { |
5700 | 0 | case BAM_CPAD: |
5701 | 0 | for (l = 0; l < (cigar[k]>>BAM_CIGAR_SHIFT); l++) |
5702 | 0 | ins->s[indel++] = '*'; |
5703 | 0 | break; |
5704 | 0 | case BAM_CINS: |
5705 | 0 | for (l = 0; l < (cigar[k]>>BAM_CIGAR_SHIFT); l++, j++) { |
5706 | 0 | c = p->qpos + j - p->is_del < p->b->core.l_qseq |
5707 | 0 | ? seq_nt16_str[bam_seqi(bam_get_seq(p->b), |
5708 | 0 | p->qpos + j - p->is_del)] |
5709 | 0 | : 'N'; |
5710 | 0 | ins->s[indel++] = c; |
5711 | 0 | int nm; |
5712 | 0 | hts_base_mod mod[256]; |
5713 | 0 | if (m && (nm = bam_mods_at_qpos(p->b, p->qpos + j - p->is_del, |
5714 | 0 | m, mod, 256)) > 0) { |
5715 | 0 | int o_indel = indel; |
5716 | 0 | if (ks_resize(ins, ins->l + nm*16+3) < 0) |
5717 | 0 | return -1; |
5718 | 0 | ins->s[indel++] = '['; |
5719 | 0 | int j; |
5720 | 0 | for (j = 0; j < nm; j++) { |
5721 | 0 | char qual[20]; |
5722 | 0 | if (mod[j].qual >= 0) |
5723 | 0 | snprintf(qual, sizeof(qual), "%d", mod[j].qual); |
5724 | 0 | else |
5725 | 0 | *qual=0; |
5726 | 0 | if (mod[j].modified_base < 0) |
5727 | | // ChEBI |
5728 | 0 | indel += snprintf(&ins->s[indel], ins->m - indel, |
5729 | 0 | "%c(%d)%s", |
5730 | 0 | "+-"[mod[j].strand], |
5731 | 0 | -mod[j].modified_base, |
5732 | 0 | qual); |
5733 | 0 | else |
5734 | 0 | indel += snprintf(&ins->s[indel], ins->m - indel, |
5735 | 0 | "%c%c%s", |
5736 | 0 | "+-"[mod[j].strand], |
5737 | 0 | mod[j].modified_base, |
5738 | 0 | qual); |
5739 | 0 | } |
5740 | 0 | ins->s[indel++] = ']'; |
5741 | 0 | ins->l += indel - o_indel; // grow by amount we used |
5742 | 0 | } |
5743 | 0 | } |
5744 | 0 | break; |
5745 | 0 | case BAM_CDEL: |
5746 | | // eg cigar 1M2I1D gives mpileup output in T+2AA-1C style |
5747 | 0 | if (del_len) { |
5748 | 0 | uint64_t len64 = cigar[k]>>BAM_CIGAR_SHIFT; |
5749 | 0 | while (k+1 < p->b->core.n_cigar && |
5750 | 0 | (cigar[k+1] & BAM_CIGAR_MASK) == BAM_CDEL) { |
5751 | 0 | len64 += cigar[++k] >> BAM_CIGAR_SHIFT; |
5752 | 0 | } |
5753 | 0 | if (len64 < INT32_MAX) |
5754 | 0 | *del_len = len64; |
5755 | 0 | else |
5756 | 0 | return -1; |
5757 | 0 | } |
5758 | | // fall through |
5759 | 0 | default: |
5760 | 0 | k = p->b->core.n_cigar; |
5761 | 0 | break; |
5762 | 0 | } |
5763 | 0 | k++; |
5764 | 0 | } |
5765 | 0 | ins->s[indel] = '\0'; |
5766 | 0 | ins->l = indel; // string length |
5767 | |
|
5768 | 0 | return nb; // base length |
5769 | 0 | } |
5770 | | |
5771 | | /* |
5772 | | * Fills out the kstring with the padded insertion sequence for the current |
5773 | | * location in 'p'. If this is not an insertion site, the string is blank. |
5774 | | * |
5775 | | * This is the original interface with no capability for reporting base |
5776 | | * modifications. |
5777 | | * |
5778 | | * Returns the length of insertion string on success; |
5779 | | * -1 on failure. |
5780 | | */ |
5781 | 0 | int bam_plp_insertion(const bam_pileup1_t *p, kstring_t *ins, int *del_len) { |
5782 | 0 | return bam_plp_insertion_mod(p, NULL, ins, del_len); |
5783 | 0 | } |
5784 | | |
5785 | | /*********************** |
5786 | | *** Pileup iterator *** |
5787 | | ***********************/ |
5788 | | |
5789 | | // Dictionary of overlapping reads |
5790 | 0 | KHASH_MAP_INIT_STR(olap_hash, lbnode_t *) |
5791 | 0 | typedef khash_t(olap_hash) olap_hash_t; |
5792 | 0 |
|
5793 | 0 | struct bam_plp_s { |
5794 | 0 | mempool_t *mp; |
5795 | 0 | lbnode_t *head, *tail; |
5796 | 0 | int32_t tid, max_tid; |
5797 | 0 | hts_pos_t pos, max_pos; |
5798 | 0 | int is_eof, max_plp, error, maxcnt; |
5799 | 0 | uint64_t id; |
5800 | 0 | bam_pileup1_t *plp; |
5801 | 0 | // for the "auto" interface only |
5802 | 0 | bam1_t *b; |
5803 | 0 | bam_plp_auto_f func; |
5804 | 0 | void *data; |
5805 | 0 | olap_hash_t *overlaps; |
5806 | 0 |
|
5807 | 0 | // For notification of creation and destruction events |
5808 | 0 | // and associated client-owned pointer. |
5809 | 0 | int (*plp_construct)(void *data, const bam1_t *b, bam_pileup_cd *cd); |
5810 | 0 | int (*plp_destruct )(void *data, const bam1_t *b, bam_pileup_cd *cd); |
5811 | 0 | }; |
5812 | 0 |
|
5813 | 0 | bam_plp_t bam_plp_init(bam_plp_auto_f func, void *data) |
5814 | 0 | { |
5815 | 0 | bam_plp_t iter; |
5816 | 0 | iter = (bam_plp_t)calloc(1, sizeof(struct bam_plp_s)); |
5817 | 0 | iter->mp = mp_init(); |
5818 | 0 | iter->head = iter->tail = mp_alloc(iter->mp); |
5819 | 0 | iter->max_tid = iter->max_pos = -1; |
5820 | 0 | iter->maxcnt = 8000; |
5821 | 0 | if (func) { |
5822 | 0 | iter->func = func; |
5823 | 0 | iter->data = data; |
5824 | 0 | iter->b = bam_init1(); |
5825 | 0 | } |
5826 | 0 | return iter; |
5827 | 0 | } |
5828 | | |
5829 | | int bam_plp_init_overlaps(bam_plp_t iter) |
5830 | 0 | { |
5831 | 0 | iter->overlaps = kh_init(olap_hash); // hash for tweaking quality of bases in overlapping reads |
5832 | 0 | return iter->overlaps ? 0 : -1; |
5833 | 0 | } |
5834 | | |
5835 | | void bam_plp_destroy(bam_plp_t iter) |
5836 | 0 | { |
5837 | 0 | lbnode_t *p, *pnext; |
5838 | 0 | if ( iter->overlaps ) kh_destroy(olap_hash, iter->overlaps); |
5839 | 0 | for (p = iter->head; p != NULL; p = pnext) { |
5840 | 0 | if (iter->plp_destruct && p != iter->tail) |
5841 | 0 | iter->plp_destruct(iter->data, &p->b, &p->cd); |
5842 | 0 | pnext = p->next; |
5843 | 0 | mp_free(iter->mp, p); |
5844 | 0 | } |
5845 | 0 | mp_destroy(iter->mp); |
5846 | 0 | if (iter->b) bam_destroy1(iter->b); |
5847 | 0 | free(iter->plp); |
5848 | 0 | free(iter); |
5849 | 0 | } |
5850 | | |
5851 | | void bam_plp_constructor(bam_plp_t plp, |
5852 | 0 | int (*func)(void *data, const bam1_t *b, bam_pileup_cd *cd)) { |
5853 | 0 | plp->plp_construct = func; |
5854 | 0 | } |
5855 | | |
5856 | | void bam_plp_destructor(bam_plp_t plp, |
5857 | 0 | int (*func)(void *data, const bam1_t *b, bam_pileup_cd *cd)) { |
5858 | 0 | plp->plp_destruct = func; |
5859 | 0 | } |
5860 | | |
5861 | | //--------------------------------- |
5862 | | //--- Tweak overlapping reads |
5863 | | //--------------------------------- |
5864 | | |
5865 | | /** |
5866 | | * cigar_iref2iseq_set() - find the first CMATCH setting the ref and the read index |
5867 | | * cigar_iref2iseq_next() - get the next CMATCH base |
5868 | | * @cigar: pointer to current cigar block (rw) |
5869 | | * @cigar_max: pointer just beyond the last cigar block |
5870 | | * @icig: position within the current cigar block (rw) |
5871 | | * @iseq: position in the sequence (rw) |
5872 | | * @iref: position with respect to the beginning of the read (iref_pos - b->core.pos) (rw) |
5873 | | * |
5874 | | * Returns BAM_CMATCH, -1 when there is no more cigar to process or the requested position is not covered, |
5875 | | * or -2 on error. |
5876 | | */ |
5877 | | static inline int cigar_iref2iseq_set(const uint32_t **cigar, |
5878 | | const uint32_t *cigar_max, |
5879 | | hts_pos_t *icig, |
5880 | | hts_pos_t *iseq, |
5881 | | hts_pos_t *iref) |
5882 | 0 | { |
5883 | 0 | hts_pos_t pos = *iref; |
5884 | 0 | if ( pos < 0 ) return -1; |
5885 | 0 | *icig = 0; |
5886 | 0 | *iseq = 0; |
5887 | 0 | *iref = 0; |
5888 | 0 | while ( *cigar<cigar_max ) |
5889 | 0 | { |
5890 | 0 | int cig = (**cigar) & BAM_CIGAR_MASK; |
5891 | 0 | int ncig = (**cigar) >> BAM_CIGAR_SHIFT; |
5892 | |
|
5893 | 0 | if ( cig==BAM_CSOFT_CLIP ) { (*cigar)++; *iseq += ncig; *icig = 0; continue; } |
5894 | 0 | if ( cig==BAM_CHARD_CLIP || cig==BAM_CPAD ) { (*cigar)++; *icig = 0; continue; } |
5895 | 0 | if ( cig==BAM_CMATCH || cig==BAM_CEQUAL || cig==BAM_CDIFF ) |
5896 | 0 | { |
5897 | 0 | pos -= ncig; |
5898 | 0 | if ( pos < 0 ) { *icig = ncig + pos; *iseq += *icig; *iref += *icig; return BAM_CMATCH; } |
5899 | 0 | (*cigar)++; *iseq += ncig; *icig = 0; *iref += ncig; |
5900 | 0 | continue; |
5901 | 0 | } |
5902 | 0 | if ( cig==BAM_CINS ) { (*cigar)++; *iseq += ncig; *icig = 0; continue; } |
5903 | 0 | if ( cig==BAM_CDEL || cig==BAM_CREF_SKIP ) |
5904 | 0 | { |
5905 | 0 | pos -= ncig; |
5906 | 0 | if ( pos<0 ) pos = 0; |
5907 | 0 | (*cigar)++; *icig = 0; *iref += ncig; |
5908 | 0 | continue; |
5909 | 0 | } |
5910 | 0 | hts_log_error("Unexpected cigar %d", cig); |
5911 | 0 | return -2; |
5912 | 0 | } |
5913 | 0 | *iseq = -1; |
5914 | 0 | return -1; |
5915 | 0 | } |
5916 | | static inline int cigar_iref2iseq_next(const uint32_t **cigar, |
5917 | | const uint32_t *cigar_max, |
5918 | | hts_pos_t *icig, |
5919 | | hts_pos_t *iseq, |
5920 | | hts_pos_t *iref) |
5921 | 0 | { |
5922 | 0 | while ( *cigar < cigar_max ) |
5923 | 0 | { |
5924 | 0 | int cig = (**cigar) & BAM_CIGAR_MASK; |
5925 | 0 | int ncig = (**cigar) >> BAM_CIGAR_SHIFT; |
5926 | |
|
5927 | 0 | if ( cig==BAM_CMATCH || cig==BAM_CEQUAL || cig==BAM_CDIFF ) |
5928 | 0 | { |
5929 | 0 | if ( *icig >= ncig - 1 ) { *icig = -1; (*cigar)++; continue; } |
5930 | 0 | (*iseq)++; (*icig)++; (*iref)++; |
5931 | 0 | return BAM_CMATCH; |
5932 | 0 | } |
5933 | 0 | if ( cig==BAM_CDEL || cig==BAM_CREF_SKIP ) { (*cigar)++; (*iref) += ncig; *icig = -1; continue; } |
5934 | 0 | if ( cig==BAM_CINS ) { (*cigar)++; *iseq += ncig; *icig = -1; continue; } |
5935 | 0 | if ( cig==BAM_CSOFT_CLIP ) { (*cigar)++; *iseq += ncig; *icig = -1; continue; } |
5936 | 0 | if ( cig==BAM_CHARD_CLIP || cig==BAM_CPAD ) { (*cigar)++; *icig = -1; continue; } |
5937 | 0 | hts_log_error("Unexpected cigar %d", cig); |
5938 | 0 | return -2; |
5939 | 0 | } |
5940 | 0 | *iseq = -1; |
5941 | 0 | *iref = -1; |
5942 | 0 | return -1; |
5943 | 0 | } |
5944 | | |
5945 | | // Given overlapping read 'a' (left) and 'b' (right) on the same |
5946 | | // template, adjust quality values to zero for either a or b. |
5947 | | // Note versions 1.12 and earlier always removed quality from 'b' for |
5948 | | // matching bases. Now we select a or b semi-randomly based on name hash. |
5949 | | // Returns 0 on success, |
5950 | | // -1 on failure |
5951 | | static int tweak_overlap_quality(bam1_t *a, bam1_t *b) |
5952 | 0 | { |
5953 | 0 | const uint32_t *a_cigar = bam_get_cigar(a), |
5954 | 0 | *a_cigar_max = a_cigar + a->core.n_cigar; |
5955 | 0 | const uint32_t *b_cigar = bam_get_cigar(b), |
5956 | 0 | *b_cigar_max = b_cigar + b->core.n_cigar; |
5957 | 0 | hts_pos_t a_icig = 0, a_iseq = 0; |
5958 | 0 | hts_pos_t b_icig = 0, b_iseq = 0; |
5959 | 0 | uint8_t *a_qual = bam_get_qual(a), *b_qual = bam_get_qual(b); |
5960 | 0 | uint8_t *a_seq = bam_get_seq(a), *b_seq = bam_get_seq(b); |
5961 | |
|
5962 | 0 | hts_pos_t iref = b->core.pos; |
5963 | 0 | hts_pos_t a_iref = iref - a->core.pos; |
5964 | 0 | hts_pos_t b_iref = iref - b->core.pos; |
5965 | |
|
5966 | 0 | int a_ret = cigar_iref2iseq_set(&a_cigar, a_cigar_max, |
5967 | 0 | &a_icig, &a_iseq, &a_iref); |
5968 | 0 | if ( a_ret<0 ) |
5969 | | // no overlap or error |
5970 | 0 | return a_ret<-1 ? -1:0; |
5971 | | |
5972 | 0 | int b_ret = cigar_iref2iseq_set(&b_cigar, b_cigar_max, |
5973 | 0 | &b_icig, &b_iseq, &b_iref); |
5974 | 0 | if ( b_ret<0 ) |
5975 | | // no overlap or error |
5976 | 0 | return b_ret<-1 ? -1:0; |
5977 | | |
5978 | | // Determine which seq is the one getting modified qualities. |
5979 | 0 | uint8_t amul, bmul; |
5980 | 0 | if (__ac_Wang_hash(__ac_X31_hash_string(bam_get_qname(a))) & 1) { |
5981 | 0 | amul = 1; |
5982 | 0 | bmul = 0; |
5983 | 0 | } else { |
5984 | 0 | amul = 0; |
5985 | 0 | bmul = 1; |
5986 | 0 | } |
5987 | | |
5988 | | // Loop over the overlapping region nulling qualities in either |
5989 | | // seq a or b. |
5990 | 0 | int err = 0; |
5991 | 0 | while ( 1 ) { |
5992 | | // Step to next matching reference position in a and b |
5993 | 0 | while ( a_ret >= 0 && a_iref>=0 && a_iref < iref - a->core.pos ) |
5994 | 0 | a_ret = cigar_iref2iseq_next(&a_cigar, a_cigar_max, |
5995 | 0 | &a_icig, &a_iseq, &a_iref); |
5996 | 0 | if ( a_ret<0 ) { // done |
5997 | 0 | err = a_ret<-1?-1:0; |
5998 | 0 | break; |
5999 | 0 | } |
6000 | | |
6001 | 0 | while ( b_ret >= 0 && b_iref>=0 && b_iref < iref - b->core.pos ) |
6002 | 0 | b_ret = cigar_iref2iseq_next(&b_cigar, b_cigar_max, &b_icig, |
6003 | 0 | &b_iseq, &b_iref); |
6004 | 0 | if ( b_ret<0 ) { // done |
6005 | 0 | err = b_ret<-1?-1:0; |
6006 | 0 | break; |
6007 | 0 | } |
6008 | | |
6009 | 0 | if ( iref < a_iref + a->core.pos ) |
6010 | 0 | iref = a_iref + a->core.pos; |
6011 | |
|
6012 | 0 | if ( iref < b_iref + b->core.pos ) |
6013 | 0 | iref = b_iref + b->core.pos; |
6014 | |
|
6015 | 0 | iref++; |
6016 | | |
6017 | | // If A or B has a deletion then we catch up the other to this point. |
6018 | | // We also amend quality values using the same rules for mismatch. |
6019 | 0 | if (a_iref+a->core.pos != b_iref+b->core.pos) { |
6020 | 0 | if (a_iref+a->core.pos < b_iref+b->core.pos |
6021 | 0 | && b_cigar > bam_get_cigar(b) |
6022 | 0 | && bam_cigar_op(b_cigar[-1]) == BAM_CDEL) { |
6023 | | // Del in B means it's moved on further than A |
6024 | 0 | while (a_iref + a->core.pos < b_iref+b->core.pos && |
6025 | 0 | a_iseq < a->core.l_qseq) { |
6026 | 0 | a_qual[a_iseq] = amul |
6027 | 0 | ? a_qual[a_iseq]*0.8 |
6028 | 0 | : 0; |
6029 | 0 | a_ret = cigar_iref2iseq_next(&a_cigar, a_cigar_max, |
6030 | 0 | &a_icig, &a_iseq, &a_iref); |
6031 | 0 | if (a_ret < 0) |
6032 | 0 | return -(a_ret<-1); // 0 or -1 |
6033 | 0 | } |
6034 | 0 | } else if (a_cigar > bam_get_cigar(a) |
6035 | 0 | && bam_cigar_op(a_cigar[-1]) == BAM_CDEL) { |
6036 | | // Del in A means it's moved on further than B |
6037 | 0 | while (b_iref + b->core.pos < a_iref+a->core.pos && |
6038 | 0 | b_iseq < b->core.l_qseq) { |
6039 | 0 | b_qual[b_iseq] = bmul |
6040 | 0 | ? b_qual[b_iseq]*0.8 |
6041 | 0 | : 0; |
6042 | 0 | b_ret = cigar_iref2iseq_next(&b_cigar, b_cigar_max, |
6043 | 0 | &b_icig, &b_iseq, &b_iref); |
6044 | 0 | if (b_ret < 0) |
6045 | 0 | return -(b_ret<-1); // 0 or -1 |
6046 | 0 | } |
6047 | 0 | } else { |
6048 | | // Anything else, eg ref-skip, we don't support here |
6049 | 0 | continue; |
6050 | 0 | } |
6051 | 0 | } |
6052 | | |
6053 | | // fprintf(stderr, "a_cig=%ld,%ld b_cig=%ld,%ld iref=%ld " |
6054 | | // "a_iref=%ld b_iref=%ld a_iseq=%ld b_iseq=%ld\n", |
6055 | | // a_cigar-bam_get_cigar(a), a_icig, |
6056 | | // b_cigar-bam_get_cigar(b), b_icig, |
6057 | | // iref, a_iref+a->core.pos+1, b_iref+b->core.pos+1, |
6058 | | // a_iseq, b_iseq); |
6059 | | |
6060 | 0 | if (a_iseq >= a->core.l_qseq || b_iseq >= b->core.l_qseq) |
6061 | | // Fell off end of sequence, bad CIGAR? |
6062 | 0 | return -1; |
6063 | | |
6064 | | // We're finally at the same ref base in both a and b. |
6065 | | // Check if the bases match (confident) or mismatch |
6066 | | // (not so confident). |
6067 | 0 | if ( bam_seqi(a_seq,a_iseq) == bam_seqi(b_seq,b_iseq) ) { |
6068 | | // We are very confident about this base. Use sum of quals |
6069 | 0 | int qual = a_qual[a_iseq] + b_qual[b_iseq]; |
6070 | 0 | a_qual[a_iseq] = amul * (qual>200 ? 200 : qual); |
6071 | 0 | b_qual[b_iseq] = bmul * (qual>200 ? 200 : qual);; |
6072 | 0 | } else { |
6073 | | // Not so confident about anymore given the mismatch. |
6074 | | // Reduce qual for lowest quality base. |
6075 | 0 | if ( a_qual[a_iseq] > b_qual[b_iseq] ) { |
6076 | | // A highest qual base; keep |
6077 | 0 | a_qual[a_iseq] = 0.8 * a_qual[a_iseq]; |
6078 | 0 | b_qual[b_iseq] = 0; |
6079 | 0 | } else if (a_qual[a_iseq] < b_qual[b_iseq] ) { |
6080 | | // B highest qual base; keep |
6081 | 0 | b_qual[b_iseq] = 0.8 * b_qual[b_iseq]; |
6082 | 0 | a_qual[a_iseq] = 0; |
6083 | 0 | } else { |
6084 | | // Both equal, so pick randomly |
6085 | 0 | a_qual[a_iseq] = amul * 0.8 * a_qual[a_iseq]; |
6086 | 0 | b_qual[b_iseq] = bmul * 0.8 * b_qual[b_iseq]; |
6087 | 0 | } |
6088 | 0 | } |
6089 | 0 | } |
6090 | | |
6091 | 0 | return err; |
6092 | 0 | } |
6093 | | |
6094 | | // Fix overlapping reads. Simple soft-clipping did not give good results. |
6095 | | // Lowering qualities of unwanted bases is more selective and works better. |
6096 | | // |
6097 | | // Returns 0 on success, -1 on failure |
6098 | | static int overlap_push(bam_plp_t iter, lbnode_t *node) |
6099 | 0 | { |
6100 | 0 | if ( !iter->overlaps ) return 0; |
6101 | | |
6102 | | // mapped mates and paired reads only |
6103 | 0 | if ( node->b.core.flag&BAM_FMUNMAP || !(node->b.core.flag&BAM_FPROPER_PAIR) ) return 0; |
6104 | | |
6105 | | // no overlap possible, unless some wild cigar |
6106 | 0 | if ( (node->b.core.mtid >= 0 && node->b.core.tid != node->b.core.mtid) |
6107 | 0 | || (llabs(node->b.core.isize) >= 2*node->b.core.l_qseq |
6108 | 0 | && node->b.core.mpos >= node->end) // for those wild cigars |
6109 | 0 | ) return 0; |
6110 | | |
6111 | 0 | khiter_t kitr = kh_get(olap_hash, iter->overlaps, bam_get_qname(&node->b)); |
6112 | 0 | if ( kitr==kh_end(iter->overlaps) ) |
6113 | 0 | { |
6114 | | // Only add reads where the mate is still to arrive |
6115 | 0 | if (node->b.core.mpos >= node->b.core.pos || |
6116 | 0 | ((node->b.core.flag & BAM_FPAIRED) && node->b.core.mpos == -1)) { |
6117 | 0 | int ret; |
6118 | 0 | kitr = kh_put(olap_hash, iter->overlaps, bam_get_qname(&node->b), &ret); |
6119 | 0 | if (ret < 0) return -1; |
6120 | 0 | kh_value(iter->overlaps, kitr) = node; |
6121 | 0 | } |
6122 | 0 | } |
6123 | 0 | else |
6124 | 0 | { |
6125 | 0 | lbnode_t *a = kh_value(iter->overlaps, kitr); |
6126 | 0 | int err = tweak_overlap_quality(&a->b, &node->b); |
6127 | 0 | kh_del(olap_hash, iter->overlaps, kitr); |
6128 | 0 | assert(a->end-1 == a->s.end); |
6129 | 0 | return err; |
6130 | 0 | } |
6131 | 0 | return 0; |
6132 | 0 | } |
6133 | | |
6134 | | static void overlap_remove(bam_plp_t iter, const bam1_t *b) |
6135 | 0 | { |
6136 | 0 | if ( !iter->overlaps ) return; |
6137 | | |
6138 | 0 | khiter_t kitr; |
6139 | 0 | if ( b ) |
6140 | 0 | { |
6141 | 0 | if ( b->core.flag&BAM_FUNMAP || !(b->core.flag&BAM_FPROPER_PAIR) ) //no need |
6142 | 0 | return; |
6143 | | |
6144 | 0 | kitr = kh_get(olap_hash, iter->overlaps, bam_get_qname(b)); |
6145 | 0 | if ( kitr!=kh_end(iter->overlaps) ) |
6146 | 0 | kh_del(olap_hash, iter->overlaps, kitr); |
6147 | 0 | } |
6148 | 0 | else |
6149 | 0 | { |
6150 | | // remove all |
6151 | 0 | for (kitr = kh_begin(iter->overlaps); kitr<kh_end(iter->overlaps); kitr++) |
6152 | 0 | if ( kh_exist(iter->overlaps, kitr) ) kh_del(olap_hash, iter->overlaps, kitr); |
6153 | 0 | } |
6154 | 0 | } |
6155 | | |
6156 | | |
6157 | | |
6158 | | // Prepares next pileup position in bam records collected by bam_plp_auto -> user func -> bam_plp_push. Returns |
6159 | | // pointer to the piled records if next position is ready or NULL if there is not enough records in the |
6160 | | // buffer yet (the current position is still the maximum position across all buffered reads). |
6161 | | const bam_pileup1_t *bam_plp64_next(bam_plp_t iter, int *_tid, hts_pos_t *_pos, int *_n_plp) |
6162 | 0 | { |
6163 | 0 | if (iter->error) { *_n_plp = -1; return NULL; } |
6164 | 0 | *_n_plp = 0; |
6165 | 0 | if (iter->is_eof && iter->head == iter->tail) return NULL; |
6166 | 0 | while (iter->is_eof || iter->max_tid > iter->tid || (iter->max_tid == iter->tid && iter->max_pos > iter->pos)) { |
6167 | 0 | int n_plp = 0; |
6168 | | // write iter->plp at iter->pos |
6169 | 0 | lbnode_t **pptr = &iter->head; |
6170 | 0 | while (*pptr != iter->tail) { |
6171 | 0 | if ((*pptr)->next) |
6172 | 0 | hts_prefetch((*pptr)->next); |
6173 | 0 | lbnode_t *p = *pptr; |
6174 | 0 | if (p->b.core.tid < iter->tid || (p->b.core.tid == iter->tid && p->end <= iter->pos)) { // then remove |
6175 | 0 | overlap_remove(iter, &p->b); |
6176 | 0 | if (iter->plp_destruct) |
6177 | 0 | iter->plp_destruct(iter->data, &p->b, &p->cd); |
6178 | 0 | *pptr = p->next; mp_free(iter->mp, p); |
6179 | 0 | } |
6180 | 0 | else { |
6181 | 0 | if (p->b.core.tid == iter->tid && p->beg <= iter->pos) { // here: p->end > pos; then add to pileup |
6182 | 0 | if (n_plp == iter->max_plp) { // then double the capacity |
6183 | 0 | iter->max_plp = iter->max_plp? iter->max_plp<<1 : 256; |
6184 | 0 | iter->plp = hts_realloc_p(iter->plp, sizeof(bam_pileup1_t), iter->max_plp); |
6185 | 0 | } |
6186 | 0 | iter->plp[n_plp].b = &p->b; |
6187 | 0 | iter->plp[n_plp].cd = p->cd; |
6188 | 0 | if (resolve_cigar2(iter->plp + n_plp, iter->pos, &p->s)) { |
6189 | 0 | ++n_plp; |
6190 | 0 | } else { |
6191 | 0 | hts_log_error("Excessive element size in CIGAR"); |
6192 | 0 | iter->error = 1; |
6193 | 0 | *_n_plp = -1; |
6194 | 0 | return NULL; |
6195 | 0 | } |
6196 | 0 | } |
6197 | 0 | pptr = &(*pptr)->next; |
6198 | 0 | } |
6199 | 0 | } |
6200 | 0 | *_n_plp = n_plp; *_tid = iter->tid; *_pos = iter->pos; |
6201 | | // update iter->tid and iter->pos |
6202 | 0 | if (iter->head != iter->tail) { |
6203 | 0 | if (iter->tid > iter->head->b.core.tid) { |
6204 | 0 | hts_log_error("Unsorted input. Pileup aborts"); |
6205 | 0 | iter->error = 1; |
6206 | 0 | *_n_plp = -1; |
6207 | 0 | return NULL; |
6208 | 0 | } |
6209 | 0 | } |
6210 | 0 | if (iter->tid < iter->head->b.core.tid) { // come to a new reference sequence |
6211 | 0 | iter->tid = iter->head->b.core.tid; iter->pos = iter->head->beg; // jump to the next reference |
6212 | 0 | } else if (iter->pos < iter->head->beg) { // here: tid == head->b.core.tid |
6213 | 0 | iter->pos = iter->head->beg; // jump to the next position |
6214 | 0 | } else ++iter->pos; // scan contiguously |
6215 | | // return |
6216 | 0 | if (n_plp) return iter->plp; |
6217 | 0 | if (iter->is_eof && iter->head == iter->tail) break; |
6218 | 0 | } |
6219 | 0 | return NULL; |
6220 | 0 | } |
6221 | | |
6222 | | const bam_pileup1_t *bam_plp_next(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp) |
6223 | 0 | { |
6224 | 0 | hts_pos_t pos64 = 0; |
6225 | 0 | const bam_pileup1_t *p = bam_plp64_next(iter, _tid, &pos64, _n_plp); |
6226 | 0 | if (pos64 < INT_MAX) { |
6227 | 0 | *_pos = pos64; |
6228 | 0 | } else { |
6229 | 0 | hts_log_error("Position %"PRId64" too large", pos64); |
6230 | 0 | *_pos = INT_MAX; |
6231 | 0 | iter->error = 1; |
6232 | 0 | *_n_plp = -1; |
6233 | 0 | return NULL; |
6234 | 0 | } |
6235 | 0 | return p; |
6236 | 0 | } |
6237 | | |
6238 | | int bam_plp_push(bam_plp_t iter, const bam1_t *b) |
6239 | 0 | { |
6240 | 0 | if (iter->error) return -1; |
6241 | 0 | if (b) { |
6242 | 0 | if (b->core.tid < 0) { overlap_remove(iter, b); return 0; } |
6243 | | // Skip only unmapped reads here, any additional filtering must be done in iter->func |
6244 | 0 | if (b->core.flag & BAM_FUNMAP) { overlap_remove(iter, b); return 0; } |
6245 | 0 | if (iter->tid == b->core.tid && iter->pos == b->core.pos && iter->mp->cnt > iter->maxcnt) |
6246 | 0 | { |
6247 | 0 | overlap_remove(iter, b); |
6248 | 0 | return 0; |
6249 | 0 | } |
6250 | 0 | if (bam_copy1(&iter->tail->b, b) == NULL) |
6251 | 0 | return -1; |
6252 | 0 | iter->tail->b.id = iter->id++; |
6253 | 0 | iter->tail->beg = b->core.pos; |
6254 | | // Use raw rlen rather than bam_endpos() which adjusts rlen=0 to rlen=1 |
6255 | 0 | iter->tail->end = b->core.pos + bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b)); |
6256 | 0 | iter->tail->s = g_cstate_null; iter->tail->s.end = iter->tail->end - 1; // initialize cstate_t |
6257 | 0 | if (b->core.tid < iter->max_tid) { |
6258 | 0 | hts_log_error("The input is not sorted (chromosomes out of order)"); |
6259 | 0 | iter->error = 1; |
6260 | 0 | return -1; |
6261 | 0 | } |
6262 | 0 | if ((b->core.tid == iter->max_tid) && (iter->tail->beg < iter->max_pos)) { |
6263 | 0 | hts_log_error("The input is not sorted (reads out of order)"); |
6264 | 0 | iter->error = 1; |
6265 | 0 | return -1; |
6266 | 0 | } |
6267 | 0 | iter->max_tid = b->core.tid; iter->max_pos = iter->tail->beg; |
6268 | 0 | if (iter->tail->end > iter->pos || iter->tail->b.core.tid > iter->tid) { |
6269 | 0 | lbnode_t *next = mp_alloc(iter->mp); |
6270 | 0 | if (!next) { |
6271 | 0 | iter->error = 1; |
6272 | 0 | return -1; |
6273 | 0 | } |
6274 | 0 | if (iter->plp_construct) { |
6275 | 0 | if (iter->plp_construct(iter->data, &iter->tail->b, |
6276 | 0 | &iter->tail->cd) < 0) { |
6277 | 0 | mp_free(iter->mp, next); |
6278 | 0 | iter->error = 1; |
6279 | 0 | return -1; |
6280 | 0 | } |
6281 | 0 | } |
6282 | 0 | if (overlap_push(iter, iter->tail) < 0) { |
6283 | 0 | mp_free(iter->mp, next); |
6284 | 0 | iter->error = 1; |
6285 | 0 | return -1; |
6286 | 0 | } |
6287 | 0 | iter->tail->next = next; |
6288 | 0 | iter->tail = iter->tail->next; |
6289 | 0 | } |
6290 | 0 | } else iter->is_eof = 1; |
6291 | 0 | return 0; |
6292 | 0 | } |
6293 | | |
6294 | | const bam_pileup1_t *bam_plp64_auto(bam_plp_t iter, int *_tid, hts_pos_t *_pos, int *_n_plp) |
6295 | 0 | { |
6296 | 0 | const bam_pileup1_t *plp; |
6297 | 0 | if (iter->func == 0 || iter->error) { *_n_plp = -1; return 0; } |
6298 | 0 | if ((plp = bam_plp64_next(iter, _tid, _pos, _n_plp)) != 0) return plp; |
6299 | 0 | else { // no pileup line can be obtained; read alignments |
6300 | 0 | *_n_plp = 0; |
6301 | 0 | if (iter->is_eof) return 0; |
6302 | 0 | int ret; |
6303 | 0 | while ( (ret=iter->func(iter->data, iter->b)) >= 0) { |
6304 | 0 | if (bam_plp_push(iter, iter->b) < 0) { |
6305 | 0 | *_n_plp = -1; |
6306 | 0 | return 0; |
6307 | 0 | } |
6308 | 0 | if ((plp = bam_plp64_next(iter, _tid, _pos, _n_plp)) != 0) return plp; |
6309 | | // otherwise no pileup line can be returned; read the next alignment. |
6310 | 0 | } |
6311 | 0 | if ( ret < -1 ) { iter->error = ret; *_n_plp = -1; return 0; } |
6312 | 0 | if (bam_plp_push(iter, 0) < 0) { |
6313 | 0 | *_n_plp = -1; |
6314 | 0 | return 0; |
6315 | 0 | } |
6316 | 0 | if ((plp = bam_plp64_next(iter, _tid, _pos, _n_plp)) != 0) return plp; |
6317 | 0 | return 0; |
6318 | 0 | } |
6319 | 0 | } |
6320 | | |
6321 | | const bam_pileup1_t *bam_plp_auto(bam_plp_t iter, int *_tid, int *_pos, int *_n_plp) |
6322 | 0 | { |
6323 | 0 | hts_pos_t pos64 = 0; |
6324 | 0 | const bam_pileup1_t *p = bam_plp64_auto(iter, _tid, &pos64, _n_plp); |
6325 | 0 | if (pos64 < INT_MAX) { |
6326 | 0 | *_pos = pos64; |
6327 | 0 | } else { |
6328 | 0 | hts_log_error("Position %"PRId64" too large", pos64); |
6329 | 0 | *_pos = INT_MAX; |
6330 | 0 | iter->error = 1; |
6331 | 0 | *_n_plp = -1; |
6332 | 0 | return NULL; |
6333 | 0 | } |
6334 | 0 | return p; |
6335 | 0 | } |
6336 | | |
6337 | | void bam_plp_reset(bam_plp_t iter) |
6338 | 0 | { |
6339 | 0 | overlap_remove(iter, NULL); |
6340 | 0 | iter->max_tid = iter->max_pos = -1; |
6341 | 0 | iter->tid = iter->pos = 0; |
6342 | 0 | iter->is_eof = 0; |
6343 | 0 | while (iter->head != iter->tail) { |
6344 | 0 | lbnode_t *p = iter->head; |
6345 | 0 | iter->head = p->next; |
6346 | 0 | mp_free(iter->mp, p); |
6347 | 0 | } |
6348 | 0 | } |
6349 | | |
6350 | | void bam_plp_set_maxcnt(bam_plp_t iter, int maxcnt) |
6351 | 0 | { |
6352 | 0 | iter->maxcnt = maxcnt; |
6353 | 0 | } |
6354 | | |
6355 | | /************************ |
6356 | | *** Mpileup iterator *** |
6357 | | ************************/ |
6358 | | |
6359 | | struct bam_mplp_s { |
6360 | | int n; |
6361 | | int32_t min_tid, *tid; |
6362 | | hts_pos_t min_pos, *pos; |
6363 | | bam_plp_t *iter; |
6364 | | int *n_plp; |
6365 | | const bam_pileup1_t **plp; |
6366 | | }; |
6367 | | |
6368 | | bam_mplp_t bam_mplp_init(int n, bam_plp_auto_f func, void **data) |
6369 | 0 | { |
6370 | 0 | int i; |
6371 | 0 | bam_mplp_t iter; |
6372 | 0 | iter = (bam_mplp_t)calloc(1, sizeof(struct bam_mplp_s)); |
6373 | 0 | iter->pos = (hts_pos_t*)calloc(n, sizeof(hts_pos_t)); |
6374 | 0 | iter->tid = (int32_t*)calloc(n, sizeof(int32_t)); |
6375 | 0 | iter->n_plp = (int*)calloc(n, sizeof(int)); |
6376 | 0 | iter->plp = (const bam_pileup1_t**)calloc(n, sizeof(bam_pileup1_t*)); |
6377 | 0 | iter->iter = (bam_plp_t*)calloc(n, sizeof(bam_plp_t)); |
6378 | 0 | iter->n = n; |
6379 | 0 | iter->min_pos = HTS_POS_MAX; |
6380 | 0 | iter->min_tid = (uint32_t)-1; |
6381 | 0 | for (i = 0; i < n; ++i) { |
6382 | 0 | iter->iter[i] = bam_plp_init(func, data[i]); |
6383 | 0 | iter->pos[i] = iter->min_pos; |
6384 | 0 | iter->tid[i] = iter->min_tid; |
6385 | 0 | } |
6386 | 0 | return iter; |
6387 | 0 | } |
6388 | | |
6389 | | int bam_mplp_init_overlaps(bam_mplp_t iter) |
6390 | 0 | { |
6391 | 0 | int i, r = 0; |
6392 | 0 | for (i = 0; i < iter->n; ++i) |
6393 | 0 | r |= bam_plp_init_overlaps(iter->iter[i]); |
6394 | 0 | return r == 0 ? 0 : -1; |
6395 | 0 | } |
6396 | | |
6397 | | void bam_mplp_set_maxcnt(bam_mplp_t iter, int maxcnt) |
6398 | 0 | { |
6399 | 0 | int i; |
6400 | 0 | for (i = 0; i < iter->n; ++i) |
6401 | 0 | iter->iter[i]->maxcnt = maxcnt; |
6402 | 0 | } |
6403 | | |
6404 | | void bam_mplp_destroy(bam_mplp_t iter) |
6405 | 0 | { |
6406 | 0 | int i; |
6407 | 0 | for (i = 0; i < iter->n; ++i) bam_plp_destroy(iter->iter[i]); |
6408 | 0 | free(iter->iter); free(iter->pos); free(iter->tid); |
6409 | 0 | free(iter->n_plp); free(iter->plp); |
6410 | 0 | free(iter); |
6411 | 0 | } |
6412 | | |
6413 | | int bam_mplp64_auto(bam_mplp_t iter, int *_tid, hts_pos_t *_pos, int *n_plp, const bam_pileup1_t **plp) |
6414 | 0 | { |
6415 | 0 | int i, ret = 0; |
6416 | 0 | hts_pos_t new_min_pos = HTS_POS_MAX; |
6417 | 0 | uint32_t new_min_tid = (uint32_t)-1; |
6418 | 0 | for (i = 0; i < iter->n; ++i) { |
6419 | 0 | if (iter->pos[i] == iter->min_pos && iter->tid[i] == iter->min_tid) { |
6420 | 0 | int tid; |
6421 | 0 | hts_pos_t pos; |
6422 | 0 | iter->plp[i] = bam_plp64_auto(iter->iter[i], &tid, &pos, &iter->n_plp[i]); |
6423 | 0 | if ( iter->iter[i]->error ) return -1; |
6424 | 0 | if (iter->plp[i]) { |
6425 | 0 | iter->tid[i] = tid; |
6426 | 0 | iter->pos[i] = pos; |
6427 | 0 | } else { |
6428 | 0 | iter->tid[i] = 0; |
6429 | 0 | iter->pos[i] = 0; |
6430 | 0 | } |
6431 | 0 | } |
6432 | 0 | if (iter->plp[i]) { |
6433 | 0 | if (iter->tid[i] < new_min_tid) { |
6434 | 0 | new_min_tid = iter->tid[i]; |
6435 | 0 | new_min_pos = iter->pos[i]; |
6436 | 0 | } else if (iter->tid[i] == new_min_tid && iter->pos[i] < new_min_pos) { |
6437 | 0 | new_min_pos = iter->pos[i]; |
6438 | 0 | } |
6439 | 0 | } |
6440 | 0 | } |
6441 | 0 | iter->min_pos = new_min_pos; |
6442 | 0 | iter->min_tid = new_min_tid; |
6443 | 0 | if (new_min_pos == HTS_POS_MAX) return 0; |
6444 | 0 | *_tid = new_min_tid; *_pos = new_min_pos; |
6445 | 0 | for (i = 0; i < iter->n; ++i) { |
6446 | 0 | if (iter->pos[i] == iter->min_pos && iter->tid[i] == iter->min_tid) { |
6447 | 0 | n_plp[i] = iter->n_plp[i], plp[i] = iter->plp[i]; |
6448 | 0 | ++ret; |
6449 | 0 | } else n_plp[i] = 0, plp[i] = 0; |
6450 | 0 | } |
6451 | 0 | return ret; |
6452 | 0 | } |
6453 | | |
6454 | | int bam_mplp_auto(bam_mplp_t iter, int *_tid, int *_pos, int *n_plp, const bam_pileup1_t **plp) |
6455 | 0 | { |
6456 | 0 | hts_pos_t pos64 = 0; |
6457 | 0 | int ret = bam_mplp64_auto(iter, _tid, &pos64, n_plp, plp); |
6458 | 0 | if (ret >= 0) { |
6459 | 0 | if (pos64 < INT_MAX) { |
6460 | 0 | *_pos = pos64; |
6461 | 0 | } else { |
6462 | 0 | hts_log_error("Position %"PRId64" too large", pos64); |
6463 | 0 | *_pos = INT_MAX; |
6464 | 0 | return -1; |
6465 | 0 | } |
6466 | 0 | } |
6467 | 0 | return ret; |
6468 | 0 | } |
6469 | | |
6470 | | void bam_mplp_reset(bam_mplp_t iter) |
6471 | 0 | { |
6472 | 0 | int i; |
6473 | 0 | iter->min_pos = HTS_POS_MAX; |
6474 | 0 | iter->min_tid = (uint32_t)-1; |
6475 | 0 | for (i = 0; i < iter->n; ++i) { |
6476 | 0 | bam_plp_reset(iter->iter[i]); |
6477 | 0 | iter->pos[i] = HTS_POS_MAX; |
6478 | 0 | iter->tid[i] = (uint32_t)-1; |
6479 | 0 | iter->n_plp[i] = 0; |
6480 | 0 | iter->plp[i] = NULL; |
6481 | 0 | } |
6482 | 0 | } |
6483 | | |
6484 | | void bam_mplp_constructor(bam_mplp_t iter, |
6485 | 0 | int (*func)(void *arg, const bam1_t *b, bam_pileup_cd *cd)) { |
6486 | 0 | int i; |
6487 | 0 | for (i = 0; i < iter->n; ++i) |
6488 | 0 | bam_plp_constructor(iter->iter[i], func); |
6489 | 0 | } |
6490 | | |
6491 | | void bam_mplp_destructor(bam_mplp_t iter, |
6492 | 0 | int (*func)(void *arg, const bam1_t *b, bam_pileup_cd *cd)) { |
6493 | 0 | int i; |
6494 | 0 | for (i = 0; i < iter->n; ++i) |
6495 | 0 | bam_plp_destructor(iter->iter[i], func); |
6496 | 0 | } |
6497 | | |
6498 | | #endif // ~!defined(BAM_NO_PILEUP) |