/[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 2120 by persson, Sun Aug 29 11:10:36 2010 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 <set>
26  #include <string.h>  #include <string.h>
 #include <sstream>  
27    
28  #include "RIFF.h"  #include "RIFF.h"
29    
30    #include "helper.h"
31    
32  namespace RIFF {  namespace RIFF {
33    
34  // *************** Helper Functions **************  // *************** Internal functions **************
35  // *  // *
36    
37      template<class T> inline String ToString(T o) {      /// Returns a human readable path of the given chunk.
38          std::stringstream ss;      static String __resolveChunkPath(Chunk* pCk) {
39          ss << o;          String sPath;
40          return ss.str();          for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
41                if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
42                    List* pList = (List*) pChunk;
43                    sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
44                } else {
45                    sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
46                }
47            }
48            return sPath;
49      }      }
50    
51    
# Line 49  namespace RIFF { Line 60  namespace RIFF {
60          ulPos      = 0;          ulPos      = 0;
61          pParent    = NULL;          pParent    = NULL;
62          pChunkData = NULL;          pChunkData = NULL;
63            CurrentChunkSize = 0;
64            NewChunkSize = 0;
65            ulChunkDataSize = 0;
66            ChunkID    = CHUNK_ID_RIFF;
67          this->pFile = pFile;          this->pFile = pFile;
68      }      }
69    
# Line 61  namespace RIFF { Line 76  namespace RIFF {
76          pParent       = Parent;          pParent       = Parent;
77          ulPos         = 0;          ulPos         = 0;
78          pChunkData    = NULL;          pChunkData    = NULL;
79            CurrentChunkSize = 0;
80            NewChunkSize = 0;
81            ulChunkDataSize = 0;
82          ReadHeader(StartPos);          ReadHeader(StartPos);
83      }      }
84    
# Line 71  namespace RIFF { Line 89  namespace RIFF {
89          ulPos            = 0;          ulPos            = 0;
90          pChunkData       = NULL;          pChunkData       = NULL;
91          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
92            ulChunkDataSize  = 0;
93          CurrentChunkSize = 0;          CurrentChunkSize = 0;
94          NewChunkSize     = uiBodySize;          NewChunkSize     = uiBodySize;
95      }      }
96    
97      Chunk::~Chunk() {      Chunk::~Chunk() {
98            if (pFile) pFile->UnlogResized(this);
99          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
100      }      }
101    
# Line 83  namespace RIFF { Line 103  namespace RIFF {
103          #if DEBUG          #if DEBUG
104          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << fPos << ") ";
105          #endif // DEBUG          #endif // DEBUG
106            ChunkID = 0;
107            NewChunkSize = CurrentChunkSize = 0;
108          #if POSIX          #if POSIX
109          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
110              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
111              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
112            #elif defined(WIN32)
113            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
114                DWORD dwBytesRead;
115                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
116                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
117          #else          #else
118          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
119              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
# Line 94  namespace RIFF { Line 121  namespace RIFF {
121          #endif // POSIX          #endif // POSIX
122              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
123              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
124                  bEndianNative = false;                  pFile->bEndianNative = false;
125              }              }
126              #else // little endian              #else // little endian
127              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
# Line 108  namespace RIFF { Line 135  namespace RIFF {
135              }              }
136              #if DEBUG              #if DEBUG
137              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
138              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << CurrentChunkSize << " ";
139              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
140              #endif // DEBUG              #endif // DEBUG
141              NewChunkSize = CurrentChunkSize;              NewChunkSize = CurrentChunkSize;
142          }          }
# Line 135  namespace RIFF { Line 162  namespace RIFF {
162              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
163              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &uiNewChunkSize, 4);
164          }          }
165            #elif defined(WIN32)
166            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
167                DWORD dwBytesWritten;
168                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
169                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
170            }
171          #else          #else
172          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
173              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
# Line 199  namespace RIFF { Line 232  namespace RIFF {
232         #if DEBUG         #if DEBUG
233         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;
234         #endif // DEBUG         #endif // DEBUG
235          return CurrentChunkSize - ulPos;          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;
236      }      }
237    
238      /**      /**
# Line 210  namespace RIFF { Line 243  namespace RIFF {
243       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
244       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
245       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
246       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
247       *    possible without SetPos()       *    possible without SetPos()
248       */       */
249      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
# Line 218  namespace RIFF { Line 251  namespace RIFF {
251        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
252        #endif // DEBUG        #endif // DEBUG
253          #if POSIX          #if POSIX
254          if (pFile->hFileRead == 0)    return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
255            #elif defined (WIN32)
256            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
257                return stream_closed;
258          #else          #else
259          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
260          #endif // POSIX          #endif // POSIX
# Line 245  namespace RIFF { Line 281  namespace RIFF {
281         #if DEBUG         #if DEBUG
282         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
283         #endif // DEBUG         #endif // DEBUG
284            if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
285          if (ulPos >= CurrentChunkSize) return 0;          if (ulPos >= CurrentChunkSize) return 0;
286          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
287          #if POSIX          #if POSIX
# Line 252  namespace RIFF { Line 289  namespace RIFF {
289          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
290          if (readWords < 1) return 0;          if (readWords < 1) return 0;
291          readWords /= WordSize;          readWords /= WordSize;
292            #elif defined(WIN32)
293            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
294            DWORD readWords;
295            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
296            if (readWords < 1) return 0;
297            readWords /= WordSize;
298          #else // standard C functions          #else // standard C functions
299          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
300          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
# Line 293  namespace RIFF { Line 336  namespace RIFF {
336       *  @see Resize()       *  @see Resize()
337       */       */
338      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {
339          if (pFile->Mode == stream_mode_read)          if (pFile->Mode != stream_mode_read_write)
340              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");
341          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize >= CurrentChunkSize)          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)
342              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
343          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
344              switch (WordSize) {              switch (WordSize) {
# Line 321  namespace RIFF { Line 364  namespace RIFF {
364          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
365          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");
366          writtenWords /= WordSize;          writtenWords /= WordSize;
367            #elif defined(WIN32)
368            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
369                throw Exception("Could not seek to position " + ToString(ulPos) +
370                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
371            }
372            DWORD writtenWords;
373            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
374            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
375            writtenWords /= WordSize;
376          #else // standard C functions          #else // standard C functions
377          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
378              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
# Line 667  namespace RIFF { Line 719  namespace RIFF {
719       *       *
720       * <b>Caution:</b> the buffer pointer will be invalidated once       * <b>Caution:</b> the buffer pointer will be invalidated once
721       * File::Save() was called. You have to call LoadChunkData() again to       * File::Save() was called. You have to call LoadChunkData() again to
722       * get a new pointer whenever File::Save() was called.       * get a new, valid pointer whenever File::Save() was called.
723         *
724         * You can call LoadChunkData() again if you previously scheduled to
725         * enlarge this chunk with a Resize() call. In that case the buffer will
726         * be enlarged to the new, scheduled chunk size and you can already
727         * place the new chunk data to the buffer and finally call File::Save()
728         * to enlarge the chunk physically and write the new data in one rush.
729         * This approach is definitely recommended if you have to enlarge and
730         * write new data to a lot of chunks.
731       *       *
732       * @returns a pointer to the data in RAM on success, NULL otherwise       * @returns a pointer to the data in RAM on success, NULL otherwise
733         * @throws Exception if data buffer could not be enlarged
734       * @see ReleaseChunkData()       * @see ReleaseChunkData()
735       */       */
736      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
737          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {
738              #if POSIX              #if POSIX
739              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
740              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
741              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());  
742              #else              #else
743              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
744              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
745                unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
746                pChunkData = new uint8_t[ulBufferSize];
747              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
748                memset(pChunkData, 0, ulBufferSize);
749                #if POSIX
750                unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
751                #elif defined(WIN32)
752                DWORD readWords;
753                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
754                #else
755              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
756              #endif // POSIX              #endif // POSIX
757              if (readWords != GetSize()) {              if (readWords != GetSize()) {
758                  delete[] pChunkData;                  delete[] pChunkData;
759                  return (pChunkData = NULL);                  return (pChunkData = NULL);
760              }              }
761                ulChunkDataSize = ulBufferSize;
762            } else if (NewChunkSize > ulChunkDataSize) {
763                uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
764                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
765                memset(pNewBuffer, 0 , NewChunkSize);
766                memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
767                delete[] pChunkData;
768                pChunkData      = pNewBuffer;
769                ulChunkDataSize = NewChunkSize;
770          }          }
771          return pChunkData;          return pChunkData;
772      }      }
# Line 718  namespace RIFF { Line 796  namespace RIFF {
796       *       *
797       * <b>Caution:</b> You cannot directly write to enlarged chunks before       * <b>Caution:</b> You cannot directly write to enlarged chunks before
798       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
799       * boundary.       * boundary!
800       *       *
801       * @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)
802       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a iNewSize is less than 1
803       * @see File::Save()       * @see File::Save()
804       */       */
805      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
806          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0)
807                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
808            if (NewChunkSize == iNewSize) return;
809          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
810          pFile->LogAsResized(this);          pFile->LogAsResized(this);
811      }      }
# Line 743  namespace RIFF { Line 823  namespace RIFF {
823       *          (including its header size of course)       *          (including its header size of course)
824       */       */
825      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
826          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
827          ulWritePos += CHUNK_HEADER_SIZE;          ulWritePos += CHUNK_HEADER_SIZE;
828    
829            if (pFile->Mode != stream_mode_read_write)
830                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
831    
832          // if the whole chunk body was loaded into RAM          // if the whole chunk body was loaded into RAM
833          if (pChunkData) {          if (pChunkData) {
834              // 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
835              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;  
             }  
   
836              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
837              #if POSIX              #if POSIX
838              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
839              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
840                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
841              }              }
842                #elif defined(WIN32)
843                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
844                DWORD dwBytesWritten;
845                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
846                if (dwBytesWritten != NewChunkSize) {
847                    throw Exception("Writing Chunk data (from RAM) failed");
848                }
849              #else              #else
850              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
851              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 777  namespace RIFF { Line 856  namespace RIFF {
856              // 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
857              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
858              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
859                #if defined(WIN32)
860                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
861                #else
862              int iBytesMoved = 1;              int iBytesMoved = 1;
863              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              #endif
864                for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
865                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
866                  #if POSIX                  #if POSIX
867                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
868                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
869                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
870                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
871                    #elif defined(WIN32)
872                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
873                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
874                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
875                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
876                  #else                  #else
877                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
878                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 806  namespace RIFF { Line 894  namespace RIFF {
894    
895          // add pad byte if needed          // add pad byte if needed
896          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ulStartPos + NewChunkSize) % 2 != 0) {
897              char cPadByte = 0;              const char cPadByte = 0;
898              #if POSIX              #if POSIX
899                lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
900              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
901                #elif defined(WIN32)
902                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
903                DWORD dwBytesWritten;
904                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
905              #else              #else
906                fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
907              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
908              #endif              #endif
909              return ulStartPos + NewChunkSize + 1;              return ulStartPos + NewChunkSize + 1;
# Line 857  namespace RIFF { Line 951  namespace RIFF {
951        #if DEBUG        #if DEBUG
952        std::cout << "List::~List()" << std::endl;        std::cout << "List::~List()" << std::endl;
953        #endif // DEBUG        #endif // DEBUG
954            DeleteChunkList();
955        }
956    
957        void List::DeleteChunkList() {
958          if (pSubChunks) {          if (pSubChunks) {
959              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
960              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 865  namespace RIFF { Line 963  namespace RIFF {
963                  iter++;                  iter++;
964              }              }
965              delete pSubChunks;              delete pSubChunks;
966                pSubChunks = NULL;
967            }
968            if (pSubChunksMap) {
969                delete pSubChunksMap;
970                pSubChunksMap = NULL;
971          }          }
         if (pSubChunksMap) delete pSubChunksMap;  
972      }      }
973    
974      /**      /**
# Line 1063  namespace RIFF { Line 1165  namespace RIFF {
1165      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1166          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");
1167          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1168          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, uiBodySize);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1169          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1170          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1171          pFile->ResizedChunks.push_back(pNewChunk);          pNewChunk->Resize(uiBodySize);
1172            NewChunkSize += CHUNK_HEADER_SIZE;
1173            pFile->LogAsResized(this);
1174          return pNewChunk;          return pNewChunk;
1175      }      }
1176    
1177        /** @brief Moves a sub chunk.
1178         *
1179         * Moves a sub chunk from one position in a list to another
1180         * position in the same list. The pSrc chunk is placed before the
1181         * pDst chunk.
1182         *
1183         * @param pSrc - sub chunk to be moved
1184         * @param pDst - the position to move to. pSrc will be placed
1185         *               before pDst. If pDst is 0, pSrc will be placed
1186         *               last in list.
1187         */
1188        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1189            if (!pSubChunks) LoadSubChunks();
1190            pSubChunks->remove(pSrc);
1191            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1192            pSubChunks->insert(iter, pSrc);
1193        }
1194    
1195      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1196       *       *
1197       * 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 1206  namespace RIFF {
1206          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1207          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1208          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1209            NewChunkSize += LIST_HEADER_SIZE;
1210            pFile->LogAsResized(this);
1211          return pNewListChunk;          return pNewListChunk;
1212      }      }
1213    
# Line 1091  namespace RIFF { Line 1215  namespace RIFF {
1215       *       *
1216       * 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
1217       * 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
1218       * 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,
1219       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1220         * should call File::Save() to make this change persistent at any time.
1221       *       *
1222       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1223       */       */
# Line 1119  namespace RIFF { Line 1244  namespace RIFF {
1244        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1245        #endif // DEBUG        #endif // DEBUG
1246          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1247            if (CurrentChunkSize < 4) return;
1248          NewChunkSize = CurrentChunkSize -= 4;          NewChunkSize = CurrentChunkSize -= 4;
1249          #if POSIX          #if POSIX
1250          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1251          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1252            #elif defined(WIN32)
1253            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1254            DWORD dwBytesRead;
1255            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1256          #else          #else
1257          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1258          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1143  namespace RIFF { Line 1273  namespace RIFF {
1273          #if POSIX          #if POSIX
1274          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1275          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1276            #elif defined(WIN32)
1277            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1278            DWORD dwBytesWritten;
1279            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1280          #else          #else
1281          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1282          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
# Line 1156  namespace RIFF { Line 1290  namespace RIFF {
1290          if (!pSubChunks) {          if (!pSubChunks) {
1291              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1292              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1293                #if defined(WIN32)
1294                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1295                #else
1296              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1297                #endif
1298              unsigned long uiOriginalPos = GetPos();              unsigned long uiOriginalPos = GetPos();
1299              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1300              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
# Line 1182  namespace RIFF { Line 1320  namespace RIFF {
1320          }          }
1321      }      }
1322    
1323        void List::LoadSubChunksRecursively() {
1324            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1325                pList->LoadSubChunksRecursively();
1326        }
1327    
1328      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
1329       *       *
1330       * 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 1340  namespace RIFF {
1340       *          (including its header size of course)       *          (including its header size of course)
1341       */       */
1342      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1343          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
1344          ulWritePos += LIST_HEADER_SIZE;          ulWritePos += LIST_HEADER_SIZE;
1345    
1346            if (pFile->Mode != stream_mode_read_write)
1347                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1348    
1349          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1350          if (pSubChunks) {          if (pSubChunks) {
1351              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 1357  namespace RIFF {
1357          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1358          WriteHeader(ulOriginalPos);          WriteHeader(ulOriginalPos);
1359    
1360            // offset of this list chunk in new written file may have changed
1361            ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1362    
1363          return ulWritePos;          return ulWritePos;
1364      }      }
1365    
# Line 1235  namespace RIFF { Line 1384  namespace RIFF {
1384  // *************** File ***************  // *************** File ***************
1385  // *  // *
1386    
1387    //HACK: to avoid breaking DLL compatibility to older versions of libgig we roll the new std::set<Chunk*> into the old std::list<Chunk*> container, should be replaced on member variable level soon though
1388    #define _GET_RESIZED_CHUNKS() \
1389            (reinterpret_cast<std::set<Chunk*>*>(ResizedChunks.front()))
1390    
1391      /** @brief Create new RIFF file.      /** @brief Create new RIFF file.
1392       *       *
1393       * Use this constructor if you want to create a new RIFF file completely       * Use this constructor if you want to create a new RIFF file completely
1394       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1395       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1396       *       *
1397       * @see AddSubChunk(), AddSubList()       * Note: by default, the RIFF file will be saved in native endian
1398       */       * format; that is, as a RIFF file on little-endian machines and
1399      File::File() : List(this) {       * as a RIFX file on big-endian. To change this behaviour, call
1400         * SetByteOrder() before calling Save().
1401         *
1402         * @param FileType - four-byte identifier of the RIFF file type
1403         * @see AddSubChunk(), AddSubList(), SetByteOrder()
1404         */
1405        File::File(uint32_t FileType) : List(this) {
1406            //HACK: see _GET_RESIZED_CHUNKS() comment
1407            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1408            #if defined(WIN32)
1409            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1410            #else
1411          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1412            #endif
1413            Mode = stream_mode_closed;
1414          bEndianNative = true;          bEndianNative = true;
1415          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1416            ListType = FileType;
1417      }      }
1418    
1419      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1262  namespace RIFF { Line 1429  namespace RIFF {
1429        std::cout << "File::File("<<path<<")" << std::endl;        std::cout << "File::File("<<path<<")" << std::endl;
1430        #endif // DEBUG        #endif // DEBUG
1431          bEndianNative = true;          bEndianNative = true;
1432            //HACK: see _GET_RESIZED_CHUNKS() comment
1433            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1434          #if POSIX          #if POSIX
1435          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1436          if (hFileRead <= 0) {          if (hFileRead <= 0) {
1437              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1438              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1439          }          }
1440            #elif defined(WIN32)
1441            hFileRead = hFileWrite = CreateFile(
1442                                         path.c_str(), GENERIC_READ,
1443                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1444                                         NULL, OPEN_EXISTING,
1445                                         FILE_ATTRIBUTE_NORMAL |
1446                                         FILE_FLAG_RANDOM_ACCESS, NULL
1447                                     );
1448            if (hFileRead == INVALID_HANDLE_VALUE) {
1449                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1450                throw RIFF::Exception("Can't open \"" + path + "\"");
1451            }
1452          #else          #else
1453          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1454          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1455          #endif // POSIX          #endif // POSIX
1456            Mode = stream_mode_read;
1457          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1458          ReadHeader(0);          ReadHeader(0);
1459          if (ChunkID != CHUNK_ID_RIFF) {          if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1460              throw RIFF::Exception("Not a RIFF file");              throw RIFF::Exception("Not a RIFF file");
1461          }          }
1462      }      }
# Line 1308  namespace RIFF { Line 1490  namespace RIFF {
1490                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1491                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1492                      }                      }
1493                        #elif defined(WIN32)
1494                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1495                        hFileRead = hFileWrite = CreateFile(
1496                                                     Filename.c_str(), GENERIC_READ,
1497                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1498                                                     NULL, OPEN_EXISTING,
1499                                                     FILE_ATTRIBUTE_NORMAL |
1500                                                     FILE_FLAG_RANDOM_ACCESS,
1501                                                     NULL
1502                                                 );
1503                        if (hFileRead == INVALID_HANDLE_VALUE) {
1504                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1505                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1506                        }
1507                      #else                      #else
1508                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1509                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1510                      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");
1511                      #endif                      #endif
1512                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1513                      return true;                      break;
1514                  case stream_mode_read_write:                  case stream_mode_read_write:
1515                      #if POSIX                      #if POSIX
1516                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
# Line 1323  namespace RIFF { Line 1519  namespace RIFF {
1519                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1520                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1521                      }                      }
1522                        #elif defined(WIN32)
1523                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1524                        hFileRead = hFileWrite = CreateFile(
1525                                                     Filename.c_str(),
1526                                                     GENERIC_READ | GENERIC_WRITE,
1527                                                     FILE_SHARE_READ,
1528                                                     NULL, OPEN_ALWAYS,
1529                                                     FILE_ATTRIBUTE_NORMAL |
1530                                                     FILE_FLAG_RANDOM_ACCESS,
1531                                                     NULL
1532                                                 );
1533                        if (hFileRead == INVALID_HANDLE_VALUE) {
1534                            hFileRead = hFileWrite = CreateFile(
1535                                                         Filename.c_str(), GENERIC_READ,
1536                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1537                                                         NULL, OPEN_EXISTING,
1538                                                         FILE_ATTRIBUTE_NORMAL |
1539                                                         FILE_FLAG_RANDOM_ACCESS,
1540                                                         NULL
1541                                                     );
1542                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1543                        }
1544                      #else                      #else
1545                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1546                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1547                      if (!hFileRead) {                      if (!hFileRead) {
1548                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1549                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1550                      }                      }
1551                      #endif                      #endif
1552                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1553                      return true;                      break;
1554                    case stream_mode_closed:
1555                        #if POSIX
1556                        if (hFileRead)  close(hFileRead);
1557                        if (hFileWrite) close(hFileWrite);
1558                        #elif defined(WIN32)
1559                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1560                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1561                        #else
1562                        if (hFileRead)  fclose(hFileRead);
1563                        if (hFileWrite) fclose(hFileWrite);
1564                        #endif
1565                        hFileRead = hFileWrite = 0;
1566                        break;
1567                  default:                  default:
1568                      throw Exception("Unknown file access mode");                      throw Exception("Unknown file access mode");
1569              }              }
1570                Mode = NewMode;
1571                return true;
1572          }          }
1573          return false;          return false;
1574      }      }
1575    
1576        /** @brief Set the byte order to be used when saving.
1577         *
1578         * Set the byte order to be used in the file. A value of
1579         * endian_little will create a RIFF file, endian_big a RIFX file
1580         * and endian_native will create a RIFF file on little-endian
1581         * machines and RIFX on big-endian machines.
1582         *
1583         * @param Endian - endianess to use when file is saved.
1584         */
1585        void File::SetByteOrder(endian_t Endian) {
1586            #if WORDS_BIGENDIAN
1587            bEndianNative = Endian != endian_little;
1588            #else
1589            bEndianNative = Endian != endian_big;
1590            #endif
1591        }
1592    
1593      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1594       *       *
1595       * 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 1601  namespace RIFF {
1601       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1602       */       */
1603      void File::Save() {      void File::Save() {
1604            // make sure the RIFF tree is built (from the original file)
1605            LoadSubChunksRecursively();
1606    
1607          // reopen file in write mode          // reopen file in write mode
1608          bool bModeWasChanged = SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1609    
1610          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
1611          // 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 1616  namespace RIFF {
1616    
1617          // 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)
1618          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1619          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          std::set<Chunk*>* resizedChunks = _GET_RESIZED_CHUNKS();
1620              if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)");          for (std::set<Chunk*>::const_iterator iter = resizedChunks->begin(), end = resizedChunks->end(); iter != end; ++iter) {
1621              unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte              if ((*iter)->GetNewSize() == 0) {
1622              if (ulDiff > 0) ulPositiveSizeDiff += ulDiff;                  throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
1623                }
1624                unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1625                unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1626                if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1627          }          }
1628    
1629          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1379  namespace RIFF { Line 1636  namespace RIFF {
1636              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1637              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1638              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1639                #if defined(WIN32)
1640                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1641                #else
1642              int iBytesMoved = 1;              int iBytesMoved = 1;
1643              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              #endif
1644                  const unsigned long ulToMove = ulFileSize - ulPos;              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1645                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1646                    ulPos -= iBytesMoved;
1647                  #if POSIX                  #if POSIX
1648                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ulPos, SEEK_SET);
1649                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1650                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1651                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1652                    #elif defined(WIN32)
1653                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1654                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1655                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1656                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1657                  #else                  #else
1658                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1659                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
# Line 1400  namespace RIFF { Line 1666  namespace RIFF {
1666          }          }
1667    
1668          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree
1669          unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff);          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);
1670            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1671    
1672          // resize file to the final size          // resize file to the final size
1673          if (ulTotalSize < ulWorkingFileSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1674    
1675          // forget all resized chunks          // forget all resized chunks
1676          ResizedChunks.clear();          resizedChunks->clear();
   
         // reopen file in read mode  
         if (bModeWasChanged) SetMode(stream_mode_read);  
1677      }      }
1678    
1679      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1417  namespace RIFF { Line 1681  namespace RIFF {
1681       * Make all changes of all chunks persistent by writing them to another       * Make all changes of all chunks persistent by writing them to another
1682       * file. <b>Caution:</b> this method is optimized for writing to       * file. <b>Caution:</b> this method is optimized for writing to
1683       * <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
1684       * file! Use File::Save() in that case instead!       * file! Use File::Save() in that case instead! Ignoring this might
1685         * result in a corrupted file, especially in case chunks were resized!
1686       *       *
1687       * After calling this method, this File object will be associated with       * After calling this method, this File object will be associated with
1688       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
# Line 1425  namespace RIFF { Line 1690  namespace RIFF {
1690       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1691       */       */
1692      void File::Save(const String& path) {      void File::Save(const String& path) {
1693            //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
1694    
1695            // make sure the RIFF tree is built (from the original file)
1696            LoadSubChunksRecursively();
1697    
1698            if (Filename.length() > 0) SetMode(stream_mode_read);
1699          // 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
1700          #if POSIX          #if POSIX
1701          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);
1702          if (hFileWrite < 0) {          if (hFileWrite < 0) {
1703              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1704              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1705          }          }
1706            #elif defined(WIN32)
1707            hFileWrite = CreateFile(
1708                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1709                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1710                             FILE_FLAG_RANDOM_ACCESS, NULL
1711                         );
1712            if (hFileWrite == INVALID_HANDLE_VALUE) {
1713                hFileWrite = hFileRead;
1714                throw Exception("Could not open file \"" + path + "\" for writing");
1715            }
1716          #else          #else
1717          hFileWrite = fopen(path.c_str(), "w+b");          hFileWrite = fopen(path.c_str(), "w+b");
1718          if (!hFileWrite) {          if (!hFileWrite) {
# Line 1439  namespace RIFF { Line 1720  namespace RIFF {
1720              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1721          }          }
1722          #endif // POSIX          #endif // POSIX
1723            Mode = stream_mode_read_write;
1724    
1725          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
1726          WriteChunk(0, 0);          unsigned long ulTotalSize  = WriteChunk(0, 0);
1727            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1728    
1729            // resize file to the final size (if the file was originally larger)
1730            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1731    
1732          // forget all resized chunks          // forget all resized chunks
1733          ResizedChunks.clear();          _GET_RESIZED_CHUNKS()->clear();
1734    
1735            #if POSIX
1736            if (hFileWrite) close(hFileWrite);
1737            #elif defined(WIN32)
1738            if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1739            #else
1740            if (hFileWrite) fclose(hFileWrite);
1741            #endif
1742            hFileWrite = hFileRead;
1743    
1744          // associate new file with this File object from now on          // associate new file with this File object from now on
1745          Filename = path;          Filename = path;
1746          stream_mode_t oldMode = Mode;          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1747          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.  
1748      }      }
1749    
1750      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(unsigned long ulNewSize) {
1751          #if POSIX          #if POSIX
1752          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1753              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1754            #elif defined(WIN32)
1755            if (
1756                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1757                !SetEndOfFile(hFileWrite)
1758            ) throw Exception("Could not resize file \"" + Filename + "\"");
1759          #else          #else
1760          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1761          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1762          #endif          #endif
1763      }      }
1764    
# Line 1469  namespace RIFF { Line 1768  namespace RIFF {
1768         #endif // DEBUG         #endif // DEBUG
1769          #if POSIX          #if POSIX
1770          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1771            #elif defined(WIN32)
1772            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1773          #else          #else
1774          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1775          #endif // POSIX          #endif // POSIX
1776            DeleteChunkList();
1777            pFile = NULL;
1778            //HACK: see _GET_RESIZED_CHUNKS() comment
1779            delete _GET_RESIZED_CHUNKS();
1780      }      }
1781    
1782      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {
1783          ResizedChunks.push_back(pResizedChunk);          _GET_RESIZED_CHUNKS()->insert(pResizedChunk);
1784        }
1785    
1786        void File::UnlogResized(Chunk* pResizedChunk) {
1787            _GET_RESIZED_CHUNKS()->erase(pResizedChunk);
1788      }      }
1789    
1790      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
1791          #if POSIX          return __GetFileSize(hFileRead);
1792        }
1793    
1794        #if POSIX
1795        unsigned long File::__GetFileSize(int hFile) {
1796          struct stat filestat;          struct stat filestat;
1797          fstat(hFileRead, &filestat);          fstat(hFile, &filestat);
1798          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  
1799          return size;          return size;
1800      }      }
1801        #elif defined(WIN32)
1802        unsigned long File::__GetFileSize(HANDLE hFile) {
1803            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1804            if (dwSize == INVALID_FILE_SIZE)
1805                throw Exception("Windows FS error: could not determine file size");
1806            return dwSize;
1807        }
1808        #else // standard C functions
1809        unsigned long File::__GetFileSize(FILE* hFile) {
1810            long curpos = ftell(hFile);
1811            fseek(hFile, 0, SEEK_END);
1812            long size = ftell(hFile);
1813            fseek(hFile, curpos, SEEK_SET);
1814            return size;
1815        }
1816        #endif
1817    
1818    
1819  // *************** Exception ***************  // *************** Exception ***************

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

  ViewVC Help
Powered by ViewVC