/[svn]/libgig/trunk/src/RIFF.cpp
ViewVC logotype

Diff of /libgig/trunk/src/RIFF.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 780 by schoenebeck, Sun Sep 25 13:40:37 2005 UTC revision 1859 by persson, Sun Mar 8 12:24:56 2009 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2009 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25  #include <string.h>  #include <string.h>
 #include <sstream>  
26    
27  #include "RIFF.h"  #include "RIFF.h"
28    
29    #include "helper.h"
30    
31  namespace RIFF {  namespace RIFF {
32    
33  // *************** Helper Functions **************  // *************** Internal functions **************
34  // *  // *
35    
36      template<class T> inline String ToString(T o) {      /// Returns a human readable path of the given chunk.
37          std::stringstream ss;      static String __resolveChunkPath(Chunk* pCk) {
38          ss << o;          String sPath;
39          return ss.str();          for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
40                if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
41                    List* pList = (List*) pChunk;
42                    sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
43                } else {
44                    sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
45                }
46            }
47            return sPath;
48      }      }
49    
50    
# Line 49  namespace RIFF { Line 59  namespace RIFF {
59          ulPos      = 0;          ulPos      = 0;
60          pParent    = NULL;          pParent    = NULL;
61          pChunkData = NULL;          pChunkData = NULL;
62            ulChunkDataSize = 0;
63            ChunkID    = CHUNK_ID_RIFF;
64          this->pFile = pFile;          this->pFile = pFile;
65      }      }
66    
# Line 61  namespace RIFF { Line 73  namespace RIFF {
73          pParent       = Parent;          pParent       = Parent;
74          ulPos         = 0;          ulPos         = 0;
75          pChunkData    = NULL;          pChunkData    = NULL;
76            ulChunkDataSize = 0;
77          ReadHeader(StartPos);          ReadHeader(StartPos);
78      }      }
79    
# Line 70  namespace RIFF { Line 83  namespace RIFF {
83          this->pParent    = pParent;          this->pParent    = pParent;
84          ulPos            = 0;          ulPos            = 0;
85          pChunkData       = NULL;          pChunkData       = NULL;
86            ulChunkDataSize  = 0;
87          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
88          CurrentChunkSize = 0;          CurrentChunkSize = 0;
89          NewChunkSize     = uiBodySize;          NewChunkSize     = uiBodySize;
90      }      }
91    
92      Chunk::~Chunk() {      Chunk::~Chunk() {
93            pFile->UnlogResized(this);
94          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
95      }      }
96    
# Line 87  namespace RIFF { Line 102  namespace RIFF {
102          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
103              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
104              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
105            #elif defined(WIN32)
106            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
107                DWORD dwBytesRead;
108                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
109                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
110          #else          #else
111          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
112              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
# Line 94  namespace RIFF { Line 114  namespace RIFF {
114          #endif // POSIX          #endif // POSIX
115              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
116              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
117                  bEndianNative = false;                  pFile->bEndianNative = false;
118              }              }
119              #else // little endian              #else // little endian
120              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
# Line 135  namespace RIFF { Line 155  namespace RIFF {
155              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
156              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &uiNewChunkSize, 4);
157          }          }
158            #elif defined(WIN32)
159            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
160                DWORD dwBytesWritten;
161                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
162                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
163            }
164          #else          #else
165          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
166              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
# Line 210  namespace RIFF { Line 236  namespace RIFF {
236       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
237       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
238       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
239       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
240       *    possible without SetPos()       *    possible without SetPos()
241       */       */
242      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
# Line 218  namespace RIFF { Line 244  namespace RIFF {
244        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
245        #endif // DEBUG        #endif // DEBUG
246          #if POSIX          #if POSIX
247          if (pFile->hFileRead == 0)    return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
248            #elif defined (WIN32)
249            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
250                return stream_closed;
251          #else          #else
252          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
253          #endif // POSIX          #endif // POSIX
# Line 245  namespace RIFF { Line 274  namespace RIFF {
274         #if DEBUG         #if DEBUG
275         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
276         #endif // DEBUG         #endif // DEBUG
277            if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
278          if (ulPos >= CurrentChunkSize) return 0;          if (ulPos >= CurrentChunkSize) return 0;
279          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
280          #if POSIX          #if POSIX
# Line 252  namespace RIFF { Line 282  namespace RIFF {
282          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
283          if (readWords < 1) return 0;          if (readWords < 1) return 0;
284          readWords /= WordSize;          readWords /= WordSize;
285            #elif defined(WIN32)
286            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
287            DWORD readWords;
288            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
289            if (readWords < 1) return 0;
290            readWords /= WordSize;
291          #else // standard C functions          #else // standard C functions
292          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
293          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
# Line 293  namespace RIFF { Line 329  namespace RIFF {
329       *  @see Resize()       *  @see Resize()
330       */       */
331      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {
332          if (pFile->Mode == stream_mode_read)          if (pFile->Mode != stream_mode_read_write)
333              throw Exception("Writing chunk data in read-only file access mode was attempted");              throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
334          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize >= CurrentChunkSize)          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)
335              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
336          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
337              switch (WordSize) {              switch (WordSize) {
# Line 321  namespace RIFF { Line 357  namespace RIFF {
357          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
358          if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");          if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
359          writtenWords /= WordSize;          writtenWords /= WordSize;
360            #elif defined(WIN32)
361            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
362                throw Exception("Could not seek to position " + ToString(ulPos) +
363                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
364            }
365            DWORD writtenWords;
366            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
367            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
368            writtenWords /= WordSize;
369          #else // standard C functions          #else // standard C functions
370          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
371              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
# Line 667  namespace RIFF { Line 712  namespace RIFF {
712       *       *
713       * <b>Caution:</b> the buffer pointer will be invalidated once       * <b>Caution:</b> the buffer pointer will be invalidated once
714       * File::Save() was called. You have to call LoadChunkData() again to       * File::Save() was called. You have to call LoadChunkData() again to
715       * get a new pointer whenever File::Save() was called.       * get a new, valid pointer whenever File::Save() was called.
716         *
717         * You can call LoadChunkData() again if you previously scheduled to
718         * enlarge this chunk with a Resize() call. In that case the buffer will
719         * be enlarged to the new, scheduled chunk size and you can already
720         * place the new chunk data to the buffer and finally call File::Save()
721         * to enlarge the chunk physically and write the new data in one rush.
722         * This approach is definitely recommended if you have to enlarge and
723         * write new data to a lot of chunks.
724       *       *
725       * @returns a pointer to the data in RAM on success, NULL otherwise       * @returns a pointer to the data in RAM on success, NULL otherwise
726         * @throws Exception if data buffer could not be enlarged
727       * @see ReleaseChunkData()       * @see ReleaseChunkData()
728       */       */
729      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
730          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {
731              #if POSIX              #if POSIX
732              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
733              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
734              if (!pChunkData) return NULL;              if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;
             unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());  
735              #else              #else
736              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
737              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
738                unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
739                pChunkData = new uint8_t[ulBufferSize];
740              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
741                memset(pChunkData, 0, ulBufferSize);
742                #if POSIX
743                unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
744                #elif defined(WIN32)
745                DWORD readWords;
746                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
747                #else
748              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
749              #endif // POSIX              #endif // POSIX
750              if (readWords != GetSize()) {              if (readWords != GetSize()) {
751                  delete[] pChunkData;                  delete[] pChunkData;
752                  return (pChunkData = NULL);                  return (pChunkData = NULL);
753              }              }
754                ulChunkDataSize = ulBufferSize;
755            } else if (NewChunkSize > ulChunkDataSize) {
756                uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
757                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
758                memset(pNewBuffer, 0 , NewChunkSize);
759                memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
760                delete[] pChunkData;
761                pChunkData      = pNewBuffer;
762                ulChunkDataSize = NewChunkSize;
763          }          }
764          return pChunkData;          return pChunkData;
765      }      }
# Line 718  namespace RIFF { Line 789  namespace RIFF {
789       *       *
790       * <b>Caution:</b> You cannot directly write to enlarged chunks before       * <b>Caution:</b> You cannot directly write to enlarged chunks before
791       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
792       * boundary.       * boundary!
793       *       *
794       * @param iNewSize - new chunk body size in bytes (must be greater than zero)       * @param iNewSize - new chunk body size in bytes (must be greater than zero)
795       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a iNewSize is less than 1
796       * @see File::Save()       * @see File::Save()
797       */       */
798      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
799          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0)
800                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
801            if (NewChunkSize == iNewSize) return;
802          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
803          pFile->LogAsResized(this);          pFile->LogAsResized(this);
804      }      }
# Line 743  namespace RIFF { Line 816  namespace RIFF {
816       *          (including its header size of course)       *          (including its header size of course)
817       */       */
818      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
819          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
820          ulWritePos += CHUNK_HEADER_SIZE;          ulWritePos += CHUNK_HEADER_SIZE;
821    
822            if (pFile->Mode != stream_mode_read_write)
823                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
824    
825          // if the whole chunk body was loaded into RAM          // if the whole chunk body was loaded into RAM
826          if (pChunkData) {          if (pChunkData) {
827              // in case the chunk size was changed, reallocate the data in RAM with the chunk's new size              // make sure chunk data buffer in RAM is at least as large as the new chunk size
828              if (NewChunkSize != CurrentChunkSize) {              LoadChunkData();
                 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;  
             }  
   
829              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
830              #if POSIX              #if POSIX
831              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
832              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
833                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
834              }              }
835                #elif defined(WIN32)
836                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
837                DWORD dwBytesWritten;
838                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
839                if (dwBytesWritten != NewChunkSize) {
840                    throw Exception("Writing Chunk data (from RAM) failed");
841                }
842              #else              #else
843              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
844              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 777  namespace RIFF { Line 849  namespace RIFF {
849              // move chunk data from the end of the file to the appropriate position              // move chunk data from the end of the file to the appropriate position
850              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
851              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
852                #if defined(WIN32)
853                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
854                #else
855              int iBytesMoved = 1;              int iBytesMoved = 1;
856                #endif
857              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
858                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
859                  #if POSIX                  #if POSIX
# Line 785  namespace RIFF { Line 861  namespace RIFF {
861                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
862                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
863                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
864                    #elif defined(WIN32)
865                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
866                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
867                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
868                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
869                  #else                  #else
870                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
871                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 806  namespace RIFF { Line 887  namespace RIFF {
887    
888          // add pad byte if needed          // add pad byte if needed
889          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ulStartPos + NewChunkSize) % 2 != 0) {
890              char cPadByte = 0;              const char cPadByte = 0;
891              #if POSIX              #if POSIX
892                lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
893              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
894                #elif defined(WIN32)
895                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
896                DWORD dwBytesWritten;
897                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
898              #else              #else
899                fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
900              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
901              #endif              #endif
902              return ulStartPos + NewChunkSize + 1;              return ulStartPos + NewChunkSize + 1;
# Line 1063  namespace RIFF { Line 1150  namespace RIFF {
1150      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1151          if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");          if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1152          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1153          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, uiBodySize);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1154          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1155          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1156          pFile->ResizedChunks.push_back(pNewChunk);          pNewChunk->Resize(uiBodySize);
1157            NewChunkSize += CHUNK_HEADER_SIZE;
1158            pFile->LogAsResized(this);
1159          return pNewChunk;          return pNewChunk;
1160      }      }
1161    
1162        /** @brief Moves a sub chunk.
1163         *
1164         * Moves a sub chunk from one position in a list to another
1165         * position in the same list. The pSrc chunk is placed before the
1166         * pDst chunk.
1167         *
1168         * @param pSrc - sub chunk to be moved
1169         * @param pDst - the position to move to. pSrc will be placed
1170         *               before pDst. If pDst is 0, pSrc will be placed
1171         *               last in list.
1172         */
1173        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1174            if (!pSubChunks) LoadSubChunks();
1175            pSubChunks->remove(pSrc);
1176            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1177            pSubChunks->insert(iter, pSrc);
1178        }
1179    
1180      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1181       *       *
1182       * Creates and adds a new list sub chunk to this list chunk. Note that       * Creates and adds a new list sub chunk to this list chunk. Note that
# Line 1084  namespace RIFF { Line 1191  namespace RIFF {
1191          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1192          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1193          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1194            NewChunkSize += LIST_HEADER_SIZE;
1195            pFile->LogAsResized(this);
1196          return pNewListChunk;          return pNewListChunk;
1197      }      }
1198    
# Line 1091  namespace RIFF { Line 1200  namespace RIFF {
1200       *       *
1201       * Removes the sub chunk given by \a pSubChunk from this list and frees       * Removes the sub chunk given by \a pSubChunk from this list and frees
1202       * it completely from RAM. The given chunk can either be a normal sub       * it completely from RAM. The given chunk can either be a normal sub
1203       * chunk or a list sub chunk. You should call File::Save() to make this       * chunk or a list sub chunk. In case the given chunk is a list chunk,
1204       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1205         * should call File::Save() to make this change persistent at any time.
1206       *       *
1207       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1208       */       */
# Line 1123  namespace RIFF { Line 1233  namespace RIFF {
1233          #if POSIX          #if POSIX
1234          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1235          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1236            #elif defined(WIN32)
1237            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1238            DWORD dwBytesRead;
1239            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1240          #else          #else
1241          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1242          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1143  namespace RIFF { Line 1257  namespace RIFF {
1257          #if POSIX          #if POSIX
1258          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1259          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1260            #elif defined(WIN32)
1261            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1262            DWORD dwBytesWritten;
1263            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1264          #else          #else
1265          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1266          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
# Line 1156  namespace RIFF { Line 1274  namespace RIFF {
1274          if (!pSubChunks) {          if (!pSubChunks) {
1275              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1276              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1277                #if defined(WIN32)
1278                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1279                #else
1280              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1281                #endif
1282              unsigned long uiOriginalPos = GetPos();              unsigned long uiOriginalPos = GetPos();
1283              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1284              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
# Line 1182  namespace RIFF { Line 1304  namespace RIFF {
1304          }          }
1305      }      }
1306    
1307        void List::LoadSubChunksRecursively() {
1308            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1309                pList->LoadSubChunksRecursively();
1310        }
1311    
1312      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
1313       *       *
1314       * Stores the list chunk persistently to its actual "physical" file. All       * Stores the list chunk persistently to its actual "physical" file. All
# Line 1197  namespace RIFF { Line 1324  namespace RIFF {
1324       *          (including its header size of course)       *          (including its header size of course)
1325       */       */
1326      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1327          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
1328          ulWritePos += LIST_HEADER_SIZE;          ulWritePos += LIST_HEADER_SIZE;
1329    
1330            if (pFile->Mode != stream_mode_read_write)
1331                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1332    
1333          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1334          if (pSubChunks) {          if (pSubChunks) {
1335              for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {              for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
# Line 1211  namespace RIFF { Line 1341  namespace RIFF {
1341          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1342          WriteHeader(ulOriginalPos);          WriteHeader(ulOriginalPos);
1343    
1344            // offset of this list chunk in new written file may have changed
1345            ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1346    
1347          return ulWritePos;          return ulWritePos;
1348      }      }
1349    
# Line 1241  namespace RIFF { Line 1374  namespace RIFF {
1374       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1375       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1376       *       *
1377       * @see AddSubChunk(), AddSubList()       * Note: by default, the RIFF file will be saved in native endian
1378       */       * format; that is, as a RIFF file on little-endian machines and
1379      File::File() : List(this) {       * as a RIFX file on big-endian. To change this behaviour, call
1380         * SetByteOrder() before calling Save().
1381         *
1382         * @param FileType - four-byte identifier of the RIFF file type
1383         * @see AddSubChunk(), AddSubList(), SetByteOrder()
1384         */
1385        File::File(uint32_t FileType) : List(this) {
1386            #if defined(WIN32)
1387            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1388            #else
1389          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1390            #endif
1391            Mode = stream_mode_closed;
1392          bEndianNative = true;          bEndianNative = true;
1393          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1394            ListType = FileType;
1395      }      }
1396    
1397      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1268  namespace RIFF { Line 1413  namespace RIFF {
1413              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1414              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1415          }          }
1416            #elif defined(WIN32)
1417            hFileRead = hFileWrite = CreateFile(
1418                                         path.c_str(), GENERIC_READ,
1419                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1420                                         NULL, OPEN_EXISTING,
1421                                         FILE_ATTRIBUTE_NORMAL |
1422                                         FILE_FLAG_RANDOM_ACCESS, NULL
1423                                     );
1424            if (hFileRead == INVALID_HANDLE_VALUE) {
1425                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1426                throw RIFF::Exception("Can't open \"" + path + "\"");
1427            }
1428          #else          #else
1429          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1430          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1431          #endif // POSIX          #endif // POSIX
1432            Mode = stream_mode_read;
1433          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1434          ReadHeader(0);          ReadHeader(0);
1435          if (ChunkID != CHUNK_ID_RIFF) {          if (ChunkID != CHUNK_ID_RIFF) {
# Line 1308  namespace RIFF { Line 1466  namespace RIFF {
1466                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1467                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1468                      }                      }
1469                        #elif defined(WIN32)
1470                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1471                        hFileRead = hFileWrite = CreateFile(
1472                                                     Filename.c_str(), GENERIC_READ,
1473                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1474                                                     NULL, OPEN_EXISTING,
1475                                                     FILE_ATTRIBUTE_NORMAL |
1476                                                     FILE_FLAG_RANDOM_ACCESS,
1477                                                     NULL
1478                                                 );
1479                        if (hFileRead == INVALID_HANDLE_VALUE) {
1480                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1481                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1482                        }
1483                      #else                      #else
1484                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1485                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1486                      if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                      if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1487                      #endif                      #endif
1488                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1489                      return true;                      break;
1490                  case stream_mode_read_write:                  case stream_mode_read_write:
1491                      #if POSIX                      #if POSIX
1492                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
# Line 1323  namespace RIFF { Line 1495  namespace RIFF {
1495                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1496                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1497                      }                      }
1498                        #elif defined(WIN32)
1499                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1500                        hFileRead = hFileWrite = CreateFile(
1501                                                     Filename.c_str(),
1502                                                     GENERIC_READ | GENERIC_WRITE,
1503                                                     FILE_SHARE_READ,
1504                                                     NULL, OPEN_ALWAYS,
1505                                                     FILE_ATTRIBUTE_NORMAL |
1506                                                     FILE_FLAG_RANDOM_ACCESS,
1507                                                     NULL
1508                                                 );
1509                        if (hFileRead == INVALID_HANDLE_VALUE) {
1510                            hFileRead = hFileWrite = CreateFile(
1511                                                         Filename.c_str(), GENERIC_READ,
1512                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1513                                                         NULL, OPEN_EXISTING,
1514                                                         FILE_ATTRIBUTE_NORMAL |
1515                                                         FILE_FLAG_RANDOM_ACCESS,
1516                                                         NULL
1517                                                     );
1518                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1519                        }
1520                      #else                      #else
1521                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1522                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1523                      if (!hFileRead) {                      if (!hFileRead) {
1524                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1525                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1526                      }                      }
1527                      #endif                      #endif
1528                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1529                      return true;                      break;
1530                    case stream_mode_closed:
1531                        #if POSIX
1532                        if (hFileRead)  close(hFileRead);
1533                        if (hFileWrite) close(hFileWrite);
1534                        #elif defined(WIN32)
1535                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1536                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1537                        #else
1538                        if (hFileRead)  fclose(hFileRead);
1539                        if (hFileWrite) fclose(hFileWrite);
1540                        #endif
1541                        hFileRead = hFileWrite = 0;
1542                        break;
1543                  default:                  default:
1544                      throw Exception("Unknown file access mode");                      throw Exception("Unknown file access mode");
1545              }              }
1546                Mode = NewMode;
1547                return true;
1548          }          }
1549          return false;          return false;
1550      }      }
1551    
1552        /** @brief Set the byte order to be used when saving.
1553         *
1554         * Set the byte order to be used in the file. A value of
1555         * endian_little will create a RIFF file, endian_big a RIFX file
1556         * and endian_native will create a RIFF file on little-endian
1557         * machines and RIFX on big-endian machines.
1558         *
1559         * @param Endian - endianess to use when file is saved.
1560         */
1561        void File::SetByteOrder(endian_t Endian) {
1562            #if WORDS_BIGENDIAN
1563            bEndianNative = Endian != endian_little;
1564            #else
1565            bEndianNative = Endian != endian_big;
1566            #endif
1567        }
1568    
1569      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1570       *       *
1571       * Make all changes of all chunks persistent by writing them to the       * Make all changes of all chunks persistent by writing them to the
# Line 1351  namespace RIFF { Line 1577  namespace RIFF {
1577       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1578       */       */
1579      void File::Save() {      void File::Save() {
1580            // make sure the RIFF tree is built (from the original file)
1581            LoadSubChunksRecursively();
1582    
1583          // reopen file in write mode          // reopen file in write mode
1584          bool bModeWasChanged = SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1585    
1586          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
1587          // RAM and without having to store the data in a temporary file, we          // RAM and without having to store the data in a temporary file, we
# Line 1363  namespace RIFF { Line 1592  namespace RIFF {
1592    
1593          // first we sum up all positive chunk size changes (and skip all negative ones)          // first we sum up all positive chunk size changes (and skip all negative ones)
1594          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1595          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          for (std::set<Chunk*>::const_iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1596              if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)");              if ((*iter)->GetNewSize() == 0) {
1597              unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte                  throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
1598              if (ulDiff > 0) ulPositiveSizeDiff += ulDiff;              }
1599                unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1600                unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1601                if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1602          }          }
1603    
1604          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1379  namespace RIFF { Line 1611  namespace RIFF {
1611              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1612              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1613              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1614                #if defined(WIN32)
1615                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1616                #else
1617              int iBytesMoved = 1;              int iBytesMoved = 1;
1618              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              #endif
1619                  const unsigned long ulToMove = ulFileSize - ulPos;              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1620                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1621                    ulPos -= iBytesMoved;
1622                  #if POSIX                  #if POSIX
1623                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ulPos, SEEK_SET);
1624                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1625                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1626                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1627                    #elif defined(WIN32)
1628                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1629                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1630                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1631                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1632                  #else                  #else
1633                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1634                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
# Line 1400  namespace RIFF { Line 1641  namespace RIFF {
1641          }          }
1642    
1643          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree
1644          unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff);          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);
1645            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1646    
1647          // resize file to the final size          // resize file to the final size
1648          if (ulTotalSize < ulWorkingFileSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1649    
1650          // forget all resized chunks          // forget all resized chunks
1651          ResizedChunks.clear();          ResizedChunks.clear();
   
         // reopen file in read mode  
         if (bModeWasChanged) SetMode(stream_mode_read);  
1652      }      }
1653    
1654      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1417  namespace RIFF { Line 1656  namespace RIFF {
1656       * Make all changes of all chunks persistent by writing them to another       * Make all changes of all chunks persistent by writing them to another
1657       * file. <b>Caution:</b> this method is optimized for writing to       * file. <b>Caution:</b> this method is optimized for writing to
1658       * <b>another</b> file, do not use it to save the changes to the same       * <b>another</b> file, do not use it to save the changes to the same
1659       * file! Use File::Save() in that case instead!       * file! Use File::Save() in that case instead! Ignoring this might
1660         * result in a corrupted file, especially in case chunks were resized!
1661       *       *
1662       * After calling this method, this File object will be associated with       * After calling this method, this File object will be associated with
1663       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
# Line 1425  namespace RIFF { Line 1665  namespace RIFF {
1665       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1666       */       */
1667      void File::Save(const String& path) {      void File::Save(const String& path) {
1668            //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
1669    
1670            // make sure the RIFF tree is built (from the original file)
1671            LoadSubChunksRecursively();
1672    
1673            if (Filename.length() > 0) SetMode(stream_mode_read);
1674          // open the other (new) file for writing and truncate it to zero size          // open the other (new) file for writing and truncate it to zero size
1675          #if POSIX          #if POSIX
1676          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);
1677          if (hFileWrite < 0) {          if (hFileWrite < 0) {
1678              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1679              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1680          }          }
1681            #elif defined(WIN32)
1682            hFileWrite = CreateFile(
1683                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1684                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1685                             FILE_FLAG_RANDOM_ACCESS, NULL
1686                         );
1687            if (hFileWrite == INVALID_HANDLE_VALUE) {
1688                hFileWrite = hFileRead;
1689                throw Exception("Could not open file \"" + path + "\" for writing");
1690            }
1691          #else          #else
1692          hFileWrite = fopen(path.c_str(), "w+b");          hFileWrite = fopen(path.c_str(), "w+b");
1693          if (!hFileWrite) {          if (!hFileWrite) {
# Line 1439  namespace RIFF { Line 1695  namespace RIFF {
1695              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1696          }          }
1697          #endif // POSIX          #endif // POSIX
1698            Mode = stream_mode_read_write;
1699    
1700          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
1701          WriteChunk(0, 0);          unsigned long ulTotalSize  = WriteChunk(0, 0);
1702            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1703    
1704            // resize file to the final size (if the file was originally larger)
1705            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1706    
1707          // forget all resized chunks          // forget all resized chunks
1708          ResizedChunks.clear();          ResizedChunks.clear();
1709    
1710            #if POSIX
1711            if (hFileWrite) close(hFileWrite);
1712            #elif defined(WIN32)
1713            if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1714            #else
1715            if (hFileWrite) fclose(hFileWrite);
1716            #endif
1717            hFileWrite = hFileRead;
1718    
1719          // associate new file with this File object from now on          // associate new file with this File object from now on
1720          Filename = path;          Filename = path;
1721          stream_mode_t oldMode = Mode;          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1722          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.
         SetMode(oldMode);          // ... so SetMode() has to reopen the file handles.  
1723      }      }
1724    
1725      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(unsigned long ulNewSize) {
1726          #if POSIX          #if POSIX
1727          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1728              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1729            #elif defined(WIN32)
1730            if (
1731                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1732                !SetEndOfFile(hFileWrite)
1733            ) throw Exception("Could not resize file \"" + Filename + "\"");
1734          #else          #else
1735          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1736          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1737          #endif          #endif
1738      }      }
1739    
# Line 1469  namespace RIFF { Line 1743  namespace RIFF {
1743         #endif // DEBUG         #endif // DEBUG
1744          #if POSIX          #if POSIX
1745          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1746            #elif defined(WIN32)
1747            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1748          #else          #else
1749          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1750          #endif // POSIX          #endif // POSIX
1751      }      }
1752    
1753      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {
1754          ResizedChunks.push_back(pResizedChunk);          ResizedChunks.insert(pResizedChunk);
1755        }
1756    
1757        void File::UnlogResized(Chunk* pResizedChunk) {
1758            ResizedChunks.erase(pResizedChunk);
1759      }      }
1760    
1761      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
1762          #if POSIX          return __GetFileSize(hFileRead);
1763        }
1764    
1765        #if POSIX
1766        unsigned long File::__GetFileSize(int hFile) {
1767          struct stat filestat;          struct stat filestat;
1768          fstat(hFileRead, &filestat);          fstat(hFile, &filestat);
1769          long size = filestat.st_size;          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  
1770          return size;          return size;
1771      }      }
1772        #elif defined(WIN32)
1773        unsigned long File::__GetFileSize(HANDLE hFile) {
1774            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1775            if (dwSize == INVALID_FILE_SIZE)
1776                throw Exception("Windows FS error: could not determine file size");
1777            return dwSize;
1778        }
1779        #else // standard C functions
1780        unsigned long File::__GetFileSize(FILE* hFile) {
1781            long curpos = ftell(hFile);
1782            fseek(hFile, 0, SEEK_END);
1783            long size = ftell(hFile);
1784            fseek(hFile, curpos, SEEK_SET);
1785            return size;
1786        }
1787        #endif
1788    
1789    
1790  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.780  
changed lines
  Added in v.1859

  ViewVC Help
Powered by ViewVC