1 /*
2     This file is part of BioD.
3     Copyright (C) 2012-2016    Artem Tarasov <lomereiter@gmail.com>
4 
5     Permission is hereby granted, free of charge, to any person obtaining a
6     copy of this software and associated documentation files (the "Software"),
7     to deal in the Software without restriction, including without limitation
8     the rights to use, copy, modify, merge, publish, distribute, sublicense,
9     and/or sell copies of the Software, and to permit persons to whom the
10     Software is furnished to do so, subject to the following conditions:
11 
12     The above copyright notice and this permission notice shall be included in
13     all copies or substantial portions of the Software.
14 
15     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20     FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21     DEALINGS IN THE SOFTWARE.
22 
23 */
24 module bio.core.bgzf.compress;
25 
26 import bio.std.hts.bam.constants;
27 import bio.core.utils.zlib;
28 
29 import std.array;
30 import std.system;
31 import std.bitmanip: nativeToLittleEndian;
32 
33 /// Returns BGZF block containing compressed $(D chunk).
34 /// If $(D buffer) is provided, it will be used for storing the block.
35 ///
36 /// Params:
37 ///         chunk =  chunk of memory to be compressed
38 ///         level =  compression level, see zlib documentation (https://github.com/madler/zlib/blob/master/zlib.h)
39 ///         buffer = optional buffer which will be used for storing
40 ///                  decompressed data
41 ///
42 /// For uncompressed BAM output, use level = 0.
43 ubyte[] bgzfCompress(ubyte[] chunk, int level=-1, ubyte[] buffer=null)
44 in
45 {
46     assert(-1 <= level && level <= 9);
47 }
48 body
49 {
50     assert(bio.core.utils.zlib.compressBound(BGZF_BLOCK_SIZE) < BGZF_MAX_BLOCK_SIZE);
51 
52     if (buffer is null) {
53         buffer = uninitializedArray!(ubyte[])(BGZF_MAX_BLOCK_SIZE);
54     } else {
55         buffer.length = BGZF_MAX_BLOCK_SIZE;
56     }
57 
58     // write header
59     buffer[0 .. BLOCK_HEADER_LENGTH - ushort.sizeof] = BLOCK_HEADER_START[];
60 
61     bio.core.utils.zlib.z_stream zs;
62 
63     zs.zalloc = null;
64     zs.zfree = null;
65 
66     zs.next_in  = cast(ubyte*)chunk.ptr;
67     zs.avail_in = cast(uint)chunk.length;
68 
69     zs.next_out = buffer.ptr + BLOCK_HEADER_LENGTH;
70     zs.avail_out = cast(int)(buffer.length - BLOCK_HEADER_LENGTH - BLOCK_FOOTER_LENGTH);
71 
72     auto err = bio.core.utils.zlib.deflateInit2(&zs, /* compression level */ level,
73                                             /* deflated compression method */ Z_DEFLATED,
74                                             /* winbits (no header) */ -15,
75                                             /* memory usage level (default) */ 8,
76                                             /* default compression strategy */ Z_DEFAULT_STRATEGY);
77     if (err != Z_OK) {
78         throw new ZlibException("deflateInit2", err);
79     }
80 
81     err = bio.core.utils.zlib.deflate(&zs, Z_FINISH);
82     if (err != Z_STREAM_END) {
83         throw new ZlibException("deflate", err);
84     }
85 
86     err = bio.core.utils.zlib.deflateEnd(&zs);
87     if (err != Z_OK) {
88         throw new ZlibException("deflateEnd", err);
89     }
90 
91     // almost done, update buffer length
92     buffer.length = zs.total_out + BLOCK_HEADER_LENGTH + BLOCK_FOOTER_LENGTH;
93 
94     // Write (block length - 1) in BC subfield.
95     // Why -1? To fit the value into 2 bytes (it's assumed to be in range 1-65536).
96     ushort len = cast(ushort)(buffer.length - 1);
97     buffer[BLOCK_HEADER_LENGTH - 2 .. $][0 .. 2] = nativeToLittleEndian(len);
98 
99     // Write the footer
100     buffer[$ - 8 .. $ - 4] = nativeToLittleEndian(crc32(0, chunk));
101     buffer[$- 4 .. $] = nativeToLittleEndian(cast(uint)chunk.length);
102     return buffer;
103 }