/[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 1207 by persson, Sat May 26 13:59:40 2007 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-2007 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 22  Line 22 
22   ***************************************************************************/   ***************************************************************************/
23    
24  #include <string.h>  #include <string.h>
 #include <sstream>  
25    
26  #include "RIFF.h"  #include "RIFF.h"
27    
28    #include "helper.h"
29    
30  namespace RIFF {  namespace RIFF {
31    
32  // *************** Helper Functions **************  // *************** Internal functions **************
33  // *  // *
34    
35      template<class T> inline String ToString(T o) {      /// Returns a human readable path of the given chunk.
36          std::stringstream ss;      String __resolveChunkPath(Chunk* pCk) {
37          ss << o;          String sPath;
38          return ss.str();          for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
39                if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
40                    List* pList = (List*) pChunk;
41                    sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
42                } else {
43                    sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
44                }
45            }
46            return sPath;
47      }      }
48    
49    
# Line 49  namespace RIFF { Line 58  namespace RIFF {
58          ulPos      = 0;          ulPos      = 0;
59          pParent    = NULL;          pParent    = NULL;
60          pChunkData = NULL;          pChunkData = NULL;
61            ulChunkDataSize = 0;
62            ChunkID    = CHUNK_ID_RIFF;
63          this->pFile = pFile;          this->pFile = pFile;
64      }      }
65    
# Line 61  namespace RIFF { Line 72  namespace RIFF {
72          pParent       = Parent;          pParent       = Parent;
73          ulPos         = 0;          ulPos         = 0;
74          pChunkData    = NULL;          pChunkData    = NULL;
75            ulChunkDataSize = 0;
76          ReadHeader(StartPos);          ReadHeader(StartPos);
77      }      }
78    
# Line 70  namespace RIFF { Line 82  namespace RIFF {
82          this->pParent    = pParent;          this->pParent    = pParent;
83          ulPos            = 0;          ulPos            = 0;
84          pChunkData       = NULL;          pChunkData       = NULL;
85            ulChunkDataSize  = 0;
86          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
87          CurrentChunkSize = 0;          CurrentChunkSize = 0;
88          NewChunkSize     = uiBodySize;          NewChunkSize     = uiBodySize;
89      }      }
90    
91      Chunk::~Chunk() {      Chunk::~Chunk() {
92            if (CurrentChunkSize != NewChunkSize) pFile->UnlogResized(this);
93          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
94      }      }
95    
# Line 87  namespace RIFF { Line 101  namespace RIFF {
101          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
102              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
103              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
104            #elif defined(WIN32)
105            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
106                DWORD dwBytesRead;
107                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
108                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
109          #else          #else
110          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
111              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
# Line 94  namespace RIFF { Line 113  namespace RIFF {
113          #endif // POSIX          #endif // POSIX
114              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
115              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
116                  bEndianNative = false;                  pFile->bEndianNative = false;
117              }              }
118              #else // little endian              #else // little endian
119              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
# Line 135  namespace RIFF { Line 154  namespace RIFF {
154              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
155              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &uiNewChunkSize, 4);
156          }          }
157            #elif defined(WIN32)
158            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
159                DWORD dwBytesWritten;
160                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
161                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
162            }
163          #else          #else
164          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
165              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
# Line 218  namespace RIFF { Line 243  namespace RIFF {
243        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
244        #endif // DEBUG        #endif // DEBUG
245          #if POSIX          #if POSIX
246          if (pFile->hFileRead == 0)    return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
247            #elif defined (WIN32)
248            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
249                return stream_closed;
250          #else          #else
251          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
252          #endif // POSIX          #endif // POSIX
# Line 252  namespace RIFF { Line 280  namespace RIFF {
280          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
281          if (readWords < 1) return 0;          if (readWords < 1) return 0;
282          readWords /= WordSize;          readWords /= WordSize;
283            #elif defined(WIN32)
284            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
285            DWORD readWords;
286            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
287            if (readWords < 1) return 0;
288            readWords /= WordSize;
289          #else // standard C functions          #else // standard C functions
290          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
291          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
# Line 293  namespace RIFF { Line 327  namespace RIFF {
327       *  @see Resize()       *  @see Resize()
328       */       */
329      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {
330          if (pFile->Mode == stream_mode_read)          if (pFile->Mode != stream_mode_read_write)
331              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");
332          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize >= CurrentChunkSize)          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)
333              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
334          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
335              switch (WordSize) {              switch (WordSize) {
# Line 321  namespace RIFF { Line 355  namespace RIFF {
355          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
356          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");
357          writtenWords /= WordSize;          writtenWords /= WordSize;
358            #elif defined(WIN32)
359            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
360                throw Exception("Could not seek to position " + ToString(ulPos) +
361                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");            
362            }
363            DWORD writtenWords;
364            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
365            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
366            writtenWords /= WordSize;
367          #else // standard C functions          #else // standard C functions
368          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
369              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
# Line 667  namespace RIFF { Line 710  namespace RIFF {
710       *       *
711       * <b>Caution:</b> the buffer pointer will be invalidated once       * <b>Caution:</b> the buffer pointer will be invalidated once
712       * File::Save() was called. You have to call LoadChunkData() again to       * File::Save() was called. You have to call LoadChunkData() again to
713       * get a new pointer whenever File::Save() was called.       * get a new, valid pointer whenever File::Save() was called.
714         *
715         * You can call LoadChunkData() again if you previously scheduled to
716         * enlarge this chunk with a Resize() call. In that case the buffer will
717         * be enlarged to the new, scheduled chunk size and you can already
718         * place the new chunk data to the buffer and finally call File::Save()
719         * to enlarge the chunk physically and write the new data in one rush.
720         * This approach is definitely recommended if you have to enlarge and
721         * write new data to a lot of chunks.
722       *       *
723       * @returns a pointer to the data in RAM on success, NULL otherwise       * @returns a pointer to the data in RAM on success, NULL otherwise
724         * @throws Exception if data buffer could not be enlarged
725       * @see ReleaseChunkData()       * @see ReleaseChunkData()
726       */       */
727      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
728          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "") {
729              #if POSIX              #if POSIX
730              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
731              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
732              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());  
733              #else              #else
734              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
735              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
736                unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
737                pChunkData = new uint8_t[ulBufferSize];
738              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
739                memset(pChunkData, 0, ulBufferSize);
740                #if POSIX
741                unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
742                #elif defined(WIN32)
743                DWORD readWords;
744                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
745                #else
746              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
747              #endif // POSIX              #endif // POSIX
748              if (readWords != GetSize()) {              if (readWords != GetSize()) {
749                  delete[] pChunkData;                  delete[] pChunkData;
750                  return (pChunkData = NULL);                  return (pChunkData = NULL);
751              }              }
752                ulChunkDataSize = ulBufferSize;
753            } else if (NewChunkSize > ulChunkDataSize) {
754                uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
755                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
756                memset(pNewBuffer, 0 , NewChunkSize);
757                memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
758                delete[] pChunkData;
759                pChunkData      = pNewBuffer;
760                ulChunkDataSize = NewChunkSize;
761          }          }
762          return pChunkData;          return pChunkData;
763      }      }
# Line 718  namespace RIFF { Line 787  namespace RIFF {
787       *       *
788       * <b>Caution:</b> You cannot directly write to enlarged chunks before       * <b>Caution:</b> You cannot directly write to enlarged chunks before
789       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
790       * boundary.       * boundary!
791       *       *
792       * @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)
793       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a iNewSize is less than 1
794       * @see File::Save()       * @see File::Save()
795       */       */
796      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
797          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0)
798                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
799            if (NewChunkSize == iNewSize) return;
800          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
801          pFile->LogAsResized(this);          pFile->LogAsResized(this);
802      }      }
# Line 743  namespace RIFF { Line 814  namespace RIFF {
814       *          (including its header size of course)       *          (including its header size of course)
815       */       */
816      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
817          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
818          ulWritePos += CHUNK_HEADER_SIZE;          ulWritePos += CHUNK_HEADER_SIZE;
819    
820            if (pFile->Mode != stream_mode_read_write)
821                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
822    
823          // if the whole chunk body was loaded into RAM          // if the whole chunk body was loaded into RAM
824          if (pChunkData) {          if (pChunkData) {
825              // 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
826              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;  
             }  
   
827              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
828              #if POSIX              #if POSIX
829              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
830              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
831                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
832              }              }
833                #elif defined(WIN32)
834                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
835                DWORD dwBytesWritten;
836                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
837                if (dwBytesWritten != NewChunkSize) {
838                    throw Exception("Writing Chunk data (from RAM) failed");
839                }
840              #else              #else
841              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
842              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 777  namespace RIFF { Line 847  namespace RIFF {
847              // 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
848              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
849              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
850                #if defined(WIN32)
851                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
852                #else
853              int iBytesMoved = 1;              int iBytesMoved = 1;
854                #endif
855              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
856                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
857                  #if POSIX                  #if POSIX
# Line 785  namespace RIFF { Line 859  namespace RIFF {
859                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
860                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
861                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
862                    #elif defined(WIN32)
863                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
864                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
865                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
866                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
867                  #else                  #else
868                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
869                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 806  namespace RIFF { Line 885  namespace RIFF {
885    
886          // add pad byte if needed          // add pad byte if needed
887          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ulStartPos + NewChunkSize) % 2 != 0) {
888              char cPadByte = 0;              const char cPadByte = 0;
889              #if POSIX              #if POSIX
890                lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
891              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
892                #elif defined(WIN32)
893                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
894                DWORD dwBytesWritten;
895                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
896              #else              #else
897                fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
898              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
899              #endif              #endif
900              return ulStartPos + NewChunkSize + 1;              return ulStartPos + NewChunkSize + 1;
# Line 1063  namespace RIFF { Line 1148  namespace RIFF {
1148      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1149          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");
1150          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1151          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, uiBodySize);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1152          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1153          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1154          pFile->ResizedChunks.push_back(pNewChunk);          pNewChunk->Resize(uiBodySize);
1155          return pNewChunk;          return pNewChunk;
1156      }      }
1157    
1158        /** @brief Moves a sub chunk.
1159         *
1160         * Moves a sub chunk from one position in a list to another
1161         * position in the same list. The pSrc chunk is placed before the
1162         * pDst chunk.
1163         *
1164         * @param pSrc - sub chunk to be moved
1165         * @param pDst - the position to move to. pSrc will be placed
1166         *               before pDst. If pDst is 0, pSrc will be placed
1167         *               last in list.
1168         */
1169        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1170            if (!pSubChunks) LoadSubChunks();
1171            pSubChunks->remove(pSrc);
1172            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1173            pSubChunks->insert(iter, pSrc);
1174        }
1175    
1176      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1177       *       *
1178       * 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 1091  namespace RIFF { Line 1194  namespace RIFF {
1194       *       *
1195       * 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
1196       * 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
1197       * 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,
1198       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1199         * should call File::Save() to make this change persistent at any time.
1200       *       *
1201       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1202       */       */
# Line 1123  namespace RIFF { Line 1227  namespace RIFF {
1227          #if POSIX          #if POSIX
1228          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1229          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1230            #elif defined(WIN32)
1231            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1232            DWORD dwBytesRead;
1233            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1234          #else          #else
1235          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1236          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1143  namespace RIFF { Line 1251  namespace RIFF {
1251          #if POSIX          #if POSIX
1252          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1253          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1254            #elif defined(WIN32)
1255            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1256            DWORD dwBytesWritten;
1257            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1258          #else          #else
1259          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1260          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
# Line 1182  namespace RIFF { Line 1294  namespace RIFF {
1294          }          }
1295      }      }
1296    
1297        void List::LoadSubChunksRecursively() {
1298            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1299                pList->LoadSubChunksRecursively();
1300        }
1301    
1302      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
1303       *       *
1304       * 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 1314  namespace RIFF {
1314       *          (including its header size of course)       *          (including its header size of course)
1315       */       */
1316      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1317          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
1318          ulWritePos += LIST_HEADER_SIZE;          ulWritePos += LIST_HEADER_SIZE;
1319    
1320            if (pFile->Mode != stream_mode_read_write)
1321                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1322    
1323          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1324          if (pSubChunks) {          if (pSubChunks) {
1325              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 1331  namespace RIFF {
1331          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1332          WriteHeader(ulOriginalPos);          WriteHeader(ulOriginalPos);
1333    
1334            // offset of this list chunk in new written file may have changed
1335            ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1336    
1337          return ulWritePos;          return ulWritePos;
1338      }      }
1339    
# Line 1241  namespace RIFF { Line 1364  namespace RIFF {
1364       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1365       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1366       *       *
1367       * @see AddSubChunk(), AddSubList()       * Note: by default, the RIFF file will be saved in native endian
1368       */       * format; that is, as a RIFF file on little-endian machines and
1369      File::File() : List(this) {       * as a RIFX file on big-endian. To change this behaviour, call
1370         * SetByteOrder() before calling Save().
1371         *
1372         * @param FileType - four-byte identifier of the RIFF file type
1373         * @see AddSubChunk(), AddSubList(), SetByteOrder()
1374         */
1375        File::File(uint32_t FileType) : List(this) {
1376            #if defined(WIN32)
1377            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1378            #else
1379          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1380            #endif
1381            Mode = stream_mode_closed;
1382          bEndianNative = true;          bEndianNative = true;
1383          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1384            ListType = FileType;
1385      }      }
1386    
1387      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1268  namespace RIFF { Line 1403  namespace RIFF {
1403              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1404              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1405          }          }
1406            #elif defined(WIN32)
1407            hFileRead = hFileWrite = CreateFile(
1408                                         path.c_str(), GENERIC_READ,
1409                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1410                                         NULL, OPEN_EXISTING,
1411                                         FILE_ATTRIBUTE_NORMAL, NULL
1412                                     );
1413            if (hFileRead == INVALID_HANDLE_VALUE) {
1414                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1415                throw RIFF::Exception("Can't open \"" + path + "\"");
1416            }
1417          #else          #else
1418          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1419          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1420          #endif // POSIX          #endif // POSIX
1421            Mode = stream_mode_read;
1422          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1423          ReadHeader(0);          ReadHeader(0);
1424          if (ChunkID != CHUNK_ID_RIFF) {          if (ChunkID != CHUNK_ID_RIFF) {
# Line 1308  namespace RIFF { Line 1455  namespace RIFF {
1455                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1456                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1457                      }                      }
1458                        #elif defined(WIN32)
1459                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1460                        hFileRead = hFileWrite = CreateFile(
1461                                                     Filename.c_str(), GENERIC_READ,
1462                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1463                                                     NULL, OPEN_EXISTING,
1464                                                     FILE_ATTRIBUTE_NORMAL, NULL
1465                                                 );
1466                        if (hFileRead == INVALID_HANDLE_VALUE) {
1467                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1468                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1469                        }
1470                      #else                      #else
1471                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1472                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1473                      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");
1474                      #endif                      #endif
1475                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1476                      return true;                      break;
1477                  case stream_mode_read_write:                  case stream_mode_read_write:
1478                      #if POSIX                      #if POSIX
1479                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
# Line 1323  namespace RIFF { Line 1482  namespace RIFF {
1482                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1483                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1484                      }                      }
1485                        #elif defined(WIN32)
1486                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1487                        hFileRead = hFileWrite = CreateFile(
1488                                                     Filename.c_str(),
1489                                                     GENERIC_READ | GENERIC_WRITE,
1490                                                     FILE_SHARE_READ,
1491                                                     NULL, OPEN_ALWAYS,
1492                                                     FILE_ATTRIBUTE_NORMAL, NULL
1493                                                 );
1494                        if (hFileRead == INVALID_HANDLE_VALUE) {
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, NULL
1500                                                     );
1501                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1502                        }
1503                      #else                      #else
1504                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1505                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1506                      if (!hFileRead) {                      if (!hFileRead) {
1507                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1508                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1509                      }                      }
1510                      #endif                      #endif
1511                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1512                      return true;                      break;
1513                    case stream_mode_closed:
1514                        #if POSIX
1515                        if (hFileRead)  close(hFileRead);
1516                        if (hFileWrite) close(hFileWrite);
1517                        #elif defined(WIN32)
1518                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1519                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1520                        #else
1521                        if (hFileRead)  fclose(hFileRead);
1522                        if (hFileWrite) fclose(hFileWrite);
1523                        #endif
1524                        hFileRead = hFileWrite = 0;
1525                        break;
1526                  default:                  default:
1527                      throw Exception("Unknown file access mode");                      throw Exception("Unknown file access mode");
1528              }              }
1529                Mode = NewMode;
1530                return true;
1531          }          }
1532          return false;          return false;
1533      }      }
1534    
1535        /** @brief Set the byte order to be used when saving.
1536         *
1537         * Set the byte order to be used in the file. A value of
1538         * endian_little will create a RIFF file, endian_big a RIFX file
1539         * and endian_native will create a RIFF file on little-endian
1540         * machines and RIFX on big-endian machines.
1541         *
1542         * @param Endian - endianess to use when file is saved.
1543         */
1544        void File::SetByteOrder(endian_t Endian) {
1545            #if WORDS_BIGENDIAN
1546            bEndianNative = Endian != endian_little;
1547            #else
1548            bEndianNative = Endian != endian_big;
1549            #endif
1550        }
1551    
1552      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1553       *       *
1554       * 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 1560  namespace RIFF {
1560       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1561       */       */
1562      void File::Save() {      void File::Save() {
1563            // make sure the RIFF tree is built (from the original file)
1564            LoadSubChunksRecursively();
1565    
1566          // reopen file in write mode          // reopen file in write mode
1567          bool bModeWasChanged = SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1568    
1569          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
1570          // 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 1364  namespace RIFF { Line 1576  namespace RIFF {
1576          // 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)
1577          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1578          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1579              if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)");              if ((*iter)->GetNewSize() == 0) {
1580              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));
1581              if (ulDiff > 0) ulPositiveSizeDiff += ulDiff;              }
1582                if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {
1583                    unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte
1584                    ulPositiveSizeDiff += ulDiff;
1585                }
1586          }          }
1587    
1588          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1379  namespace RIFF { Line 1595  namespace RIFF {
1595              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1596              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1597              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1598              int iBytesMoved = 1;              #if defined(WIN32)
1599                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1600                #else
1601                int iBytesMoved = 1;
1602                #endif
1603              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {
1604                  const unsigned long ulToMove = ulFileSize - ulPos;                  const unsigned long ulToMove = ulFileSize - ulPos;
1605                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
# Line 1388  namespace RIFF { Line 1608  namespace RIFF {
1608                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1609                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1610                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1611                    #elif defined(WIN32)
1612                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1613                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1614                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1615                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1616                  #else                  #else
1617                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1618                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
# Line 1400  namespace RIFF { Line 1625  namespace RIFF {
1625          }          }
1626    
1627          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree
1628          unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff);          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);
1629            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1630    
1631          // resize file to the final size          // resize file to the final size
1632          if (ulTotalSize < ulWorkingFileSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1633    
1634          // forget all resized chunks          // forget all resized chunks
1635          ResizedChunks.clear();          ResizedChunks.clear();
   
         // reopen file in read mode  
         if (bModeWasChanged) SetMode(stream_mode_read);  
1636      }      }
1637    
1638      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1417  namespace RIFF { Line 1640  namespace RIFF {
1640       * Make all changes of all chunks persistent by writing them to another       * Make all changes of all chunks persistent by writing them to another
1641       * file. <b>Caution:</b> this method is optimized for writing to       * file. <b>Caution:</b> this method is optimized for writing to
1642       * <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
1643       * file! Use File::Save() in that case instead!       * file! Use File::Save() in that case instead! Ignoring this might
1644         * result in a corrupted file, especially in case chunks were resized!
1645       *       *
1646       * After calling this method, this File object will be associated with       * After calling this method, this File object will be associated with
1647       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
# Line 1425  namespace RIFF { Line 1649  namespace RIFF {
1649       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1650       */       */
1651      void File::Save(const String& path) {      void File::Save(const String& path) {
1652            //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
1653    
1654            // make sure the RIFF tree is built (from the original file)
1655            LoadSubChunksRecursively();
1656    
1657            if (Filename.length() > 0) SetMode(stream_mode_read);
1658          // 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
1659          #if POSIX          #if POSIX
1660          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);
1661          if (hFileWrite < 0) {          if (hFileWrite < 0) {
1662              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1663              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1664          }          }
1665            #elif defined(WIN32)
1666            hFileWrite = CreateFile(
1667                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1668                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL
1669                         );
1670            if (hFileWrite == INVALID_HANDLE_VALUE) {
1671                hFileWrite = hFileRead;
1672                throw Exception("Could not open file \"" + path + "\" for writing");
1673            }
1674          #else          #else
1675          hFileWrite = fopen(path.c_str(), "w+b");          hFileWrite = fopen(path.c_str(), "w+b");
1676          if (!hFileWrite) {          if (!hFileWrite) {
# Line 1439  namespace RIFF { Line 1678  namespace RIFF {
1678              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1679          }          }
1680          #endif // POSIX          #endif // POSIX
1681            Mode = stream_mode_read_write;
1682    
1683          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
1684          WriteChunk(0, 0);          unsigned long ulTotalSize  = WriteChunk(0, 0);
1685            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1686    
1687            // resize file to the final size (if the file was originally larger)
1688            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1689    
1690          // forget all resized chunks          // forget all resized chunks
1691          ResizedChunks.clear();          ResizedChunks.clear();
1692    
1693            if (Filename.length() > 0) {
1694                #if POSIX
1695                close(hFileWrite);
1696                #elif defined(WIN32)
1697                CloseHandle(hFileWrite);
1698                #else
1699                fclose(hFileWrite);
1700                #endif
1701                hFileWrite = hFileRead;
1702            }
1703    
1704          // associate new file with this File object from now on          // associate new file with this File object from now on
1705          Filename = path;          Filename = path;
1706          stream_mode_t oldMode = Mode;          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1707          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.  
1708      }      }
1709    
1710      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(unsigned long ulNewSize) {
1711          #if POSIX          #if POSIX
1712          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1713              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1714            #elif defined(WIN32)
1715            if (
1716                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1717                !SetEndOfFile(hFileWrite)
1718            ) throw Exception("Could not resize file \"" + Filename + "\"");
1719          #else          #else
1720          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1721          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1722          #endif          #endif
1723      }      }
1724    
# Line 1469  namespace RIFF { Line 1728  namespace RIFF {
1728         #endif // DEBUG         #endif // DEBUG
1729          #if POSIX          #if POSIX
1730          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1731            #elif defined(WIN32)
1732            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1733          #else          #else
1734          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1735          #endif // POSIX          #endif // POSIX
# Line 1478  namespace RIFF { Line 1739  namespace RIFF {
1739          ResizedChunks.push_back(pResizedChunk);          ResizedChunks.push_back(pResizedChunk);
1740      }      }
1741    
1742        void File::UnlogResized(Chunk* pResizedChunk) {
1743            ResizedChunks.remove(pResizedChunk);
1744        }
1745    
1746      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
1747          #if POSIX          return __GetFileSize(hFileRead);
1748        }
1749    
1750        #if POSIX
1751        unsigned long File::__GetFileSize(int hFile) {
1752          struct stat filestat;          struct stat filestat;
1753          fstat(hFileRead, &filestat);          fstat(hFile, &filestat);
1754          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  
1755          return size;          return size;
1756      }      }
1757        #elif defined(WIN32)
1758        unsigned long File::__GetFileSize(HANDLE hFile) {
1759            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1760            if (dwSize == INVALID_FILE_SIZE)
1761                throw Exception("Windows FS error: could not determine file size");
1762            return dwSize;
1763        }
1764        #else // standard C functions
1765        unsigned long File::__GetFileSize(FILE* hFile) {
1766            long curpos = ftell(hFile);
1767            fseek(hFile, 0, SEEK_END);
1768            long size = ftell(hFile);
1769            fseek(hFile, curpos, SEEK_SET);
1770            return size;
1771        }
1772        #endif
1773    
1774    
1775  // *************** Exception ***************  // *************** Exception ***************

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

  ViewVC Help
Powered by ViewVC