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 // ***************************************************************************
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;
28 // ----------------------------
29 // RaiiWrapper implementation
30 // ----------------------------
32 BgzfStream::RaiiWrapper::RaiiWrapper(void) {
33 CompressedBlock = new char[Constants::BGZF_MAX_BLOCK_SIZE];
34 UncompressedBlock = new char[Constants::BGZF_DEFAULT_BLOCK_SIZE];
37 BgzfStream::RaiiWrapper::~RaiiWrapper(void) {
40 delete[] CompressedBlock;
41 delete[] UncompressedBlock;
43 UncompressedBlock = 0;
46 // ---------------------------
47 // BgzfStream implementation
48 // ---------------------------
51 BgzfStream::BgzfStream(void)
55 , m_isWriteCompressed(true)
60 BgzfStream::~BgzfStream(void) {
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 );
77 void BgzfStream::Close(void) {
83 m_isWriteCompressed = true;
85 // skip if no device open
86 if ( m_device == 0 ) return;
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) ) {
92 const size_t blockLength = DeflateBlock();
93 m_device->Write(Resources.CompressedBlock, blockLength);
102 // compresses the current block
103 size_t BgzfStream::DeflateBlock(void) {
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;
118 // set compression level
119 const int compressionLevel = ( m_isWriteCompressed ? Z_DEFAULT_COMPRESSION : 0 );
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;
128 // initialize zstream values
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;
139 // initialize the zlib compression algorithm
140 int status = deflateInit2(&zs,
143 Constants::GZIP_WINDOW_BITS,
144 Constants::Z_DEFAULT_MEM_LEVEL,
146 if ( status != Z_OK )
147 throw BamException("BgzfStream::DeflateBlock", "zlib deflateInit2 failed");
150 status = deflate(&zs, Z_FINISH);
152 // if not at stream end
153 if ( status != Z_STREAM_END ) {
158 if ( status != Z_OK )
159 throw BamException("BgzfStream::DeflateBlock", "zlib deflate failed");
161 // not enough space available in buffer
162 // try to reduce the input length & re-start loop
164 if ( inputLength <= 0 )
165 throw BamException("BgzfStream::DeflateBlock", "input reduction failed");
169 // finalize the compression routine
170 status = deflateEnd(&zs);
171 if ( status != Z_OK )
172 throw BamException("BgzfStream::DeflateBlock", "zlib deflateEnd failed");
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");
185 // store the compressed length
186 BamTools::PackUnsignedShort(&buffer[16], static_cast<uint16_t>(compressedLength - 1));
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);
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);
203 m_blockOffset = remaining;
206 return compressedLength;
209 // flushes the data in the BGZF block
210 void BgzfStream::FlushBlock(void) {
212 BT_ASSERT_X( m_device, "BgzfStream::FlushBlock() - attempting to flush to null device" );
214 // flush all of the remaining blocks
215 while ( m_blockOffset > 0 ) {
217 // compress the data block
218 const size_t blockLength = DeflateBlock();
220 // flush the data to our output device
221 const size_t numBytesWritten = m_device->Write(Resources.CompressedBlock, blockLength);
222 if ( numBytesWritten != blockLength ) {
224 s << "expected to write " << blockLength
225 << " bytes during flushing, but wrote " << numBytesWritten;
226 throw BamException("BgzfStream::FlushBlock", s.str());
230 m_blockAddress += blockLength;
234 // decompresses the current block
235 size_t BgzfStream::InflateBlock(const size_t& blockLength) {
237 // setup zlib stream object
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;
247 int status = inflateInit2(&zs, Constants::GZIP_WINDOW_BITS);
248 if ( status != Z_OK )
249 throw BamException("BgzfStream::InflateBlock", "zlib inflateInit failed");
252 status = inflate(&zs, Z_FINISH);
253 if ( status != Z_STREAM_END ) {
255 throw BamException("BgzfStream::InflateBlock", "zlib inflate failed");
259 status = inflateEnd(&zs);
260 if ( status != Z_OK ) {
262 throw BamException("BgzfStream::InflateBlock", "zlib inflateEnd failed");
269 bool BgzfStream::IsOpen(void) const {
272 return m_device->IsOpen();
275 void BgzfStream::Open(const string& filename, const IBamIODevice::OpenMode mode) {
277 // close current device if necessary
279 BT_ASSERT_X( (m_device == 0), "BgzfStream::Open() - unable to properly close previous IO device" );
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" );
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);
293 // reads BGZF data into a byte buffer
294 size_t BgzfStream::Read(char* data, const size_t dataLength) {
296 if ( dataLength == 0 )
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) )
304 // read blocks as needed until desired data length is retrieved
305 size_t numBytesRead = 0;
306 while ( numBytesRead < dataLength ) {
308 // determine bytes available in current block
309 int bytesAvailable = m_blockLength - m_blockOffset;
311 // read (and decompress) next block if needed
312 if ( bytesAvailable <= 0 ) {
314 bytesAvailable = m_blockLength - m_blockOffset;
315 if ( bytesAvailable <= 0 )
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);
324 m_blockOffset += copyLength;
326 numBytesRead += copyLength;
330 if ( m_blockOffset == m_blockLength ) {
331 m_blockAddress = m_device->Tell();
337 // return actual number of bytes read
341 // reads a BGZF block
342 void BgzfStream::ReadBlock(void) {
344 BT_ASSERT_X( m_device, "BgzfStream::ReadBlock() - trying to read from null IO device");
346 // store block's starting address
347 int64_t blockAddress = m_device->Tell();
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);
353 // if block header empty
354 if ( numBytesRead == 0 ) {
359 // if block header invalid size
360 if ( numBytesRead != Constants::BGZF_BLOCK_HEADER_LENGTH )
361 throw BamException("BgzfStream::ReadBlock", "invalid block header size");
363 // validate block header contents
364 if ( !BgzfStream::CheckBlockHeader(header) )
365 throw BamException("BgzfStream::ReadBlock", "invalid block header contents");
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);
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");
377 // decompress block data
378 numBytesRead = InflateBlock(blockLength);
381 if ( m_blockLength != 0 )
383 m_blockAddress = blockAddress;
384 m_blockLength = numBytesRead;
387 // seek to position in BGZF file
388 void BgzfStream::Seek(const int64_t& position) {
390 BT_ASSERT_X( m_device, "BgzfStream::Seek() - trying to seek on null IO device");
392 // skip if device is not open
393 if ( !IsOpen() ) return;
395 // determine adjusted offset & address
396 int blockOffset = (position & 0xFFFF);
397 int64_t blockAddress = (position >> 16) & 0xFFFFFFFFFFFFLL;
399 // attempt seek in file
400 if ( m_device->IsRandomAccess() && m_device->Seek(blockAddress) ) {
402 // update block data & return success
404 m_blockAddress = blockAddress;
405 m_blockOffset = blockOffset;
409 s << "unable to seek to position: " << position;
410 throw BamException("BgzfStream::Seek", s.str());
414 void BgzfStream::SetWriteCompressed(bool ok) {
415 m_isWriteCompressed = ok;
418 // get file position in BGZF file
419 int64_t BgzfStream::Tell(void) const {
422 return ( (m_blockAddress << 16) | (m_blockOffset & 0xFFFF) );
425 // writes the supplied data into the BGZF buffer
426 size_t BgzfStream::Write(const char* data, const size_t dataLength) {
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");
432 // skip if file not open for writing
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 ) {
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);
448 m_blockOffset += copyLength;
450 numBytesWritten += copyLength;
452 // flush (& compress) output buffer when full
453 if ( m_blockOffset == blockLength )
457 // return actual number of bytes written
458 return numBytesWritten;