/[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 798 by schoenebeck, Thu Nov 3 23:49:11 2005 UTC revision 2450 by persson, Wed May 8 17:53:07 2013 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-2013 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;          ChunkID    = CHUNK_ID_RIFF;
67          this->pFile = pFile;          this->pFile = pFile;
68      }      }
# Line 62  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 72  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 84  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 95  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 109  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 136  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 200  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 211  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 219  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 246  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 253  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 322  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 544  namespace RIFF { Line 595  namespace RIFF {
595      }      }
596    
597      /**      /**
598         * Reads a null-padded string of size characters and copies it
599         * into the string \a s. The position within the chunk will
600         * automatically be incremented.
601         *
602         * @param s                 destination string
603         * @param size              number of characters to read
604         * @throws RIFF::Exception  if an error occured or less than
605         *                          \a size characters could be read!
606         */
607        void Chunk::ReadString(String& s, int size) {
608            char* buf = new char[size];
609            ReadSceptical(buf, 1, size);
610            s.assign(buf, std::find(buf, buf + size, '\0'));
611            delete[] buf;
612        }
613    
614        /**
615       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
616       * buffer pointed by \a pData to the chunk's body, directly to the       * buffer pointed by \a pData to the chunk's body, directly to the
617       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 668  namespace RIFF { Line 736  namespace RIFF {
736       *       *
737       * <b>Caution:</b> the buffer pointer will be invalidated once       * <b>Caution:</b> the buffer pointer will be invalidated once
738       * File::Save() was called. You have to call LoadChunkData() again to       * File::Save() was called. You have to call LoadChunkData() again to
739       * get a new pointer whenever File::Save() was called.       * get a new, valid pointer whenever File::Save() was called.
740         *
741         * You can call LoadChunkData() again if you previously scheduled to
742         * enlarge this chunk with a Resize() call. In that case the buffer will
743         * be enlarged to the new, scheduled chunk size and you can already
744         * place the new chunk data to the buffer and finally call File::Save()
745         * to enlarge the chunk physically and write the new data in one rush.
746         * This approach is definitely recommended if you have to enlarge and
747         * write new data to a lot of chunks.
748       *       *
749       * @returns a pointer to the data in RAM on success, NULL otherwise       * @returns a pointer to the data in RAM on success, NULL otherwise
750         * @throws Exception if data buffer could not be enlarged
751       * @see ReleaseChunkData()       * @see ReleaseChunkData()
752       */       */
753      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
754          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {
755              #if POSIX              #if POSIX
756              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
757              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
758              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());  
759              #else              #else
760              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
761              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
762                unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
763                pChunkData = new uint8_t[ulBufferSize];
764              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
765                memset(pChunkData, 0, ulBufferSize);
766                #if POSIX
767                unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
768                #elif defined(WIN32)
769                DWORD readWords;
770                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
771                #else
772              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
773              #endif // POSIX              #endif // POSIX
774              if (readWords != GetSize()) {              if (readWords != GetSize()) {
775                  delete[] pChunkData;                  delete[] pChunkData;
776                  return (pChunkData = NULL);                  return (pChunkData = NULL);
777              }              }
778                ulChunkDataSize = ulBufferSize;
779            } else if (NewChunkSize > ulChunkDataSize) {
780                uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
781                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
782                memset(pNewBuffer, 0 , NewChunkSize);
783                memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
784                delete[] pChunkData;
785                pChunkData      = pNewBuffer;
786                ulChunkDataSize = NewChunkSize;
787          }          }
788          return pChunkData;          return pChunkData;
789      }      }
# Line 719  namespace RIFF { Line 813  namespace RIFF {
813       *       *
814       * <b>Caution:</b> You cannot directly write to enlarged chunks before       * <b>Caution:</b> You cannot directly write to enlarged chunks before
815       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
816       * boundary.       * boundary!
817       *       *
818       * @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)
819       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a iNewSize is less than 1
820       * @see File::Save()       * @see File::Save()
821       */       */
822      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
823          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0)
824                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
825            if (NewChunkSize == iNewSize) return;
826          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
827          pFile->LogAsResized(this);          pFile->LogAsResized(this);
828      }      }
# Line 752  namespace RIFF { Line 848  namespace RIFF {
848    
849          // if the whole chunk body was loaded into RAM          // if the whole chunk body was loaded into RAM
850          if (pChunkData) {          if (pChunkData) {
851              // 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
852              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;  
             }  
   
853              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
854              #if POSIX              #if POSIX
855              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
856              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
857                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
858              }              }
859                #elif defined(WIN32)
860                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
861                DWORD dwBytesWritten;
862                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
863                if (dwBytesWritten != NewChunkSize) {
864                    throw Exception("Writing Chunk data (from RAM) failed");
865                }
866              #else              #else
867              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
868              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 781  namespace RIFF { Line 873  namespace RIFF {
873              // 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
874              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
875              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
876                #if defined(WIN32)
877                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
878                #else
879              int iBytesMoved = 1;              int iBytesMoved = 1;
880              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              #endif
881                for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
882                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
883                  #if POSIX                  #if POSIX
884                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
885                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
886                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
887                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
888                    #elif defined(WIN32)
889                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
890                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
891                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
892                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
893                  #else                  #else
894                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
895                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 814  namespace RIFF { Line 915  namespace RIFF {
915              #if POSIX              #if POSIX
916              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
917              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
918                #elif defined(WIN32)
919                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
920                DWORD dwBytesWritten;
921                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
922              #else              #else
923              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
924              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
# Line 863  namespace RIFF { Line 968  namespace RIFF {
968        #if DEBUG        #if DEBUG
969        std::cout << "List::~List()" << std::endl;        std::cout << "List::~List()" << std::endl;
970        #endif // DEBUG        #endif // DEBUG
971            DeleteChunkList();
972        }
973    
974        void List::DeleteChunkList() {
975          if (pSubChunks) {          if (pSubChunks) {
976              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
977              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 871  namespace RIFF { Line 980  namespace RIFF {
980                  iter++;                  iter++;
981              }              }
982              delete pSubChunks;              delete pSubChunks;
983                pSubChunks = NULL;
984            }
985            if (pSubChunksMap) {
986                delete pSubChunksMap;
987                pSubChunksMap = NULL;
988          }          }
         if (pSubChunksMap) delete pSubChunksMap;  
989      }      }
990    
991      /**      /**
# Line 1073  namespace RIFF { Line 1186  namespace RIFF {
1186          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1187          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1188          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(uiBodySize);
1189            NewChunkSize += CHUNK_HEADER_SIZE;
1190            pFile->LogAsResized(this);
1191          return pNewChunk;          return pNewChunk;
1192      }      }
1193    
1194        /** @brief Moves a sub chunk.
1195         *
1196         * Moves a sub chunk from one position in a list to another
1197         * position in the same list. The pSrc chunk is placed before the
1198         * pDst chunk.
1199         *
1200         * @param pSrc - sub chunk to be moved
1201         * @param pDst - the position to move to. pSrc will be placed
1202         *               before pDst. If pDst is 0, pSrc will be placed
1203         *               last in list.
1204         */
1205        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1206            if (!pSubChunks) LoadSubChunks();
1207            pSubChunks->remove(pSrc);
1208            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1209            pSubChunks->insert(iter, pSrc);
1210        }
1211    
1212      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1213       *       *
1214       * 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 1090  namespace RIFF { Line 1223  namespace RIFF {
1223          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1224          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1225          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1226            NewChunkSize += LIST_HEADER_SIZE;
1227            pFile->LogAsResized(this);
1228          return pNewListChunk;          return pNewListChunk;
1229      }      }
1230    
# Line 1097  namespace RIFF { Line 1232  namespace RIFF {
1232       *       *
1233       * 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
1234       * 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
1235       * 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,
1236       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1237         * should call File::Save() to make this change persistent at any time.
1238       *       *
1239       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1240       */       */
# Line 1125  namespace RIFF { Line 1261  namespace RIFF {
1261        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1262        #endif // DEBUG        #endif // DEBUG
1263          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1264            if (CurrentChunkSize < 4) return;
1265          NewChunkSize = CurrentChunkSize -= 4;          NewChunkSize = CurrentChunkSize -= 4;
1266          #if POSIX          #if POSIX
1267          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1268          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1269            #elif defined(WIN32)
1270            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1271            DWORD dwBytesRead;
1272            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1273          #else          #else
1274          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1275          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1149  namespace RIFF { Line 1290  namespace RIFF {
1290          #if POSIX          #if POSIX
1291          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1292          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1293            #elif defined(WIN32)
1294            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1295            DWORD dwBytesWritten;
1296            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1297          #else          #else
1298          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1299          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
# Line 1162  namespace RIFF { Line 1307  namespace RIFF {
1307          if (!pSubChunks) {          if (!pSubChunks) {
1308              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1309              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1310                #if defined(WIN32)
1311                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1312                #else
1313              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1314                #endif
1315              unsigned long uiOriginalPos = GetPos();              unsigned long uiOriginalPos = GetPos();
1316              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1317              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
# Line 1188  namespace RIFF { Line 1337  namespace RIFF {
1337          }          }
1338      }      }
1339    
1340        void List::LoadSubChunksRecursively() {
1341            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1342                pList->LoadSubChunksRecursively();
1343        }
1344    
1345      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
1346       *       *
1347       * Stores the list chunk persistently to its actual "physical" file. All       * Stores the list chunk persistently to its actual "physical" file. All
# Line 1247  namespace RIFF { Line 1401  namespace RIFF {
1401  // *************** File ***************  // *************** File ***************
1402  // *  // *
1403    
1404    //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
1405    #define _GET_RESIZED_CHUNKS() \
1406            (reinterpret_cast<std::set<Chunk*>*>(ResizedChunks.front()))
1407    
1408      /** @brief Create new RIFF file.      /** @brief Create new RIFF file.
1409       *       *
1410       * 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
1411       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1412       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1413       *       *
1414         * Note: by default, the RIFF file will be saved in native endian
1415         * format; that is, as a RIFF file on little-endian machines and
1416         * as a RIFX file on big-endian. To change this behaviour, call
1417         * SetByteOrder() before calling Save().
1418         *
1419       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1420       * @see AddSubChunk(), AddSubList()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1421       */       */
1422      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType) : List(this) {
1423            //HACK: see _GET_RESIZED_CHUNKS() comment
1424            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1425            #if defined(WIN32)
1426            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1427            #else
1428          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1429            #endif
1430          Mode = stream_mode_closed;          Mode = stream_mode_closed;
1431          bEndianNative = true;          bEndianNative = true;
1432          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
# Line 1273  namespace RIFF { Line 1442  namespace RIFF {
1442       *                         given RIFF file       *                         given RIFF file
1443       */       */
1444      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path) : List(this), Filename(path) {
1445        #if DEBUG         #if DEBUG
1446        std::cout << "File::File("<<path<<")" << std::endl;         std::cout << "File::File("<<path<<")" << std::endl;
1447        #endif // DEBUG         #endif // DEBUG
1448          bEndianNative = true;          try {
1449          #if POSIX              bEndianNative = true;
1450          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);              //HACK: see _GET_RESIZED_CHUNKS() comment
1451          if (hFileRead <= 0) {              ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1452              hFileRead = hFileWrite = 0;              #if POSIX
1453              throw RIFF::Exception("Can't open \"" + path + "\"");              hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1454                if (hFileRead <= 0) {
1455                    hFileRead = hFileWrite = 0;
1456                    throw RIFF::Exception("Can't open \"" + path + "\"");
1457                }
1458                #elif defined(WIN32)
1459                hFileRead = hFileWrite = CreateFile(
1460                                             path.c_str(), GENERIC_READ,
1461                                             FILE_SHARE_READ | FILE_SHARE_WRITE,
1462                                             NULL, OPEN_EXISTING,
1463                                             FILE_ATTRIBUTE_NORMAL |
1464                                             FILE_FLAG_RANDOM_ACCESS, NULL
1465                                         );
1466                if (hFileRead == INVALID_HANDLE_VALUE) {
1467                    hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1468                    throw RIFF::Exception("Can't open \"" + path + "\"");
1469                }
1470                #else
1471                hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1472                if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1473                #endif // POSIX
1474                Mode = stream_mode_read;
1475                ulStartPos = RIFF_HEADER_SIZE;
1476                ReadHeader(0);
1477                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1478                    throw RIFF::Exception("Not a RIFF file");
1479                }
1480          }          }
1481          #else          catch (...) {
1482          hFileRead = hFileWrite = fopen(path.c_str(), "rb");              Cleanup();
1483          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");              throw;
         #endif // POSIX  
         Mode = stream_mode_read;  
         ulStartPos = RIFF_HEADER_SIZE;  
         ReadHeader(0);  
         if (ChunkID != CHUNK_ID_RIFF) {  
             throw RIFF::Exception("Not a RIFF file");  
1484          }          }
1485      }      }
1486    
# Line 1324  namespace RIFF { Line 1513  namespace RIFF {
1513                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1514                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1515                      }                      }
1516                        #elif defined(WIN32)
1517                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1518                        hFileRead = hFileWrite = CreateFile(
1519                                                     Filename.c_str(), GENERIC_READ,
1520                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1521                                                     NULL, OPEN_EXISTING,
1522                                                     FILE_ATTRIBUTE_NORMAL |
1523                                                     FILE_FLAG_RANDOM_ACCESS,
1524                                                     NULL
1525                                                 );
1526                        if (hFileRead == INVALID_HANDLE_VALUE) {
1527                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1528                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1529                        }
1530                      #else                      #else
1531                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1532                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1533                      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");
1534                      #endif                      #endif
1535                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
# Line 1339  namespace RIFF { Line 1542  namespace RIFF {
1542                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1543                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1544                      }                      }
1545                        #elif defined(WIN32)
1546                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1547                        hFileRead = hFileWrite = CreateFile(
1548                                                     Filename.c_str(),
1549                                                     GENERIC_READ | GENERIC_WRITE,
1550                                                     FILE_SHARE_READ,
1551                                                     NULL, OPEN_ALWAYS,
1552                                                     FILE_ATTRIBUTE_NORMAL |
1553                                                     FILE_FLAG_RANDOM_ACCESS,
1554                                                     NULL
1555                                                 );
1556                        if (hFileRead == INVALID_HANDLE_VALUE) {
1557                            hFileRead = hFileWrite = CreateFile(
1558                                                         Filename.c_str(), GENERIC_READ,
1559                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1560                                                         NULL, OPEN_EXISTING,
1561                                                         FILE_ATTRIBUTE_NORMAL |
1562                                                         FILE_FLAG_RANDOM_ACCESS,
1563                                                         NULL
1564                                                     );
1565                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1566                        }
1567                      #else                      #else
1568                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1569                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1570                      if (!hFileRead) {                      if (!hFileRead) {
1571                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1572                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1573                      }                      }
1574                      #endif                      #endif
# Line 1353  namespace RIFF { Line 1578  namespace RIFF {
1578                      #if POSIX                      #if POSIX
1579                      if (hFileRead)  close(hFileRead);                      if (hFileRead)  close(hFileRead);
1580                      if (hFileWrite) close(hFileWrite);                      if (hFileWrite) close(hFileWrite);
1581                        #elif defined(WIN32)
1582                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1583                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1584                      #else                      #else
1585                      if (hFileRead)  fclose(hFileRead);                      if (hFileRead)  fclose(hFileRead);
1586                      if (hFileWrite) fclose(hFileWrite);                      if (hFileWrite) fclose(hFileWrite);
# Line 1368  namespace RIFF { Line 1596  namespace RIFF {
1596          return false;          return false;
1597      }      }
1598    
1599        /** @brief Set the byte order to be used when saving.
1600         *
1601         * Set the byte order to be used in the file. A value of
1602         * endian_little will create a RIFF file, endian_big a RIFX file
1603         * and endian_native will create a RIFF file on little-endian
1604         * machines and RIFX on big-endian machines.
1605         *
1606         * @param Endian - endianess to use when file is saved.
1607         */
1608        void File::SetByteOrder(endian_t Endian) {
1609            #if WORDS_BIGENDIAN
1610            bEndianNative = Endian != endian_little;
1611            #else
1612            bEndianNative = Endian != endian_big;
1613            #endif
1614        }
1615    
1616      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1617       *       *
1618       * 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 1379  namespace RIFF { Line 1624  namespace RIFF {
1624       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1625       */       */
1626      void File::Save() {      void File::Save() {
1627            // make sure the RIFF tree is built (from the original file)
1628            LoadSubChunksRecursively();
1629    
1630          // reopen file in write mode          // reopen file in write mode
1631          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1632    
# Line 1391  namespace RIFF { Line 1639  namespace RIFF {
1639    
1640          // 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)
1641          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1642          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          std::set<Chunk*>* resizedChunks = _GET_RESIZED_CHUNKS();
1643              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) {
1644              if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {              if ((*iter)->GetNewSize() == 0) {
1645                  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));
1646                  ulPositiveSizeDiff += ulDiff;              }
1647              }              unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1648                unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1649                if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1650          }          }
1651    
1652          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1409  namespace RIFF { Line 1659  namespace RIFF {
1659              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1660              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1661              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1662                #if defined(WIN32)
1663                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1664                #else
1665              int iBytesMoved = 1;              int iBytesMoved = 1;
1666              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              #endif
1667                  const unsigned long ulToMove = ulFileSize - ulPos;              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1668                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1669                    ulPos -= iBytesMoved;
1670                  #if POSIX                  #if POSIX
1671                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ulPos, SEEK_SET);
1672                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1673                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1674                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1675                    #elif defined(WIN32)
1676                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1677                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1678                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1679                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1680                  #else                  #else
1681                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1682                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
# Line 1437  namespace RIFF { Line 1696  namespace RIFF {
1696          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1697    
1698          // forget all resized chunks          // forget all resized chunks
1699          ResizedChunks.clear();          resizedChunks->clear();
1700      }      }
1701    
1702      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1456  namespace RIFF { Line 1715  namespace RIFF {
1715      void File::Save(const String& path) {      void File::Save(const String& path) {
1716          //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          //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
1717    
1718            // make sure the RIFF tree is built (from the original file)
1719            LoadSubChunksRecursively();
1720    
1721          if (Filename.length() > 0) SetMode(stream_mode_read);          if (Filename.length() > 0) SetMode(stream_mode_read);
1722          // 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
1723          #if POSIX          #if POSIX
# Line 1464  namespace RIFF { Line 1726  namespace RIFF {
1726              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1727              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1728          }          }
1729            #elif defined(WIN32)
1730            hFileWrite = CreateFile(
1731                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1732                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1733                             FILE_FLAG_RANDOM_ACCESS, NULL
1734                         );
1735            if (hFileWrite == INVALID_HANDLE_VALUE) {
1736                hFileWrite = hFileRead;
1737                throw Exception("Could not open file \"" + path + "\" for writing");
1738            }
1739          #else          #else
1740          hFileWrite = fopen(path.c_str(), "w+b");          hFileWrite = fopen(path.c_str(), "w+b");
1741          if (!hFileWrite) {          if (!hFileWrite) {
# Line 1481  namespace RIFF { Line 1753  namespace RIFF {
1753          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1754    
1755          // forget all resized chunks          // forget all resized chunks
1756          ResizedChunks.clear();          _GET_RESIZED_CHUNKS()->clear();
1757    
1758          if (Filename.length() > 0) {          #if POSIX
1759              #if POSIX          if (hFileWrite) close(hFileWrite);
1760              close(hFileWrite);          #elif defined(WIN32)
1761              #else          if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1762              fclose(hFileWrite);          #else
1763              #endif          if (hFileWrite) fclose(hFileWrite);
1764              hFileWrite = hFileRead;          #endif
1765          }          hFileWrite = hFileRead;
1766    
1767          // associate new file with this File object from now on          // associate new file with this File object from now on
1768          Filename = path;          Filename = path;
# Line 1502  namespace RIFF { Line 1774  namespace RIFF {
1774          #if POSIX          #if POSIX
1775          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1776              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1777            #elif defined(WIN32)
1778            if (
1779                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1780                !SetEndOfFile(hFileWrite)
1781            ) throw Exception("Could not resize file \"" + Filename + "\"");
1782          #else          #else
1783          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1784          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1785          #endif          #endif
1786      }      }
# Line 1512  namespace RIFF { Line 1789  namespace RIFF {
1789         #if DEBUG         #if DEBUG
1790         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
1791         #endif // DEBUG         #endif // DEBUG
1792            Cleanup();
1793        }
1794    
1795        void File::Cleanup() {
1796          #if POSIX          #if POSIX
1797          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1798            #elif defined(WIN32)
1799            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1800          #else          #else
1801          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1802          #endif // POSIX          #endif // POSIX
1803            DeleteChunkList();
1804            pFile = NULL;
1805            //HACK: see _GET_RESIZED_CHUNKS() comment
1806            delete _GET_RESIZED_CHUNKS();
1807      }      }
1808    
1809      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {
1810          ResizedChunks.push_back(pResizedChunk);          _GET_RESIZED_CHUNKS()->insert(pResizedChunk);
1811        }
1812    
1813        void File::UnlogResized(Chunk* pResizedChunk) {
1814            _GET_RESIZED_CHUNKS()->erase(pResizedChunk);
1815      }      }
1816    
1817      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
# Line 1534  namespace RIFF { Line 1825  namespace RIFF {
1825          long size = filestat.st_size;          long size = filestat.st_size;
1826          return size;          return size;
1827      }      }
1828        #elif defined(WIN32)
1829        unsigned long File::__GetFileSize(HANDLE hFile) {
1830            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1831            if (dwSize == INVALID_FILE_SIZE)
1832                throw Exception("Windows FS error: could not determine file size");
1833            return dwSize;
1834        }
1835      #else // standard C functions      #else // standard C functions
1836      unsigned long File::__GetFileSize(FILE* hFile) {      unsigned long File::__GetFileSize(FILE* hFile) {
1837          long curpos = ftell(hFile);          long curpos = ftell(hFile);

Legend:
Removed from v.798  
changed lines
  Added in v.2450

  ViewVC Help
Powered by ViewVC