/[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 1095 by schoenebeck, Mon Mar 12 18:16:55 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  namespace RIFF {  #include "helper.h"
   
 // *************** Helper Functions **************  
 // *  
   
     template<class T> inline String ToString(T o) {  
         std::stringstream ss;  
         ss << o;  
         return ss.str();  
     }  
   
29    
30    namespace RIFF {
31    
32  // *************** Chunk **************  // *************** Chunk **************
33  // *  // *
# Line 49  namespace RIFF { Line 39  namespace RIFF {
39          ulPos      = 0;          ulPos      = 0;
40          pParent    = NULL;          pParent    = NULL;
41          pChunkData = NULL;          pChunkData = NULL;
42            ulChunkDataSize = 0;
43            ChunkID    = CHUNK_ID_RIFF;
44          this->pFile = pFile;          this->pFile = pFile;
45      }      }
46    
# Line 61  namespace RIFF { Line 53  namespace RIFF {
53          pParent       = Parent;          pParent       = Parent;
54          ulPos         = 0;          ulPos         = 0;
55          pChunkData    = NULL;          pChunkData    = NULL;
56            ulChunkDataSize = 0;
57          ReadHeader(StartPos);          ReadHeader(StartPos);
58      }      }
59    
# Line 70  namespace RIFF { Line 63  namespace RIFF {
63          this->pParent    = pParent;          this->pParent    = pParent;
64          ulPos            = 0;          ulPos            = 0;
65          pChunkData       = NULL;          pChunkData       = NULL;
66            ulChunkDataSize  = 0;
67          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
68          CurrentChunkSize = 0;          CurrentChunkSize = 0;
69          NewChunkSize     = uiBodySize;          NewChunkSize     = uiBodySize;
70      }      }
71    
72      Chunk::~Chunk() {      Chunk::~Chunk() {
73            if (CurrentChunkSize != NewChunkSize) pFile->UnlogResized(this);
74          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
75      }      }
76    
# Line 87  namespace RIFF { Line 82  namespace RIFF {
82          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
83              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
84              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
85            #elif defined(WIN32)
86            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
87                DWORD dwBytesRead;
88                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
89                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
90          #else          #else
91          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
92              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
# Line 94  namespace RIFF { Line 94  namespace RIFF {
94          #endif // POSIX          #endif // POSIX
95              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
96              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
97                  bEndianNative = false;                  pFile->bEndianNative = false;
98              }              }
99              #else // little endian              #else // little endian
100              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
# Line 135  namespace RIFF { Line 135  namespace RIFF {
135              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
136              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &uiNewChunkSize, 4);
137          }          }
138            #elif defined(WIN32)
139            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
140                DWORD dwBytesWritten;
141                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
142                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
143            }
144          #else          #else
145          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
146              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
# Line 218  namespace RIFF { Line 224  namespace RIFF {
224        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
225        #endif // DEBUG        #endif // DEBUG
226          #if POSIX          #if POSIX
227          if (pFile->hFileRead == 0)    return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
228            #elif defined (WIN32)
229            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
230                return stream_closed;
231          #else          #else
232          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
233          #endif // POSIX          #endif // POSIX
# Line 252  namespace RIFF { Line 261  namespace RIFF {
261          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
262          if (readWords < 1) return 0;          if (readWords < 1) return 0;
263          readWords /= WordSize;          readWords /= WordSize;
264            #elif defined(WIN32)
265            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
266            DWORD readWords;
267            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
268            if (readWords < 1) return 0;
269            readWords /= WordSize;
270          #else // standard C functions          #else // standard C functions
271          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
272          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
# Line 293  namespace RIFF { Line 308  namespace RIFF {
308       *  @see Resize()       *  @see Resize()
309       */       */
310      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {
311          if (pFile->Mode == stream_mode_read)          if (pFile->Mode != stream_mode_read_write)
312              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");
313          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize >= CurrentChunkSize)          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)
314              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
315          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
316              switch (WordSize) {              switch (WordSize) {
# Line 321  namespace RIFF { Line 336  namespace RIFF {
336          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
337          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");
338          writtenWords /= WordSize;          writtenWords /= WordSize;
339            #elif defined(WIN32)
340            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
341                throw Exception("Could not seek to position " + ToString(ulPos) +
342                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");            
343            }
344            DWORD writtenWords;
345            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
346            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
347            writtenWords /= WordSize;
348          #else // standard C functions          #else // standard C functions
349          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
350              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
# Line 667  namespace RIFF { Line 691  namespace RIFF {
691       *       *
692       * <b>Caution:</b> the buffer pointer will be invalidated once       * <b>Caution:</b> the buffer pointer will be invalidated once
693       * File::Save() was called. You have to call LoadChunkData() again to       * File::Save() was called. You have to call LoadChunkData() again to
694       * get a new pointer whenever File::Save() was called.       * get a new, valid pointer whenever File::Save() was called.
695         *
696         * You can call LoadChunkData() again if you previously scheduled to
697         * enlarge this chunk with a Resize() call. In that case the buffer will
698         * be enlarged to the new, scheduled chunk size and you can already
699         * place the new chunk data to the buffer and finally call File::Save()
700         * to enlarge the chunk physically and write the new data in one rush.
701         * This approach is definitely recommended if you have to enlarge and
702         * write new data to a lot of chunks.
703       *       *
704       * @returns a pointer to the data in RAM on success, NULL otherwise       * @returns a pointer to the data in RAM on success, NULL otherwise
705         * @throws Exception if data buffer could not be enlarged
706       * @see ReleaseChunkData()       * @see ReleaseChunkData()
707       */       */
708      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
709          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "") {
710              #if POSIX              #if POSIX
711              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
712              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
713              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());  
714              #else              #else
715              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
716              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
717                unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
718                pChunkData = new uint8_t[ulBufferSize];
719              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
720                memset(pChunkData, 0, ulBufferSize);
721                #if POSIX
722                unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
723                #elif defined(WIN32)
724                DWORD readWords;
725                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
726                #else
727              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
728              #endif // POSIX              #endif // POSIX
729              if (readWords != GetSize()) {              if (readWords != GetSize()) {
730                  delete[] pChunkData;                  delete[] pChunkData;
731                  return (pChunkData = NULL);                  return (pChunkData = NULL);
732              }              }
733                ulChunkDataSize = ulBufferSize;
734            } else if (NewChunkSize > ulChunkDataSize) {
735                uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
736                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
737                memset(pNewBuffer, 0 , NewChunkSize);
738                memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
739                delete[] pChunkData;
740                pChunkData      = pNewBuffer;
741                ulChunkDataSize = NewChunkSize;
742          }          }
743          return pChunkData;          return pChunkData;
744      }      }
# Line 718  namespace RIFF { Line 768  namespace RIFF {
768       *       *
769       * <b>Caution:</b> You cannot directly write to enlarged chunks before       * <b>Caution:</b> You cannot directly write to enlarged chunks before
770       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
771       * boundary.       * boundary!
772       *       *
773       * @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)
774       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a iNewSize is less than 1
# Line 726  namespace RIFF { Line 776  namespace RIFF {
776       */       */
777      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
778          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");
779            if (NewChunkSize == iNewSize) return;
780          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
781          pFile->LogAsResized(this);          pFile->LogAsResized(this);
782      }      }
# Line 743  namespace RIFF { Line 794  namespace RIFF {
794       *          (including its header size of course)       *          (including its header size of course)
795       */       */
796      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
797          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
798          ulWritePos += CHUNK_HEADER_SIZE;          ulWritePos += CHUNK_HEADER_SIZE;
799    
800            if (pFile->Mode != stream_mode_read_write)
801                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
802    
803          // if the whole chunk body was loaded into RAM          // if the whole chunk body was loaded into RAM
804          if (pChunkData) {          if (pChunkData) {
805              // 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
806              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;  
             }  
   
807              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
808              #if POSIX              #if POSIX
809              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
810              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
811                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
812              }              }
813                #elif defined(WIN32)
814                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
815                DWORD dwBytesWritten;
816                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
817                if (dwBytesWritten != NewChunkSize) {
818                    throw Exception("Writing Chunk data (from RAM) failed");
819                }
820              #else              #else
821              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
822              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 777  namespace RIFF { Line 827  namespace RIFF {
827              // 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
828              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
829              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
830                #if defined(WIN32)
831                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
832                #else
833              int iBytesMoved = 1;              int iBytesMoved = 1;
834                #endif
835              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
836                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
837                  #if POSIX                  #if POSIX
# Line 785  namespace RIFF { Line 839  namespace RIFF {
839                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
840                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
841                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
842                    #elif defined(WIN32)
843                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
844                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
845                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
846                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
847                  #else                  #else
848                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
849                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 806  namespace RIFF { Line 865  namespace RIFF {
865    
866          // add pad byte if needed          // add pad byte if needed
867          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ulStartPos + NewChunkSize) % 2 != 0) {
868              char cPadByte = 0;              const char cPadByte = 0;
869              #if POSIX              #if POSIX
870                lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
871              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
872                #elif defined(WIN32)
873                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
874                DWORD dwBytesWritten;
875                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
876              #else              #else
877                fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
878              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
879              #endif              #endif
880              return ulStartPos + NewChunkSize + 1;              return ulStartPos + NewChunkSize + 1;
# Line 1063  namespace RIFF { Line 1128  namespace RIFF {
1128      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1129          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");
1130          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1131          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, uiBodySize);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1132          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1133          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1134          pFile->ResizedChunks.push_back(pNewChunk);          pNewChunk->Resize(uiBodySize);
1135          return pNewChunk;          return pNewChunk;
1136      }      }
1137    
# Line 1091  namespace RIFF { Line 1156  namespace RIFF {
1156       *       *
1157       * 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
1158       * 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
1159       * 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,
1160       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1161         * should call File::Save() to make this change persistent at any time.
1162       *       *
1163       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1164       */       */
# Line 1123  namespace RIFF { Line 1189  namespace RIFF {
1189          #if POSIX          #if POSIX
1190          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1191          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1192            #elif defined(WIN32)
1193            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1194            DWORD dwBytesRead;
1195            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1196          #else          #else
1197          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1198          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1143  namespace RIFF { Line 1213  namespace RIFF {
1213          #if POSIX          #if POSIX
1214          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1215          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1216            #elif defined(WIN32)
1217            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1218            DWORD dwBytesWritten;
1219            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1220          #else          #else
1221          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1222          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
# Line 1182  namespace RIFF { Line 1256  namespace RIFF {
1256          }          }
1257      }      }
1258    
1259        void List::LoadSubChunksRecursively() {
1260            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1261                pList->LoadSubChunksRecursively();
1262        }
1263    
1264      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
1265       *       *
1266       * 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 1276  namespace RIFF {
1276       *          (including its header size of course)       *          (including its header size of course)
1277       */       */
1278      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1279          unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
1280          ulWritePos += LIST_HEADER_SIZE;          ulWritePos += LIST_HEADER_SIZE;
1281    
1282            if (pFile->Mode != stream_mode_read_write)
1283                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1284    
1285          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1286          if (pSubChunks) {          if (pSubChunks) {
1287              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 1293  namespace RIFF {
1293          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1294          WriteHeader(ulOriginalPos);          WriteHeader(ulOriginalPos);
1295    
1296            // offset of this list chunk in new written file may have changed
1297            ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1298    
1299          return ulWritePos;          return ulWritePos;
1300      }      }
1301    
# Line 1241  namespace RIFF { Line 1326  namespace RIFF {
1326       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1327       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1328       *       *
1329         * @param FileType - four-byte identifier of the RIFF file type
1330       * @see AddSubChunk(), AddSubList()       * @see AddSubChunk(), AddSubList()
1331       */       */
1332      File::File() : List(this) {      File::File(uint32_t FileType) : List(this) {
1333            #if defined(WIN32)
1334            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1335            #else
1336          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1337            #endif
1338            Mode = stream_mode_closed;
1339          bEndianNative = true;          bEndianNative = true;
1340          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1341            ListType = FileType;
1342      }      }
1343    
1344      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1268  namespace RIFF { Line 1360  namespace RIFF {
1360              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1361              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1362          }          }
1363            #elif defined(WIN32)
1364            hFileRead = hFileWrite = CreateFile(
1365                                         path.c_str(), GENERIC_READ,
1366                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1367                                         NULL, OPEN_EXISTING,
1368                                         FILE_ATTRIBUTE_NORMAL, NULL
1369                                     );
1370            if (hFileRead == INVALID_HANDLE_VALUE) {
1371                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1372                throw RIFF::Exception("Can't open \"" + path + "\"");
1373            }
1374          #else          #else
1375          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1376          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1377          #endif // POSIX          #endif // POSIX
1378            Mode = stream_mode_read;
1379          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1380          ReadHeader(0);          ReadHeader(0);
1381          if (ChunkID != CHUNK_ID_RIFF) {          if (ChunkID != CHUNK_ID_RIFF) {
# Line 1308  namespace RIFF { Line 1412  namespace RIFF {
1412                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1413                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1414                      }                      }
1415                        #elif defined(WIN32)
1416                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1417                        hFileRead = hFileWrite = CreateFile(
1418                                                     Filename.c_str(), GENERIC_READ,
1419                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1420                                                     NULL, OPEN_EXISTING,
1421                                                     FILE_ATTRIBUTE_NORMAL, NULL
1422                                                 );
1423                        if (hFileRead == INVALID_HANDLE_VALUE) {
1424                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1425                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1426                        }
1427                      #else                      #else
1428                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1429                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1430                      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");
1431                      #endif                      #endif
1432                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1433                      return true;                      break;
1434                  case stream_mode_read_write:                  case stream_mode_read_write:
1435                      #if POSIX                      #if POSIX
1436                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
# Line 1323  namespace RIFF { Line 1439  namespace RIFF {
1439                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1440                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1441                      }                      }
1442                        #elif defined(WIN32)
1443                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1444                        hFileRead = hFileWrite = CreateFile(
1445                                                     Filename.c_str(),
1446                                                     GENERIC_READ | GENERIC_WRITE,
1447                                                     FILE_SHARE_READ,
1448                                                     NULL, OPEN_ALWAYS,
1449                                                     FILE_ATTRIBUTE_NORMAL, NULL
1450                                                 );
1451                        if (hFileRead == INVALID_HANDLE_VALUE) {
1452                            hFileRead = hFileWrite = CreateFile(
1453                                                         Filename.c_str(), GENERIC_READ,
1454                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1455                                                         NULL, OPEN_EXISTING,
1456                                                         FILE_ATTRIBUTE_NORMAL, NULL
1457                                                     );
1458                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1459                        }
1460                      #else                      #else
1461                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1462                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1463                      if (!hFileRead) {                      if (!hFileRead) {
1464                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1465                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1466                      }                      }
1467                      #endif                      #endif
1468                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
1469                      return true;                      break;
1470                    case stream_mode_closed:
1471                        #if POSIX
1472                        if (hFileRead)  close(hFileRead);
1473                        if (hFileWrite) close(hFileWrite);
1474                        #elif defined(WIN32)
1475                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1476                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1477                        #else
1478                        if (hFileRead)  fclose(hFileRead);
1479                        if (hFileWrite) fclose(hFileWrite);
1480                        #endif
1481                        hFileRead = hFileWrite = 0;
1482                        break;
1483                  default:                  default:
1484                      throw Exception("Unknown file access mode");                      throw Exception("Unknown file access mode");
1485              }              }
1486                Mode = NewMode;
1487                return true;
1488          }          }
1489          return false;          return false;
1490      }      }
# Line 1351  namespace RIFF { Line 1500  namespace RIFF {
1500       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1501       */       */
1502      void File::Save() {      void File::Save() {
1503            // make sure the RIFF tree is built (from the original file)
1504            LoadSubChunksRecursively();
1505    
1506          // reopen file in write mode          // reopen file in write mode
1507          bool bModeWasChanged = SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1508    
1509          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
1510          // 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 1516  namespace RIFF {
1516          // 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)
1517          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1518          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1519              if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)");              if ((*iter)->GetNewSize() == 0) {
1520              unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte                  // just to make the exception message a bit more verbose: resolve the chunk's path
1521              if (ulDiff > 0) ulPositiveSizeDiff += ulDiff;                  String sChunkPath;
1522                    for (Chunk* pChunk = *iter; pChunk; pChunk = pChunk->GetParent()) {
1523                        if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
1524                            List* pList = (List*) pChunk;
1525                            sChunkPath = "->'" + pList->GetListTypeString() + "'" + sChunkPath;
1526                        } else {
1527                            sChunkPath = "->'" + pChunk->GetChunkIDString() + "'" + sChunkPath;
1528                        }
1529                    }
1530                    throw Exception("There is at least one empty chunk (zero size): " + sChunkPath);
1531                }
1532                if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {
1533                    unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte
1534                    ulPositiveSizeDiff += ulDiff;
1535                }
1536          }          }
1537    
1538          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1379  namespace RIFF { Line 1545  namespace RIFF {
1545              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1546              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1547              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1548              int iBytesMoved = 1;              #if defined(WIN32)
1549                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1550                #else
1551                int iBytesMoved = 1;
1552                #endif
1553              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {
1554                  const unsigned long ulToMove = ulFileSize - ulPos;                  const unsigned long ulToMove = ulFileSize - ulPos;
1555                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
# Line 1388  namespace RIFF { Line 1558  namespace RIFF {
1558                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1559                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1560                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1561                    #elif defined(WIN32)
1562                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1563                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1564                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1565                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1566                  #else                  #else
1567                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1568                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
# Line 1400  namespace RIFF { Line 1575  namespace RIFF {
1575          }          }
1576    
1577          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree
1578          unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff);          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);
1579            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1580    
1581          // resize file to the final size          // resize file to the final size
1582          if (ulTotalSize < ulWorkingFileSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1583    
1584          // forget all resized chunks          // forget all resized chunks
1585          ResizedChunks.clear();          ResizedChunks.clear();
   
         // reopen file in read mode  
         if (bModeWasChanged) SetMode(stream_mode_read);  
1586      }      }
1587    
1588      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1417  namespace RIFF { Line 1590  namespace RIFF {
1590       * Make all changes of all chunks persistent by writing them to another       * Make all changes of all chunks persistent by writing them to another
1591       * file. <b>Caution:</b> this method is optimized for writing to       * file. <b>Caution:</b> this method is optimized for writing to
1592       * <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
1593       * file! Use File::Save() in that case instead!       * file! Use File::Save() in that case instead! Ignoring this might
1594         * result in a corrupted file, especially in case chunks were resized!
1595       *       *
1596       * After calling this method, this File object will be associated with       * After calling this method, this File object will be associated with
1597       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
# Line 1425  namespace RIFF { Line 1599  namespace RIFF {
1599       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1600       */       */
1601      void File::Save(const String& path) {      void File::Save(const String& path) {
1602            //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
1603    
1604            // make sure the RIFF tree is built (from the original file)
1605            LoadSubChunksRecursively();
1606    
1607            if (Filename.length() > 0) SetMode(stream_mode_read);
1608          // 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
1609          #if POSIX          #if POSIX
1610          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);
1611          if (hFileWrite < 0) {          if (hFileWrite < 0) {
1612              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1613              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1614          }          }
1615            #elif defined(WIN32)
1616            hFileWrite = CreateFile(
1617                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1618                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL
1619                         );
1620            if (hFileWrite == INVALID_HANDLE_VALUE) {
1621                hFileWrite = hFileRead;
1622                throw Exception("Could not open file \"" + path + "\" for writing");
1623            }
1624          #else          #else
1625          hFileWrite = fopen(path.c_str(), "w+b");          hFileWrite = fopen(path.c_str(), "w+b");
1626          if (!hFileWrite) {          if (!hFileWrite) {
# Line 1439  namespace RIFF { Line 1628  namespace RIFF {
1628              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1629          }          }
1630          #endif // POSIX          #endif // POSIX
1631            Mode = stream_mode_read_write;
1632    
1633          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
1634          WriteChunk(0, 0);          unsigned long ulTotalSize  = WriteChunk(0, 0);
1635            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1636    
1637            // resize file to the final size (if the file was originally larger)
1638            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1639    
1640          // forget all resized chunks          // forget all resized chunks
1641          ResizedChunks.clear();          ResizedChunks.clear();
1642    
1643            if (Filename.length() > 0) {
1644                #if POSIX
1645                close(hFileWrite);
1646                #elif defined(WIN32)
1647                CloseHandle(hFileWrite);
1648                #else
1649                fclose(hFileWrite);
1650                #endif
1651                hFileWrite = hFileRead;
1652            }
1653    
1654          // associate new file with this File object from now on          // associate new file with this File object from now on
1655          Filename = path;          Filename = path;
1656          stream_mode_t oldMode = Mode;          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1657          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.  
1658      }      }
1659    
1660      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(unsigned long ulNewSize) {
1661          #if POSIX          #if POSIX
1662          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1663              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1664            #elif defined(WIN32)
1665            if (
1666                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1667                !SetEndOfFile(hFileWrite)
1668            ) throw Exception("Could not resize file \"" + Filename + "\"");
1669          #else          #else
1670          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1671          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1672          #endif          #endif
1673      }      }
1674    
# Line 1469  namespace RIFF { Line 1678  namespace RIFF {
1678         #endif // DEBUG         #endif // DEBUG
1679          #if POSIX          #if POSIX
1680          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1681            #elif defined(WIN32)
1682            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1683          #else          #else
1684          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1685          #endif // POSIX          #endif // POSIX
# Line 1478  namespace RIFF { Line 1689  namespace RIFF {
1689          ResizedChunks.push_back(pResizedChunk);          ResizedChunks.push_back(pResizedChunk);
1690      }      }
1691    
1692        void File::UnlogResized(Chunk* pResizedChunk) {
1693            ResizedChunks.remove(pResizedChunk);
1694        }
1695    
1696      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
1697          #if POSIX          return __GetFileSize(hFileRead);
1698        }
1699    
1700        #if POSIX
1701        unsigned long File::__GetFileSize(int hFile) {
1702          struct stat filestat;          struct stat filestat;
1703          fstat(hFileRead, &filestat);          fstat(hFile, &filestat);
1704          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  
1705          return size;          return size;
1706      }      }
1707        #elif defined(WIN32)
1708        unsigned long File::__GetFileSize(HANDLE hFile) {
1709            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1710            if (dwSize == INVALID_FILE_SIZE)
1711                throw Exception("Windows FS error: could not determine file size");
1712            return dwSize;
1713        }
1714        #else // standard C functions
1715        unsigned long File::__GetFileSize(FILE* hFile) {
1716            long curpos = ftell(hFile);
1717            fseek(hFile, 0, SEEK_END);
1718            long size = ftell(hFile);
1719            fseek(hFile, curpos, SEEK_SET);
1720            return size;
1721        }
1722        #endif
1723    
1724    
1725  // *************** Exception ***************  // *************** Exception ***************

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

  ViewVC Help
Powered by ViewVC