--- libgig/trunk/src/RIFF.cpp 2007/03/18 07:13:06 1102 +++ libgig/trunk/src/RIFF.cpp 2010/08/29 11:10:36 2120 @@ -2,7 +2,7 @@ * * * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2007 by Christian Schoenebeck * + * Copyright (C) 2003-2009 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -21,6 +21,8 @@ * MA 02111-1307 USA * ***************************************************************************/ +#include +#include #include #include "RIFF.h" @@ -29,6 +31,25 @@ namespace RIFF { +// *************** Internal functions ************** +// * + + /// Returns a human readable path of the given chunk. + static String __resolveChunkPath(Chunk* pCk) { + String sPath; + for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) { + if (pChunk->GetChunkID() == CHUNK_ID_LIST) { + List* pList = (List*) pChunk; + sPath = "->'" + pList->GetListTypeString() + "'" + sPath; + } else { + sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath; + } + } + return sPath; + } + + + // *************** Chunk ************** // * @@ -39,6 +60,8 @@ ulPos = 0; pParent = NULL; pChunkData = NULL; + CurrentChunkSize = 0; + NewChunkSize = 0; ulChunkDataSize = 0; ChunkID = CHUNK_ID_RIFF; this->pFile = pFile; @@ -53,6 +76,8 @@ pParent = Parent; ulPos = 0; pChunkData = NULL; + CurrentChunkSize = 0; + NewChunkSize = 0; ulChunkDataSize = 0; ReadHeader(StartPos); } @@ -63,14 +88,14 @@ this->pParent = pParent; ulPos = 0; pChunkData = NULL; - ulChunkDataSize = 0; ChunkID = uiChunkID; + ulChunkDataSize = 0; CurrentChunkSize = 0; NewChunkSize = uiBodySize; } Chunk::~Chunk() { - if (CurrentChunkSize != NewChunkSize) pFile->UnlogResized(this); + if (pFile) pFile->UnlogResized(this); if (pChunkData) delete[] pChunkData; } @@ -78,6 +103,8 @@ #if DEBUG std::cout << "Chunk::Readheader(" << fPos << ") "; #endif // DEBUG + ChunkID = 0; + NewChunkSize = CurrentChunkSize = 0; #if POSIX if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) { read(pFile->hFileRead, &ChunkID, 4); @@ -108,8 +135,8 @@ } #if DEBUG std::cout << "ckID=" << convertToString(ChunkID) << " "; - std::cout << "ckSize=" << ChunkSize << " "; - std::cout << "bEndianNative=" << bEndianNative << std::endl; + std::cout << "ckSize=" << CurrentChunkSize << " "; + std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl; #endif // DEBUG NewChunkSize = CurrentChunkSize; } @@ -205,7 +232,7 @@ #if DEBUG std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl; #endif // DEBUG - return CurrentChunkSize - ulPos; + return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0; } /** @@ -216,7 +243,7 @@ * - RIFF::stream_closed : * the data stream was closed somehow, no more reading possible * - RIFF::stream_end_reached : - * alreaady reached the end of the chunk data, no more reading + * already reached the end of the chunk data, no more reading * possible without SetPos() */ stream_state_t Chunk::GetState() { @@ -254,6 +281,7 @@ #if DEBUG std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl; #endif // DEBUG + if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet) if (ulPos >= CurrentChunkSize) return 0; if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize; #if POSIX @@ -339,7 +367,7 @@ #elif defined(WIN32) if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { throw Exception("Could not seek to position " + ToString(ulPos) + - " in chunk (" + ToString(ulStartPos + ulPos) + " in file)"); + " in chunk (" + ToString(ulStartPos + ulPos) + " in file)"); } DWORD writtenWords; WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL); @@ -706,7 +734,7 @@ * @see ReleaseChunkData() */ void* Chunk::LoadChunkData() { - if (!pChunkData && pFile->Filename != "") { + if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) { #if POSIX if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL; #elif defined(WIN32) @@ -775,7 +803,8 @@ * @see File::Save() */ void Chunk::Resize(int iNewSize) { - if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte"); + if (iNewSize <= 0) + throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this)); if (NewChunkSize == iNewSize) return; NewChunkSize = iNewSize; pFile->LogAsResized(this); @@ -832,7 +861,7 @@ #else int iBytesMoved = 1; #endif - for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) { + for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) { iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096; #if POSIX lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET); @@ -922,6 +951,10 @@ #if DEBUG std::cout << "List::~List()" << std::endl; #endif // DEBUG + DeleteChunkList(); + } + + void List::DeleteChunkList() { if (pSubChunks) { ChunkList::iterator iter = pSubChunks->begin(); ChunkList::iterator end = pSubChunks->end(); @@ -930,8 +963,12 @@ iter++; } delete pSubChunks; + pSubChunks = NULL; + } + if (pSubChunksMap) { + delete pSubChunksMap; + pSubChunksMap = NULL; } - if (pSubChunksMap) delete pSubChunksMap; } /** @@ -1132,6 +1169,8 @@ pSubChunks->push_back(pNewChunk); (*pSubChunksMap)[uiChunkID] = pNewChunk; pNewChunk->Resize(uiBodySize); + NewChunkSize += CHUNK_HEADER_SIZE; + pFile->LogAsResized(this); return pNewChunk; } @@ -1167,6 +1206,8 @@ List* pNewListChunk = new List(pFile, this, uiListType); pSubChunks->push_back(pNewListChunk); (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk; + NewChunkSize += LIST_HEADER_SIZE; + pFile->LogAsResized(this); return pNewListChunk; } @@ -1203,6 +1244,7 @@ std::cout << "List::Readheader(ulong) "; #endif // DEBUG Chunk::ReadHeader(fPos); + if (CurrentChunkSize < 4) return; NewChunkSize = CurrentChunkSize -= 4; #if POSIX lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET); @@ -1248,7 +1290,11 @@ if (!pSubChunks) { pSubChunks = new ChunkList(); pSubChunksMap = new ChunkMap(); + #if defined(WIN32) + if (pFile->hFileRead == INVALID_HANDLE_VALUE) return; + #else if (!pFile->hFileRead) return; + #endif unsigned long uiOriginalPos = GetPos(); SetPos(0); // jump to beginning of list chunk body while (RemainingBytes() >= CHUNK_HEADER_SIZE) { @@ -1338,16 +1384,27 @@ // *************** File *************** // * +//HACK: to avoid breaking DLL compatibility to older versions of libgig we roll the new std::set into the old std::list container, should be replaced on member variable level soon though +#define _GET_RESIZED_CHUNKS() \ + (reinterpret_cast*>(ResizedChunks.front())) + /** @brief Create new RIFF file. * * Use this constructor if you want to create a new RIFF file completely * "from scratch". Note: there must be no empty chunks or empty list * chunks when trying to make the new RIFF file persistent with Save()! * + * Note: by default, the RIFF file will be saved in native endian + * format; that is, as a RIFF file on little-endian machines and + * as a RIFX file on big-endian. To change this behaviour, call + * SetByteOrder() before calling Save(). + * * @param FileType - four-byte identifier of the RIFF file type - * @see AddSubChunk(), AddSubList() + * @see AddSubChunk(), AddSubList(), SetByteOrder() */ File::File(uint32_t FileType) : List(this) { + //HACK: see _GET_RESIZED_CHUNKS() comment + ResizedChunks.push_back(reinterpret_cast(new std::set)); #if defined(WIN32) hFileRead = hFileWrite = INVALID_HANDLE_VALUE; #else @@ -1372,6 +1429,8 @@ std::cout << "File::File("<(new std::set)); #if POSIX hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK); if (hFileRead <= 0) { @@ -1383,7 +1442,8 @@ path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL + FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, NULL ); if (hFileRead == INVALID_HANDLE_VALUE) { hFileRead = hFileWrite = INVALID_HANDLE_VALUE; @@ -1396,7 +1456,7 @@ Mode = stream_mode_read; ulStartPos = RIFF_HEADER_SIZE; ReadHeader(0); - if (ChunkID != CHUNK_ID_RIFF) { + if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) { throw RIFF::Exception("Not a RIFF file"); } } @@ -1436,7 +1496,9 @@ Filename.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL + FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, + NULL ); if (hFileRead == INVALID_HANDLE_VALUE) { hFileRead = hFileWrite = INVALID_HANDLE_VALUE; @@ -1464,16 +1526,20 @@ GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL + FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, + NULL ); if (hFileRead == INVALID_HANDLE_VALUE) { hFileRead = hFileWrite = CreateFile( Filename.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL + FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, + NULL ); - throw Exception("Could not (re)open file \"" + Filename + "\" in read mode"); + throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode"); } #else if (hFileRead) fclose(hFileRead); @@ -1507,6 +1573,23 @@ return false; } + /** @brief Set the byte order to be used when saving. + * + * Set the byte order to be used in the file. A value of + * endian_little will create a RIFF file, endian_big a RIFX file + * and endian_native will create a RIFF file on little-endian + * machines and RIFX on big-endian machines. + * + * @param Endian - endianess to use when file is saved. + */ + void File::SetByteOrder(endian_t Endian) { + #if WORDS_BIGENDIAN + bEndianNative = Endian != endian_little; + #else + bEndianNative = Endian != endian_big; + #endif + } + /** @brief Save changes to same file. * * Make all changes of all chunks persistent by writing them to the @@ -1533,24 +1616,14 @@ // first we sum up all positive chunk size changes (and skip all negative ones) unsigned long ulPositiveSizeDiff = 0; - for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) { + std::set* resizedChunks = _GET_RESIZED_CHUNKS(); + for (std::set::const_iterator iter = resizedChunks->begin(), end = resizedChunks->end(); iter != end; ++iter) { if ((*iter)->GetNewSize() == 0) { - // just to make the exception message a bit more verbose: resolve the chunk's path - String sChunkPath; - for (Chunk* pChunk = *iter; pChunk; pChunk = pChunk->GetParent()) { - if (pChunk->GetChunkID() == CHUNK_ID_LIST) { - List* pList = (List*) pChunk; - sChunkPath = "->'" + pList->GetListTypeString() + "'" + sChunkPath; - } else { - sChunkPath = "->'" + pChunk->GetChunkIDString() + "'" + sChunkPath; - } - } - throw Exception("There is at least one empty chunk (zero size): " + sChunkPath); - } - if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) { - unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte - ulPositiveSizeDiff += ulDiff; + throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter)); } + unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2; + unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2; + if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded; } unsigned long ulWorkingFileSize = GetFileSize(); @@ -1566,11 +1639,11 @@ #if defined(WIN32) DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured #else - int iBytesMoved = 1; + int iBytesMoved = 1; #endif - for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) { - const unsigned long ulToMove = ulFileSize - ulPos; - iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096; + for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) { + iBytesMoved = (ulPos < 4096) ? ulPos : 4096; + ulPos -= iBytesMoved; #if POSIX lseek(hFileRead, ulPos, SEEK_SET); iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved); @@ -1600,7 +1673,7 @@ if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize); // forget all resized chunks - ResizedChunks.clear(); + resizedChunks->clear(); } /** @brief Save changes to another file. @@ -1633,7 +1706,8 @@ #elif defined(WIN32) hFileWrite = CreateFile( path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, - NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL + NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, NULL ); if (hFileWrite == INVALID_HANDLE_VALUE) { hFileWrite = hFileRead; @@ -1656,18 +1730,16 @@ if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize); // forget all resized chunks - ResizedChunks.clear(); + _GET_RESIZED_CHUNKS()->clear(); - if (Filename.length() > 0) { - #if POSIX - close(hFileWrite); - #elif defined(WIN32) - CloseHandle(hFileWrite); - #else - fclose(hFileWrite); - #endif - hFileWrite = hFileRead; - } + #if POSIX + if (hFileWrite) close(hFileWrite); + #elif defined(WIN32) + if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite); + #else + if (hFileWrite) fclose(hFileWrite); + #endif + hFileWrite = hFileRead; // associate new file with this File object from now on Filename = path; @@ -1701,14 +1773,18 @@ #else if (hFileRead) fclose(hFileRead); #endif // POSIX + DeleteChunkList(); + pFile = NULL; + //HACK: see _GET_RESIZED_CHUNKS() comment + delete _GET_RESIZED_CHUNKS(); } void File::LogAsResized(Chunk* pResizedChunk) { - ResizedChunks.push_back(pResizedChunk); + _GET_RESIZED_CHUNKS()->insert(pResizedChunk); } void File::UnlogResized(Chunk* pResizedChunk) { - ResizedChunks.remove(pResizedChunk); + _GET_RESIZED_CHUNKS()->erase(pResizedChunk); } unsigned long File::GetFileSize() {