Debian Codegraph @

samtools/tmp_file.c.pysam.c

raw symbols SCIP
1 #include "samtools.pysam.h"
2
3 /*
4 tmp_file.c - write to and read from a temporary binary file
5 for fast storage plus added compression.
6
7 Copyright (C) 2017, 2018 Genome Research Ltd.
8
9 Author: Andrew Whitwham <[email protected]>
10
11 Permission is hereby granted, free of charge, to any person obtaining a copy
12 of this software and associated documentation files (the "Software"), to deal
13 in the Software without restriction, including without limitation the rights
14 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 copies of the Software, and to permit persons to whom the Software is
16 furnished to do so, subject to the following conditions:
17
18 The above copyright notice and this permission notice shall be included in
19 all copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 DEALINGS IN THE SOFTWARE
28 */
29
30 #include <config.h>
31
32 #include <stdio.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <stdarg.h>
37 #include <fcntl.h>
38 #include <errno.h>
39
40 #ifdef _WIN32
41 #include <windows.h>
42 #endif /* _WIN32 */
43
44 #include "tmp_file.h"
45 #include "htslib/sam.h"
46
47
48 static void HTS_FORMAT(HTS_PRINTF_FMT, 2, 3)
49 tmp_print_error(tmp_file_t *tmp, const char *fmt, ...) {
50 va_list argp;
51
52 if (tmp->verbose) {
53 va_start(argp, fmt);
54 vfprintf(samtools_stderr, fmt, argp);
55 va_end(argp);
56 }
57 }
58
59
60 static int tmp_file_init(tmp_file_t *tmp, int verbose) {
61 tmp->stream = LZ4_createStream();
62 tmp->data_size = 0;
63 tmp->group_size = TMP_SAM_GROUP_SIZE;
64 tmp->input_size = 0;
65 tmp->read_size = 0;
66 tmp->output_size = 0;
67 tmp->entry_number = 0;
68 tmp->offset = 0;
69 tmp->max_data_size = TMP_SAM_MAX_DATA + sizeof(bam1_t); // arbitrary but growable
70 tmp->ring_buffer_size = TMP_SAM_RING_SIZE; // arbitrary (min 64K) but growable
71 tmp->comp_buffer_size = LZ4_COMPRESSBOUND(tmp->max_data_size * tmp->group_size);
72 tmp->ring_buffer = malloc(sizeof(uint8_t) * tmp->ring_buffer_size);
73 tmp->ring_index = tmp->ring_buffer;
74 tmp->comp_buffer = malloc(tmp->comp_buffer_size);
75 tmp->verbose = verbose;
76 tmp->dict = NULL;
77 tmp->groups_written = 0;
78
79 if (!tmp->ring_buffer || !tmp->comp_buffer || !tmp->stream) {
80 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate compression buffers.\n");
81 return TMP_SAM_MEM_ERROR;
82 }
83
84 return TMP_SAM_OK;
85 }
86
87
88 /*
89 * Opens the temp file and initialises memory.
90 * Verbose mode prints out error messages to samtools_stderr.
91 * Returns 0 on success, a negative number on failure.
92 */
93 int tmp_file_open_write(tmp_file_t *tmp, char *tmp_name, int verbose) {
94 int ret;
95 unsigned int count = 1;
96 const unsigned int max_count = 100000; // more tries than this then something else is wrong
97 int fd;
98
99 if ((ret = tmp_file_init(tmp, verbose))) {
100 return ret;
101 }
102
103 // make space to write extended file name
104 if ((tmp->name = malloc(strlen(tmp_name) + 7)) == NULL) {
105 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate memory for %s.\n", tmp_name);
106 return TMP_SAM_MEM_ERROR;
107 }
108
109 // make sure temp file has a unique name
110 while (count < max_count) {
111 sprintf(tmp->name, "%s.%d", tmp_name, count);
112
113
114 #ifdef _WIN32
115 if ((fd = _open(tmp->name, O_RDWR|O_CREAT|O_EXCL|O_BINARY|O_TEMPORARY, 0600)) == -1) {
116 #else
117 if ((fd = open(tmp->name, O_RDWR|O_CREAT|O_EXCL, 0600)) == -1) {
118 #endif /* _WIN32 */
119
120 if (errno != EEXIST) {
121 tmp_print_error(tmp, "[tmp_file] Error: unable to create tmp file %s.\n", tmp->name);
122 return TMP_SAM_FILE_ERROR;
123 }
124
125 count++;
126 continue;
127 }
128
129 break;
130 }
131
132 if (count >= max_count) {
133 tmp_print_error(tmp, "[tmp_file] Error: unable to create unique temp file.\n");
134 return TMP_SAM_FILE_ERROR;
135 }
136
137 if ((tmp->fp = fdopen(fd, "w+b")) == NULL) {
138 tmp_print_error(tmp, "[tmp_file] Error: unable to open write file %s.\n", tmp->name);
139 return TMP_SAM_FILE_ERROR;
140 }
141
142 #ifndef _WIN32
143 unlink(tmp->name); // should auto delete when closed on linux
144 #endif
145
146 return TMP_SAM_OK;
147 }
148
149
150 /*
151 * The ring buffer stores precompressionn/post decompression data. LZ4 requires that
152 * previous data (64K worth) be available for efficient compression. This function grows
153 * the ring buffer when needed.
154 * Returns 0 on success, a negative number on failure.
155 */
156 static int tmp_file_grow_ring_buffer(tmp_file_t *tmp, size_t new_size) {
157 // save the dictionary so lz4 can continue to function
158 int dict_size = 64 * 1024; // 64K max size
159
160 if (tmp->groups_written) {
161 // if compression has been done then there is a dictionary to save
162
163 if (tmp->dict == NULL) {
164
165 if ((tmp->dict = malloc(sizeof(char) * dict_size)) == NULL) {
166 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate memory for compression dictionary.\n");
167 return TMP_SAM_MEM_ERROR;
168 }
169 }
170
171 if (LZ4_saveDict(tmp->stream, tmp->dict, dict_size) == 0) {
172 tmp_print_error(tmp, "[tmp_file] Error: unable to save compression dictionary.\n");
173 return TMP_SAM_LZ4_ERROR;
174 }
175 }
176
177 if ((tmp->ring_buffer = realloc(tmp->ring_buffer, sizeof(char) * new_size)) == NULL) {
178 tmp_print_error(tmp, "[tmp_file] Error: unable to reallocate ring buffer.\n");
179 return TMP_SAM_MEM_ERROR;
180 }
181
182 tmp->ring_buffer_size = new_size;
183
184 return TMP_SAM_OK;
185 }
186
187
188 /*
189 * This does the actual compression and writing to a file. The file format consists of a
190 * single size_t for the size of the compressed data followed by the data itself.
191 * Returns 0 on success, a negative number on failure.
192 */
193 static int tmp_file_write_to_file(tmp_file_t *tmp) {
194 size_t comp_size;
195
196 if (tmp->input_size > tmp->max_data_size) {
197 tmp->max_data_size += tmp->input_size + sizeof(bam1_t);
198 tmp->comp_buffer_size = LZ4_COMPRESSBOUND(tmp->max_data_size);
199
200 if ((tmp->comp_buffer = realloc(tmp->comp_buffer, sizeof(char) * tmp->comp_buffer_size)) == NULL) {
201 tmp_print_error(tmp, "[tmp_file] Error: unable to reallocate compression buffer.\n");
202 return TMP_SAM_MEM_ERROR;
203 }
204
205 // make sure the ring buffer is big enough to accommodate the new max_data_size
206 if (tmp->ring_buffer_size < tmp->max_data_size * 5) {
207 int ret;
208 if ((ret = tmp_file_grow_ring_buffer(tmp, tmp->max_data_size * 5))) {
209 return ret;
210 }
211 }
212 }
213
214 tmp->ring_index = tmp->ring_buffer + tmp->offset;
215
216 comp_size = LZ4_compress_fast_continue(tmp->stream, (const char *)tmp->ring_index,
217 tmp->comp_buffer, tmp->input_size, tmp->comp_buffer_size, 1);
218
219 if (comp_size == 0) {
220 tmp_print_error(tmp, "[tmp_file] Error: compression failed.\n");
221 return TMP_SAM_LZ4_ERROR;
222 }
223
224 if (fwrite(&comp_size, sizeof(size_t), 1, tmp->fp) < 1) {
225 tmp_print_error(tmp, "[tmp_file] Error: tmp file write size failed.\n");
226 return TMP_SAM_FILE_ERROR;
227 }
228
229 if (fwrite(tmp->comp_buffer, sizeof(char), comp_size, tmp->fp) < comp_size) {
230 tmp_print_error(tmp, "[tmp_file] Error: tmp file write data failed.\n");
231 return TMP_SAM_FILE_ERROR;
232 }
233
234 tmp->offset += tmp->input_size;
235
236 if (tmp->offset >= tmp->ring_buffer_size - tmp->max_data_size)
237 tmp->offset = 0;
238
239 tmp->input_size = 0;
240 tmp->entry_number = 0;
241 tmp->groups_written++;
242
243 return TMP_SAM_OK;
244 }
245
246
247 /*
248 * Stores an in memory bam structure for writing and if enough are gathered together writes
249 * it to a file. Multiple alignments compress better that single ones though after a certain number
250 * there is a law of diminishing returns.
251 * Returns 0 on success, a negative number on failure.
252 */
253 int tmp_file_write(tmp_file_t *tmp, bam1_t *inbam) {
254
255 if ((tmp->offset + tmp->input_size + sizeof(bam1_t) + inbam->l_data) >= tmp->ring_buffer_size) {
256 int ret;
257
258 if ((ret = tmp_file_grow_ring_buffer(tmp, (tmp->offset + tmp->input_size + sizeof(bam1_t) + inbam->l_data) * 2))) {
259 tmp_print_error(tmp, "[tmp_file] Error: input line too big. (%zu).\n",
260 (tmp->input_size + inbam->l_data));
261
262 return ret;
263 }
264 }
265
266 tmp->ring_index = tmp->ring_buffer + tmp->offset + tmp->input_size;
267
268 // copy data into the ring buffer
269 memcpy(tmp->ring_index, inbam, sizeof(bam1_t));
270 memcpy(tmp->ring_index + sizeof(bam1_t) , inbam->data, inbam->l_data);
271 tmp->input_size += sizeof(bam1_t) + inbam->l_data;
272 tmp->entry_number++;
273
274 if (tmp->entry_number == tmp->group_size) {
275 // actually write out the data
276 int ret;
277
278 if ((ret = tmp_file_write_to_file(tmp))) {
279 return ret;
280 }
281 }
282
283 return TMP_SAM_OK;
284 }
285
286
287 /*
288 * Marks the end of file writing. Adds a size_t 0 to mark the end of
289 * the file. Companion function to tmp_file_begin_read below.
290 * Returns 0 on success, a negative number on failure.
291 */
292 int tmp_file_end_write(tmp_file_t *tmp) {
293 size_t terminator = 0;
294
295 if (tmp->entry_number) {
296 int ret;
297
298 if ((ret = tmp_file_write_to_file(tmp))) {
299 return ret;
300 }
301 }
302
303 if (fwrite(&terminator, sizeof(size_t), 1, tmp->fp) < 1) {
304 tmp_print_error(tmp, "[tmp_file] Error: tmp file write terminator failed.\n");
305 return TMP_SAM_FILE_ERROR;
306 }
307
308 fflush(tmp->fp);
309
310 LZ4_freeStream(tmp->stream);
311
312 return TMP_SAM_OK;
313 }
314
315
316 /*
317 * Prepares the file for reading.
318 * Companion function to tmp_file_end_write above.
319 * Returns 0 on success, a negative number on failure.
320 */
321 int tmp_file_begin_read(tmp_file_t *tmp) {
322
323 rewind(tmp->fp);
324
325 tmp->dstream = LZ4_createStreamDecode();
326 tmp->offset = 0;
327 tmp->entry_number = tmp->group_size;
328
329 if (!tmp->dstream) {
330 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate compression stream.\n");
331 return TMP_SAM_MEM_ERROR;
332 }
333
334 return TMP_SAM_OK;
335 }
336
337
338 /*
339 * Read the next alignment, either from memory or from a file.
340 * Returns size of entry on success, 0 on end of file or a negative on error.
341 */
342 int tmp_file_read(tmp_file_t *tmp, bam1_t *inbam) {
343 int entry_size;
344 uint8_t *data = inbam->data;
345
346 /* while tmp_file_read assumes that the same bam1_t variable
347 is being used in each call, this may not be the case. So
348 default to the lowest memory size for safety. */
349 if (tmp->data_size > inbam->m_data) {
350 tmp->data_size = inbam->m_data;
351 }
352
353 if (tmp->entry_number == tmp->group_size) {
354 // read more data
355 size_t comp_size;
356
357 if (fread(&comp_size, sizeof(size_t), 1, tmp->fp) == 0 || comp_size == 0) {
358 return TMP_SAM_OK;
359 }
360
361 if (tmp->offset >= tmp->ring_buffer_size - tmp->max_data_size)
362 tmp->offset = 0;
363
364 tmp->ring_index = tmp->ring_buffer + tmp->offset;
365
366 if (fread(tmp->comp_buffer, sizeof(char), comp_size, tmp->fp) > comp_size) {
367 tmp_print_error(tmp, "[tmp_file] Error: error reading compressed data.\n");
368 return TMP_SAM_FILE_ERROR;
369 }
370
371 tmp->output_size = LZ4_decompress_safe_continue(tmp->dstream, tmp->comp_buffer,
372 (char *)tmp->ring_index, comp_size, tmp->max_data_size);
373
374 if (tmp->output_size == 0) {
375 tmp_print_error(tmp, "[tmp_file] Error: decompression failed.\n");
376 return TMP_SAM_LZ4_ERROR;
377 }
378
379 tmp->entry_number = 0;
380 tmp->read_size = 0;
381 }
382
383 tmp->ring_index = tmp->ring_buffer + tmp->offset;
384 memcpy(inbam, tmp->ring_index, sizeof(bam1_t));
385 inbam->data = data; // put the pointer to real bam data back
386
387 if ((unsigned int)inbam->l_data > tmp->data_size) {
388 uint8_t *tmp_data;
389 tmp->data_size = inbam->l_data; kroundup32(tmp->data_size);
390
391 if ((tmp_data = realloc(inbam->data, sizeof(uint8_t) * tmp->data_size)) == NULL) {
392 tmp_print_error(tmp, "[tmp_file] Error: unable to allocate tmp bam data memory.\n");
393 return TMP_SAM_MEM_ERROR;
394 }
395
396 inbam->data = tmp_data;
397 }
398
399 inbam->m_data = tmp->data_size; // set to the actual data size
400
401 entry_size = sizeof(bam1_t);
402
403 memcpy(inbam->data, tmp->ring_index + entry_size, inbam->l_data);
404 entry_size += inbam->l_data;
405
406 tmp->offset += entry_size;
407 tmp->read_size += entry_size;
408 tmp->entry_number++;
409
410 if (tmp->read_size > tmp->output_size) {
411 tmp_print_error(tmp, "[tmp_file] Error: wrong size of data returned RS:%zu OS:%zu EN:%zu GS:%zu.\n",
412 tmp->read_size, tmp->output_size, tmp->entry_number, tmp->group_size);
413 return TMP_SAM_LZ4_ERROR;
414 }
415
416 if (tmp->read_size == tmp->output_size && tmp->entry_number != tmp->group_size) {
417 // hopefully the last entries in the read file
418 tmp->entry_number = tmp->group_size;
419 }
420
421 return entry_size;
422 }
423
424
425 /*
426 * Frees up memory, closes the file and deletes it.
427 * Returns 0 on success or EOF on failure.
428 */
429 int tmp_file_destroy(tmp_file_t *tmp) {
430 int ret = 0;
431
432 ret = fclose(tmp->fp);
433
434 LZ4_freeStreamDecode(tmp->dstream);
435 free(tmp->ring_buffer);
436 free(tmp->comp_buffer);
437 free(tmp->name);
438 free(tmp->dict);
439
440 return ret;
441 }