--- libgig/trunk/src/RIFF.cpp 2005/09/25 13:40:37 780 +++ libgig/trunk/src/RIFF.cpp 2008/03/06 20:42:22 1713 @@ -1,8 +1,8 @@ /*************************************************************************** * * - * libgig - C++ cross-platform Gigasampler format file loader library * + * libgig - C++ cross-platform Gigasampler format file access library * * * - * Copyright (C) 2003-2005 by Christian Schoenebeck * + * Copyright (C) 2003-2007 by Christian Schoenebeck * * * * * * This library is free software; you can redistribute it and/or modify * @@ -21,20 +21,30 @@ * MA 02111-1307 USA * ***************************************************************************/ +#include #include -#include #include "RIFF.h" +#include "helper.h" + namespace RIFF { -// *************** Helper Functions ************** +// *************** Internal functions ************** // * - template inline String ToString(T o) { - std::stringstream ss; - ss << o; - return ss.str(); + /// 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; } @@ -49,6 +59,8 @@ ulPos = 0; pParent = NULL; pChunkData = NULL; + ulChunkDataSize = 0; + ChunkID = CHUNK_ID_RIFF; this->pFile = pFile; } @@ -61,6 +73,7 @@ pParent = Parent; ulPos = 0; pChunkData = NULL; + ulChunkDataSize = 0; ReadHeader(StartPos); } @@ -70,12 +83,14 @@ this->pParent = pParent; ulPos = 0; pChunkData = NULL; + ulChunkDataSize = 0; ChunkID = uiChunkID; CurrentChunkSize = 0; NewChunkSize = uiBodySize; } Chunk::~Chunk() { + pFile->UnlogResized(this); if (pChunkData) delete[] pChunkData; } @@ -87,6 +102,11 @@ if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) { read(pFile->hFileRead, &ChunkID, 4); read(pFile->hFileRead, &CurrentChunkSize, 4); + #elif defined(WIN32) + if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) { + DWORD dwBytesRead; + ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL); + ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL); #else if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) { fread(&ChunkID, 4, 1, pFile->hFileRead); @@ -94,7 +114,7 @@ #endif // POSIX #if WORDS_BIGENDIAN if (ChunkID == CHUNK_ID_RIFF) { - bEndianNative = false; + pFile->bEndianNative = false; } #else // little endian if (ChunkID == CHUNK_ID_RIFX) { @@ -135,6 +155,12 @@ write(pFile->hFileWrite, &uiNewChunkID, 4); write(pFile->hFileWrite, &uiNewChunkSize, 4); } + #elif defined(WIN32) + if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) { + DWORD dwBytesWritten; + WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL); + WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL); + } #else if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) { fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite); @@ -210,7 +236,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() { @@ -218,7 +244,10 @@ std::cout << "Chunk::GetState()" << std::endl; #endif // DEBUG #if POSIX - if (pFile->hFileRead == 0) return stream_closed; + if (pFile->hFileRead == 0) return stream_closed; + #elif defined (WIN32) + if (pFile->hFileRead == INVALID_HANDLE_VALUE) + return stream_closed; #else if (pFile->hFileRead == NULL) return stream_closed; #endif // POSIX @@ -252,6 +281,12 @@ unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize); if (readWords < 1) return 0; readWords /= WordSize; + #elif defined(WIN32) + if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0; + DWORD readWords; + ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL); + if (readWords < 1) return 0; + readWords /= WordSize; #else // standard C functions if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0; unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead); @@ -293,9 +328,9 @@ * @see Resize() */ unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) { - if (pFile->Mode == stream_mode_read) - throw Exception("Writing chunk data in read-only file access mode was attempted"); - if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize >= CurrentChunkSize) + if (pFile->Mode != stream_mode_read_write) + throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first"); + if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize) throw Exception("End of chunk reached while trying to write data"); if (!pFile->bEndianNative && WordSize != 1) { switch (WordSize) { @@ -321,6 +356,15 @@ unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize); if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data"); writtenWords /= WordSize; + #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)"); + } + DWORD writtenWords; + WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL); + if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data"); + writtenWords /= WordSize; #else // standard C functions if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) { throw Exception("Could not seek to position " + ToString(ulPos) + @@ -667,28 +711,54 @@ * * Caution: the buffer pointer will be invalidated once * File::Save() was called. You have to call LoadChunkData() again to - * get a new pointer whenever File::Save() was called. + * get a new, valid pointer whenever File::Save() was called. + * + * You can call LoadChunkData() again if you previously scheduled to + * enlarge this chunk with a Resize() call. In that case the buffer will + * be enlarged to the new, scheduled chunk size and you can already + * place the new chunk data to the buffer and finally call File::Save() + * to enlarge the chunk physically and write the new data in one rush. + * This approach is definitely recommended if you have to enlarge and + * write new data to a lot of chunks. * * @returns a pointer to the data in RAM on success, NULL otherwise + * @throws Exception if data buffer could not be enlarged * @see ReleaseChunkData() */ void* Chunk::LoadChunkData() { - if (!pChunkData) { + if (!pChunkData && pFile->Filename != "") { #if POSIX if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL; - pChunkData = new uint8_t[GetSize()]; - if (!pChunkData) return NULL; - unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize()); + #elif defined(WIN32) + if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL; #else if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL; - pChunkData = new uint8_t[GetSize()]; + #endif // POSIX + unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize; + pChunkData = new uint8_t[ulBufferSize]; if (!pChunkData) return NULL; + memset(pChunkData, 0, ulBufferSize); + #if POSIX + unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize()); + #elif defined(WIN32) + DWORD readWords; + ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL); + #else unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead); #endif // POSIX if (readWords != GetSize()) { delete[] pChunkData; return (pChunkData = NULL); } + ulChunkDataSize = ulBufferSize; + } else if (NewChunkSize > ulChunkDataSize) { + uint8_t* pNewBuffer = new uint8_t[NewChunkSize]; + if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes"); + memset(pNewBuffer, 0 , NewChunkSize); + memcpy(pNewBuffer, pChunkData, ulChunkDataSize); + delete[] pChunkData; + pChunkData = pNewBuffer; + ulChunkDataSize = NewChunkSize; } return pChunkData; } @@ -718,14 +788,16 @@ * * Caution: You cannot directly write to enlarged chunks before * calling File::Save() as this might exceed the current chunk's body - * boundary. + * boundary! * * @param iNewSize - new chunk body size in bytes (must be greater than zero) * @throws RIFF::Exception if \a iNewSize is less than 1 * @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); } @@ -743,30 +815,29 @@ * (including its header size of course) */ unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) { - unsigned long ulOriginalPos = ulWritePos; + const unsigned long ulOriginalPos = ulWritePos; ulWritePos += CHUNK_HEADER_SIZE; + if (pFile->Mode != stream_mode_read_write) + throw Exception("Cannot write list chunk, file has to be opened in read+write mode"); + // if the whole chunk body was loaded into RAM if (pChunkData) { - // in case the chunk size was changed, reallocate the data in RAM with the chunk's new size - if (NewChunkSize != CurrentChunkSize) { - uint8_t* pNewBuffer = new uint8_t[NewChunkSize]; - if (NewChunkSize > CurrentChunkSize) { - memcpy(pNewBuffer, pChunkData, CurrentChunkSize); - memset(pNewBuffer + CurrentChunkSize, 0, NewChunkSize - CurrentChunkSize); - } else { - memcpy(pNewBuffer, pChunkData, NewChunkSize); - } - delete[] pChunkData; - pChunkData = pNewBuffer; - } - + // make sure chunk data buffer in RAM is at least as large as the new chunk size + LoadChunkData(); // write chunk data from RAM persistently to the file #if POSIX lseek(pFile->hFileWrite, ulWritePos, SEEK_SET); if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) { throw Exception("Writing Chunk data (from RAM) failed"); } + #elif defined(WIN32) + SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN); + DWORD dwBytesWritten; + WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL); + if (dwBytesWritten != NewChunkSize) { + throw Exception("Writing Chunk data (from RAM) failed"); + } #else fseek(pFile->hFileWrite, ulWritePos, SEEK_SET); if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) { @@ -777,7 +848,11 @@ // move chunk data from the end of the file to the appropriate position int8_t* pCopyBuffer = new int8_t[4096]; unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize; + #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; + #endif for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) { iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096; #if POSIX @@ -785,6 +860,11 @@ iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved); lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET); iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved); + #elif defined(WIN32) + SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN); + ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL); + SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN); + WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL); #else fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET); iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead); @@ -806,10 +886,16 @@ // add pad byte if needed if ((ulStartPos + NewChunkSize) % 2 != 0) { - char cPadByte = 0; + const char cPadByte = 0; #if POSIX + lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET); write(pFile->hFileWrite, &cPadByte, 1); + #elif defined(WIN32) + SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN); + DWORD dwBytesWritten; + WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL); #else + fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET); fwrite(&cPadByte, 1, 1, pFile->hFileWrite); #endif return ulStartPos + NewChunkSize + 1; @@ -1063,13 +1149,33 @@ Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) { if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte"); if (!pSubChunks) LoadSubChunks(); - Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, uiBodySize); + Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0); pSubChunks->push_back(pNewChunk); (*pSubChunksMap)[uiChunkID] = pNewChunk; - pFile->ResizedChunks.push_back(pNewChunk); + pNewChunk->Resize(uiBodySize); + NewChunkSize += CHUNK_HEADER_SIZE; + pFile->LogAsResized(this); return pNewChunk; } + /** @brief Moves a sub chunk. + * + * Moves a sub chunk from one position in a list to another + * position in the same list. The pSrc chunk is placed before the + * pDst chunk. + * + * @param pSrc - sub chunk to be moved + * @param pDst - the position to move to. pSrc will be placed + * before pDst. If pDst is 0, pSrc will be placed + * last in list. + */ + void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) { + if (!pSubChunks) LoadSubChunks(); + pSubChunks->remove(pSrc); + ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst); + pSubChunks->insert(iter, pSrc); + } + /** @brief Creates a new list sub chunk. * * Creates and adds a new list sub chunk to this list chunk. Note that @@ -1084,6 +1190,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; } @@ -1091,8 +1199,9 @@ * * Removes the sub chunk given by \a pSubChunk from this list and frees * it completely from RAM. The given chunk can either be a normal sub - * chunk or a list sub chunk. You should call File::Save() to make this - * change persistent at any time. + * chunk or a list sub chunk. In case the given chunk is a list chunk, + * all its subchunks (if any) will be removed recursively as well. You + * should call File::Save() to make this change persistent at any time. * * @param pSubChunk - sub chunk or sub list chunk to be removed */ @@ -1123,6 +1232,10 @@ #if POSIX lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET); read(pFile->hFileRead, &ListType, 4); + #elif defined(WIN32) + SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN); + DWORD dwBytesRead; + ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL); #else fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET); fread(&ListType, 4, 1, pFile->hFileRead); @@ -1143,6 +1256,10 @@ #if POSIX lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET); write(pFile->hFileWrite, &ListType, 4); + #elif defined(WIN32) + SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN); + DWORD dwBytesWritten; + WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL); #else fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET); fwrite(&ListType, 4, 1, pFile->hFileWrite); @@ -1156,7 +1273,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) { @@ -1182,6 +1303,11 @@ } } + void List::LoadSubChunksRecursively() { + for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList()) + pList->LoadSubChunksRecursively(); + } + /** @brief Write list chunk persistently e.g. to disk. * * Stores the list chunk persistently to its actual "physical" file. All @@ -1197,9 +1323,12 @@ * (including its header size of course) */ unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) { - unsigned long ulOriginalPos = ulWritePos; + const unsigned long ulOriginalPos = ulWritePos; ulWritePos += LIST_HEADER_SIZE; + if (pFile->Mode != stream_mode_read_write) + throw Exception("Cannot write list chunk, file has to be opened in read+write mode"); + // write all subchunks (including sub list chunks) recursively if (pSubChunks) { for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) { @@ -1211,6 +1340,9 @@ CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE; WriteHeader(ulOriginalPos); + // offset of this list chunk in new written file may have changed + ulStartPos = ulOriginalPos + LIST_HEADER_SIZE; + return ulWritePos; } @@ -1241,12 +1373,24 @@ * "from scratch". Note: there must be no empty chunks or empty list * chunks when trying to make the new RIFF file persistent with Save()! * - * @see AddSubChunk(), AddSubList() - */ - File::File() : List(this) { + * 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(), SetByteOrder() + */ + File::File(uint32_t FileType) : List(this) { + #if defined(WIN32) + hFileRead = hFileWrite = INVALID_HANDLE_VALUE; + #else hFileRead = hFileWrite = 0; + #endif + Mode = stream_mode_closed; bEndianNative = true; ulStartPos = RIFF_HEADER_SIZE; + ListType = FileType; } /** @brief Load existing RIFF file. @@ -1268,10 +1412,23 @@ hFileRead = hFileWrite = 0; throw RIFF::Exception("Can't open \"" + path + "\""); } + #elif defined(WIN32) + hFileRead = hFileWrite = CreateFile( + path.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, NULL + ); + if (hFileRead == INVALID_HANDLE_VALUE) { + hFileRead = hFileWrite = INVALID_HANDLE_VALUE; + throw RIFF::Exception("Can't open \"" + path + "\""); + } #else hFileRead = hFileWrite = fopen(path.c_str(), "rb"); - if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\""); + if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\""); #endif // POSIX + Mode = stream_mode_read; ulStartPos = RIFF_HEADER_SIZE; ReadHeader(0); if (ChunkID != CHUNK_ID_RIFF) { @@ -1308,13 +1465,27 @@ hFileRead = hFileWrite = 0; throw Exception("Could not (re)open file \"" + Filename + "\" in read mode"); } + #elif defined(WIN32) + if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead); + hFileRead = hFileWrite = CreateFile( + Filename.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, + NULL + ); + if (hFileRead == INVALID_HANDLE_VALUE) { + hFileRead = hFileWrite = INVALID_HANDLE_VALUE; + throw Exception("Could not (re)open file \"" + Filename + "\" in read mode"); + } #else if (hFileRead) fclose(hFileRead); - hFileRead = hFileWrite = fopen(path.c_str(), "rb"); + hFileRead = hFileWrite = fopen(Filename.c_str(), "rb"); if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode"); #endif __resetPos(); // reset read/write position of ALL 'Chunk' objects - return true; + break; case stream_mode_read_write: #if POSIX if (hFileRead) close(hFileRead); @@ -1323,23 +1494,77 @@ hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK); throw Exception("Could not open file \"" + Filename + "\" in read+write mode"); } + #elif defined(WIN32) + if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead); + hFileRead = hFileWrite = CreateFile( + Filename.c_str(), + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ, + NULL, OPEN_ALWAYS, + 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 | + FILE_FLAG_RANDOM_ACCESS, + NULL + ); + throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode"); + } #else if (hFileRead) fclose(hFileRead); - hFileRead = hFileWrite = fopen(path.c_str(), "r+b"); + hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b"); if (!hFileRead) { - hFileRead = hFileWrite = fopen(path.c_str(), "rb"); + hFileRead = hFileWrite = fopen(Filename.c_str(), "rb"); throw Exception("Could not open file \"" + Filename + "\" in read+write mode"); } #endif __resetPos(); // reset read/write position of ALL 'Chunk' objects - return true; + break; + case stream_mode_closed: + #if POSIX + if (hFileRead) close(hFileRead); + if (hFileWrite) close(hFileWrite); + #elif defined(WIN32) + if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead); + if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite); + #else + if (hFileRead) fclose(hFileRead); + if (hFileWrite) fclose(hFileWrite); + #endif + hFileRead = hFileWrite = 0; + break; default: throw Exception("Unknown file access mode"); } + Mode = NewMode; + return true; } 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 @@ -1351,8 +1576,11 @@ * chunk or any kind of IO error occured */ void File::Save() { + // make sure the RIFF tree is built (from the original file) + LoadSubChunksRecursively(); + // reopen file in write mode - bool bModeWasChanged = SetMode(stream_mode_read_write); + SetMode(stream_mode_read_write); // to be able to save the whole file without loading everything into // RAM and without having to store the data in a temporary file, we @@ -1363,9 +1591,11 @@ // 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) { - if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)"); - unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte + for (std::set::const_iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) { + if ((*iter)->GetNewSize() == 0) { + throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter)); + } + unsigned long ulDiff = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2 - (*iter)->GetSize() - (*iter)->GetSize() % 2; if (ulDiff > 0) ulPositiveSizeDiff += ulDiff; } @@ -1379,15 +1609,24 @@ // ... and move current data by the same amount towards end of file. int8_t* pCopyBuffer = new int8_t[4096]; const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE; + #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; - for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) { - const unsigned long ulToMove = ulFileSize - ulPos; - iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096; + #endif + 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); lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET); iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved); + #elif defined(WIN32) + SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN); + ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL); + SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN); + WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL); #else fseek(hFileRead, ulPos, SEEK_SET); iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead); @@ -1400,16 +1639,14 @@ } // rebuild / rewrite complete RIFF tree - unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff); + unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff); + unsigned long ulActualSize = __GetFileSize(hFileWrite); // resize file to the final size - if (ulTotalSize < ulWorkingFileSize) ResizeFile(ulTotalSize); + if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize); // forget all resized chunks ResizedChunks.clear(); - - // reopen file in read mode - if (bModeWasChanged) SetMode(stream_mode_read); } /** @brief Save changes to another file. @@ -1417,7 +1654,8 @@ * Make all changes of all chunks persistent by writing them to another * file. Caution: this method is optimized for writing to * another file, do not use it to save the changes to the same - * file! Use File::Save() in that case instead! + * file! Use File::Save() in that case instead! Ignoring this might + * result in a corrupted file, especially in case chunks were resized! * * After calling this method, this File object will be associated with * the new file (given by \a path) afterwards. @@ -1425,13 +1663,29 @@ * @param path - path and file name where everything should be written to */ void File::Save(const String& path) { + //TODO: we should make a check here if somebody tries to write to the same file and automatically call the other Save() method in that case + + // make sure the RIFF tree is built (from the original file) + LoadSubChunksRecursively(); + + if (Filename.length() > 0) SetMode(stream_mode_read); // open the other (new) file for writing and truncate it to zero size #if POSIX - hFileWrite = open(path.c_str(), O_RDWR | O_CREAT | O_TRUNC); + hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP); if (hFileWrite < 0) { hFileWrite = hFileRead; throw Exception("Could not open file \"" + path + "\" for writing"); } + #elif defined(WIN32) + hFileWrite = CreateFile( + path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, + NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | + FILE_FLAG_RANDOM_ACCESS, NULL + ); + if (hFileWrite == INVALID_HANDLE_VALUE) { + hFileWrite = hFileRead; + throw Exception("Could not open file \"" + path + "\" for writing"); + } #else hFileWrite = fopen(path.c_str(), "w+b"); if (!hFileWrite) { @@ -1439,27 +1693,45 @@ throw Exception("Could not open file \"" + path + "\" for writing"); } #endif // POSIX + Mode = stream_mode_read_write; // write complete RIFF tree to the other (new) file - WriteChunk(0, 0); + unsigned long ulTotalSize = WriteChunk(0, 0); + unsigned long ulActualSize = __GetFileSize(hFileWrite); + + // resize file to the final size (if the file was originally larger) + if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize); // forget all resized chunks ResizedChunks.clear(); + #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; - stream_mode_t oldMode = Mode; - Mode = (stream_mode_t) -1; // Just set it to an undefined mode ... - SetMode(oldMode); // ... so SetMode() has to reopen the file handles. + Mode = (stream_mode_t) -1; // Just set it to an undefined mode ... + SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles. } void File::ResizeFile(unsigned long ulNewSize) { #if POSIX if (ftruncate(hFileWrite, ulNewSize) < 0) throw Exception("Could not resize file \"" + Filename + "\""); + #elif defined(WIN32) + if ( + SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER || + !SetEndOfFile(hFileWrite) + ) throw Exception("Could not resize file \"" + Filename + "\""); #else - # error Sorry, this version of libgig only supports POSIX systems yet. - # error Reason: portable implementation of RIFF::File::ResizeFile() is missing! + # error Sorry, this version of libgig only supports POSIX and Windows systems yet. + # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)! #endif } @@ -1469,29 +1741,48 @@ #endif // DEBUG #if POSIX if (hFileRead) close(hFileRead); + #elif defined(WIN32) + if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead); #else if (hFileRead) fclose(hFileRead); #endif // POSIX } void File::LogAsResized(Chunk* pResizedChunk) { - ResizedChunks.push_back(pResizedChunk); + ResizedChunks.insert(pResizedChunk); + } + + void File::UnlogResized(Chunk* pResizedChunk) { + ResizedChunks.erase(pResizedChunk); } unsigned long File::GetFileSize() { - #if POSIX + return __GetFileSize(hFileRead); + } + + #if POSIX + unsigned long File::__GetFileSize(int hFile) { struct stat filestat; - fstat(hFileRead, &filestat); + fstat(hFile, &filestat); long size = filestat.st_size; - #else // standard C functions - long curpos = ftell(hFileRead); - fseek(hFileRead, 0, SEEK_END); - long size = ftell(hFileRead); - fseek(hFileRead, curpos, SEEK_SET); - #endif // POSIX return size; } - + #elif defined(WIN32) + unsigned long File::__GetFileSize(HANDLE hFile) { + DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/); + if (dwSize == INVALID_FILE_SIZE) + throw Exception("Windows FS error: could not determine file size"); + return dwSize; + } + #else // standard C functions + unsigned long File::__GetFileSize(FILE* hFile) { + long curpos = ftell(hFile); + fseek(hFile, 0, SEEK_END); + long size = ftell(hFile); + fseek(hFile, curpos, SEEK_SET); + return size; + } + #endif // *************** Exception ***************