]> git.donarmstrong.com Git - bamtools.git/blob - src/api/internal/BgzfStream_p.cpp
Cleaned up intra-API includes & moved version numbers to 2.0.0
[bamtools.git] / src / api / internal / BgzfStream_p.cpp
1 // ***************************************************************************
2 // BgzfStream_p.cpp (c) 2011 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 10 October 2011(DB)
6 // ---------------------------------------------------------------------------
7 // Based on BGZF routines developed at the Broad Institute.
8 // Provides the basic functionality for reading & writing BGZF files
9 // Replaces the old BGZF.* files to avoid clashing with other toolkits
10 // ***************************************************************************
11
12 #include "api/BamAux.h"
13 #include "api/BamConstants.h"
14 #include "api/internal/BamDeviceFactory_p.h"
15 #include "api/internal/BamException_p.h"
16 #include "api/internal/BgzfStream_p.h"
17 using namespace BamTools;
18 using namespace BamTools::Internal;
19
20 #include "zlib.h"
21
22 #include <cstring>
23 #include <algorithm>
24 #include <iostream>
25 #include <sstream>
26 using namespace std;
27
28 // ----------------------------
29 // RaiiWrapper implementation
30 // ----------------------------
31
32 BgzfStream::RaiiWrapper::RaiiWrapper(void) {
33     CompressedBlock   = new char[Constants::BGZF_MAX_BLOCK_SIZE];
34     UncompressedBlock = new char[Constants::BGZF_DEFAULT_BLOCK_SIZE];
35 }
36
37 BgzfStream::RaiiWrapper::~RaiiWrapper(void) {
38
39     // clean up buffers
40     delete[] CompressedBlock;
41     delete[] UncompressedBlock;
42     CompressedBlock = 0;
43     UncompressedBlock = 0;
44 }
45
46 // ---------------------------
47 // BgzfStream implementation
48 // ---------------------------
49
50 // constructor
51 BgzfStream::BgzfStream(void)
52   : m_blockLength(0)
53   , m_blockOffset(0)
54   , m_blockAddress(0)
55   , m_isWriteCompressed(true)
56   , m_device(0)
57 { }
58
59 // destructor
60 BgzfStream::~BgzfStream(void) {
61     Close();
62 }
63
64 // checks BGZF block header
65 bool BgzfStream::CheckBlockHeader(char* header) {
66     return (header[0] == Constants::GZIP_ID1 &&
67             header[1] == Constants::GZIP_ID2 &&
68             header[2] == Z_DEFLATED &&
69             (header[3] & Constants::FLG_FEXTRA) != 0 &&
70             BamTools::UnpackUnsignedShort(&header[10]) == Constants::BGZF_XLEN &&
71             header[12] == Constants::BGZF_ID1 &&
72             header[13] == Constants::BGZF_ID2 &&
73             BamTools::UnpackUnsignedShort(&header[14]) == Constants::BGZF_LEN );
74 }
75
76 // closes BGZF file
77 void BgzfStream::Close(void) {
78
79     // reset state
80     m_blockLength = 0;
81     m_blockOffset = 0;
82     m_blockAddress = 0;
83     m_isWriteCompressed = true;
84
85     // skip if no device open
86     if ( m_device == 0 ) return;
87
88     // if writing to file, flush the current BGZF block,
89     // then write an empty block (as EOF marker)
90     if ( m_device->IsOpen() && (m_device->Mode() == IBamIODevice::WriteOnly) ) {
91         FlushBlock();
92         const size_t blockLength = DeflateBlock();
93         m_device->Write(Resources.CompressedBlock, blockLength);
94     }
95
96     // close device
97     m_device->Close();
98     delete m_device;
99     m_device = 0;
100 }
101
102 // compresses the current block
103 size_t BgzfStream::DeflateBlock(void) {
104
105     // initialize the gzip header
106     char* buffer = Resources.CompressedBlock;
107     memset(buffer, 0, 18);
108     buffer[0]  = Constants::GZIP_ID1;
109     buffer[1]  = Constants::GZIP_ID2;
110     buffer[2]  = Constants::CM_DEFLATE;
111     buffer[3]  = Constants::FLG_FEXTRA;
112     buffer[9]  = Constants::OS_UNKNOWN;
113     buffer[10] = Constants::BGZF_XLEN;
114     buffer[12] = Constants::BGZF_ID1;
115     buffer[13] = Constants::BGZF_ID2;
116     buffer[14] = Constants::BGZF_LEN;
117
118     // set compression level
119     const int compressionLevel = ( m_isWriteCompressed ? Z_DEFAULT_COMPRESSION : 0 );
120
121     // loop to retry for blocks that do not compress enough
122     int inputLength = m_blockOffset;
123     size_t compressedLength = 0;
124     const unsigned int bufferSize = Constants::BGZF_MAX_BLOCK_SIZE;
125
126     while ( true ) {
127
128         // initialize zstream values
129         z_stream zs;
130         zs.zalloc    = NULL;
131         zs.zfree     = NULL;
132         zs.next_in   = (Bytef*)Resources.UncompressedBlock;
133         zs.avail_in  = inputLength;
134         zs.next_out  = (Bytef*)&buffer[Constants::BGZF_BLOCK_HEADER_LENGTH];
135         zs.avail_out = bufferSize -
136                        Constants::BGZF_BLOCK_HEADER_LENGTH -
137                        Constants::BGZF_BLOCK_FOOTER_LENGTH;
138
139         // initialize the zlib compression algorithm
140         int status = deflateInit2(&zs,
141                                   compressionLevel,
142                                   Z_DEFLATED,
143                                   Constants::GZIP_WINDOW_BITS,
144                                   Constants::Z_DEFAULT_MEM_LEVEL,
145                                   Z_DEFAULT_STRATEGY);
146         if ( status != Z_OK )
147             throw BamException("BgzfStream::DeflateBlock", "zlib deflateInit2 failed");
148
149         // compress the data
150         status = deflate(&zs, Z_FINISH);
151
152         // if not at stream end
153         if ( status != Z_STREAM_END ) {
154
155             deflateEnd(&zs);
156
157             // if error status
158             if ( status != Z_OK )
159                 throw BamException("BgzfStream::DeflateBlock", "zlib deflate failed");
160
161             // not enough space available in buffer
162             // try to reduce the input length & re-start loop
163             inputLength -= 1024;
164             if ( inputLength <= 0 )
165                 throw BamException("BgzfStream::DeflateBlock", "input reduction failed");
166             continue;
167         }
168
169         // finalize the compression routine
170         status = deflateEnd(&zs);
171         if ( status != Z_OK )
172             throw BamException("BgzfStream::DeflateBlock", "zlib deflateEnd failed");
173
174         // update compressedLength
175         compressedLength = zs.total_out +
176                            Constants::BGZF_BLOCK_HEADER_LENGTH +
177                            Constants::BGZF_BLOCK_FOOTER_LENGTH;
178         if ( compressedLength > Constants::BGZF_MAX_BLOCK_SIZE )
179             throw BamException("BgzfStream::DeflateBlock", "deflate overflow");
180
181         // quit while loop
182         break;
183     }
184
185     // store the compressed length
186     BamTools::PackUnsignedShort(&buffer[16], static_cast<uint16_t>(compressedLength - 1));
187
188     // store the CRC32 checksum
189     uint32_t crc = crc32(0, NULL, 0);
190     crc = crc32(crc, (Bytef*)Resources.UncompressedBlock, inputLength);
191     BamTools::PackUnsignedInt(&buffer[compressedLength - 8], crc);
192     BamTools::PackUnsignedInt(&buffer[compressedLength - 4], inputLength);
193
194     // ensure that we have less than a block of data left
195     int remaining = m_blockOffset - inputLength;
196     if ( remaining > 0 ) {
197         if ( remaining > inputLength )
198             throw BamException("BgzfStream::DeflateBlock", "after deflate, remainder too large");
199         memcpy(Resources.UncompressedBlock, Resources.UncompressedBlock + inputLength, remaining);
200     }
201
202     // update block data
203     m_blockOffset = remaining;
204
205     // return result
206     return compressedLength;
207 }
208
209 // flushes the data in the BGZF block
210 void BgzfStream::FlushBlock(void) {
211
212     BT_ASSERT_X( m_device, "BgzfStream::FlushBlock() - attempting to flush to null device" );
213
214     // flush all of the remaining blocks
215     while ( m_blockOffset > 0 ) {
216
217         // compress the data block
218         const size_t blockLength = DeflateBlock();
219
220         // flush the data to our output device
221         const size_t numBytesWritten = m_device->Write(Resources.CompressedBlock, blockLength);
222         if ( numBytesWritten != blockLength ) {
223             stringstream s("");
224             s << "expected to write " << blockLength
225               << " bytes during flushing, but wrote " << numBytesWritten;
226             throw BamException("BgzfStream::FlushBlock", s.str());
227         }
228
229         // update block data
230         m_blockAddress += blockLength;
231     }
232 }
233
234 // decompresses the current block
235 size_t BgzfStream::InflateBlock(const size_t& blockLength) {
236
237     // setup zlib stream object
238     z_stream zs;
239     zs.zalloc    = NULL;
240     zs.zfree     = NULL;
241     zs.next_in   = (Bytef*)Resources.CompressedBlock + 18;
242     zs.avail_in  = blockLength - 16;
243     zs.next_out  = (Bytef*)Resources.UncompressedBlock;
244     zs.avail_out = Constants::BGZF_DEFAULT_BLOCK_SIZE;
245
246     // initialize
247     int status = inflateInit2(&zs, Constants::GZIP_WINDOW_BITS);
248     if ( status != Z_OK )
249         throw BamException("BgzfStream::InflateBlock", "zlib inflateInit failed");
250
251     // decompress
252     status = inflate(&zs, Z_FINISH);
253     if ( status != Z_STREAM_END ) {
254         inflateEnd(&zs);
255         throw BamException("BgzfStream::InflateBlock", "zlib inflate failed");
256     }
257
258     // finalize
259     status = inflateEnd(&zs);
260     if ( status != Z_OK ) {
261         inflateEnd(&zs);
262         throw BamException("BgzfStream::InflateBlock", "zlib inflateEnd failed");
263     }
264
265     // return result
266     return zs.total_out;
267 }
268
269 bool BgzfStream::IsOpen(void) const {
270     if ( m_device == 0 )
271         return false;
272     return m_device->IsOpen();
273 }
274
275 void BgzfStream::Open(const string& filename, const IBamIODevice::OpenMode mode) {
276
277     // close current device if necessary
278     Close();
279     BT_ASSERT_X( (m_device == 0), "BgzfStream::Open() - unable to properly close previous IO device" );
280
281     // retrieve new IO device depending on filename
282     m_device = BamDeviceFactory::CreateDevice(filename);
283     BT_ASSERT_X( m_device, "BgzfStream::Open() - unable to create IO device from filename" );
284
285     // if device fails to open
286     if ( !m_device->Open(mode) ) {
287         const string deviceError = m_device->GetErrorString();
288         const string message = string("could not open BGZF stream: \n\t") + deviceError;
289         throw BamException("BgzfStream::Open", message);
290     }
291 }
292
293 // reads BGZF data into a byte buffer
294 size_t BgzfStream::Read(char* data, const size_t dataLength) {
295
296     if ( dataLength == 0 )
297         return 0;
298
299     // if stream not open for reading
300     BT_ASSERT_X( m_device, "BgzfStream::Read() - trying to read from null device");
301     if ( !m_device->IsOpen() || (m_device->Mode() != IBamIODevice::ReadOnly) )
302         return 0;
303
304     // read blocks as needed until desired data length is retrieved
305     size_t numBytesRead = 0;
306     while ( numBytesRead < dataLength ) {
307
308         // determine bytes available in current block
309         int bytesAvailable = m_blockLength - m_blockOffset;
310
311         // read (and decompress) next block if needed
312         if ( bytesAvailable <= 0 ) {
313             ReadBlock();
314             bytesAvailable = m_blockLength - m_blockOffset;
315             if ( bytesAvailable <= 0 )
316                 break;
317         }
318
319         // copy data from uncompressed source buffer into data destination buffer
320         const size_t copyLength = min( (dataLength-numBytesRead), (size_t)bytesAvailable );
321         memcpy(data, Resources.UncompressedBlock + m_blockOffset, copyLength);
322
323         // update counters
324         m_blockOffset  += copyLength;
325         data         += copyLength;
326         numBytesRead += copyLength;
327     }
328
329     // update block data
330     if ( m_blockOffset == m_blockLength ) {
331         m_blockAddress = m_device->Tell();
332         m_blockOffset  = 0;
333         m_blockLength  = 0;
334
335     }
336
337     // return actual number of bytes read
338     return numBytesRead;
339 }
340
341 // reads a BGZF block
342 void BgzfStream::ReadBlock(void) {
343
344     BT_ASSERT_X( m_device, "BgzfStream::ReadBlock() - trying to read from null IO device");
345
346     // store block's starting address
347     int64_t blockAddress = m_device->Tell();
348
349     // read block header from file
350     char header[Constants::BGZF_BLOCK_HEADER_LENGTH];
351     size_t numBytesRead = m_device->Read(header, Constants::BGZF_BLOCK_HEADER_LENGTH);
352
353     // if block header empty
354     if ( numBytesRead == 0 ) {
355         m_blockLength = 0;
356         return;
357     }
358
359     // if block header invalid size
360     if ( numBytesRead != Constants::BGZF_BLOCK_HEADER_LENGTH )
361         throw BamException("BgzfStream::ReadBlock", "invalid block header size");
362
363     // validate block header contents
364     if ( !BgzfStream::CheckBlockHeader(header) )
365         throw BamException("BgzfStream::ReadBlock", "invalid block header contents");
366
367     // copy header contents to compressed buffer
368     const size_t blockLength = BamTools::UnpackUnsignedShort(&header[16]) + 1;
369     memcpy(Resources.CompressedBlock, header, Constants::BGZF_BLOCK_HEADER_LENGTH);
370
371     // read remainder of block
372     const size_t remaining = blockLength - Constants::BGZF_BLOCK_HEADER_LENGTH;
373     numBytesRead = m_device->Read(&Resources.CompressedBlock[Constants::BGZF_BLOCK_HEADER_LENGTH], remaining);
374     if ( numBytesRead != remaining )
375         throw BamException("BgzfStream::ReadBlock", "could not read data from block");
376
377     // decompress block data
378     numBytesRead = InflateBlock(blockLength);
379
380     // update block data
381     if ( m_blockLength != 0 )
382         m_blockOffset = 0;
383     m_blockAddress = blockAddress;
384     m_blockLength  = numBytesRead;
385 }
386
387 // seek to position in BGZF file
388 void BgzfStream::Seek(const int64_t& position) {
389
390     BT_ASSERT_X( m_device, "BgzfStream::Seek() - trying to seek on null IO device");
391
392     // skip if device is not open
393     if ( !IsOpen() ) return;
394
395     // determine adjusted offset & address
396     int     blockOffset  = (position & 0xFFFF);
397     int64_t blockAddress = (position >> 16) & 0xFFFFFFFFFFFFLL;
398
399     // attempt seek in file
400     if ( m_device->IsRandomAccess() && m_device->Seek(blockAddress) ) {
401
402         // update block data & return success
403         m_blockLength  = 0;
404         m_blockAddress = blockAddress;
405         m_blockOffset  = blockOffset;
406     }
407     else {
408         stringstream s("");
409         s << "unable to seek to position: " << position;
410         throw BamException("BgzfStream::Seek", s.str());
411     }
412 }
413
414 void BgzfStream::SetWriteCompressed(bool ok) {
415     m_isWriteCompressed = ok;
416 }
417
418 // get file position in BGZF file
419 int64_t BgzfStream::Tell(void) const {
420     if ( !IsOpen() )
421         return 0;
422     return ( (m_blockAddress << 16) | (m_blockOffset & 0xFFFF) );
423 }
424
425 // writes the supplied data into the BGZF buffer
426 size_t BgzfStream::Write(const char* data, const size_t dataLength) {
427
428     BT_ASSERT_X( m_device, "BgzfStream::Write() - trying to write to null IO device");
429     BT_ASSERT_X( (m_device->Mode() == IBamIODevice::WriteOnly),
430                  "BgzfStream::Write() - trying to write to non-writable IO device");
431
432     // skip if file not open for writing
433     if ( !IsOpen() )
434         return 0;
435
436     // write blocks as needed til all data is written
437     size_t numBytesWritten = 0;
438     const char* input = data;
439     const size_t blockLength = Constants::BGZF_DEFAULT_BLOCK_SIZE;
440     while ( numBytesWritten < dataLength ) {
441
442         // copy data contents to uncompressed output buffer
443         unsigned int copyLength = min(blockLength - m_blockOffset, dataLength - numBytesWritten);
444         char* buffer = Resources.UncompressedBlock;
445         memcpy(buffer + m_blockOffset, input, copyLength);
446
447         // update counter
448         m_blockOffset   += copyLength;
449         input           += copyLength;
450         numBytesWritten += copyLength;
451
452         // flush (& compress) output buffer when full
453         if ( m_blockOffset == blockLength )
454             FlushBlock();
455     }
456
457     // return actual number of bytes written
458     return numBytesWritten;
459 }