/[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 808 by schoenebeck, Tue Nov 22 09:11:17 2005 UTC revision 2682 by schoenebeck, Mon Dec 29 16:25:51 2014 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-2014 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    #include <set>
26  #include <string.h>  #include <string.h>
27    
28  #include "RIFF.h"  #include "RIFF.h"
29    
30  #include "helper.h"  #include "helper.h"
31    
32    #if POSIX
33    # include <errno.h>
34    #endif
35    
36  namespace RIFF {  namespace RIFF {
37    
38    // *************** Internal functions **************
39    // *
40    
41        /// Returns a human readable path of the given chunk.
42        static String __resolveChunkPath(Chunk* pCk) {
43            String sPath;
44            for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
45                if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
46                    List* pList = (List*) pChunk;
47                    sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
48                } else {
49                    sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
50                }
51            }
52            return sPath;
53        }
54    
55    
56    
57    // *************** progress_t ***************
58    // *
59    
60        progress_t::progress_t() {
61            callback    = NULL;
62            custom      = NULL;
63            __range_min = 0.0f;
64            __range_max = 1.0f;
65        }
66    
67    
68    
69  // *************** Chunk **************  // *************** Chunk **************
70  // *  // *
71    
# Line 39  namespace RIFF { Line 76  namespace RIFF {
76          ulPos      = 0;          ulPos      = 0;
77          pParent    = NULL;          pParent    = NULL;
78          pChunkData = NULL;          pChunkData = NULL;
79            CurrentChunkSize = 0;
80            NewChunkSize = 0;
81          ulChunkDataSize = 0;          ulChunkDataSize = 0;
82          ChunkID    = CHUNK_ID_RIFF;          ChunkID    = CHUNK_ID_RIFF;
83          this->pFile = pFile;          this->pFile = pFile;
# Line 53  namespace RIFF { Line 92  namespace RIFF {
92          pParent       = Parent;          pParent       = Parent;
93          ulPos         = 0;          ulPos         = 0;
94          pChunkData    = NULL;          pChunkData    = NULL;
95            CurrentChunkSize = 0;
96            NewChunkSize = 0;
97          ulChunkDataSize = 0;          ulChunkDataSize = 0;
98          ReadHeader(StartPos);          ReadHeader(StartPos);
99      }      }
# Line 63  namespace RIFF { Line 104  namespace RIFF {
104          this->pParent    = pParent;          this->pParent    = pParent;
105          ulPos            = 0;          ulPos            = 0;
106          pChunkData       = NULL;          pChunkData       = NULL;
         ulChunkDataSize  = 0;  
107          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
108            ulChunkDataSize  = 0;
109          CurrentChunkSize = 0;          CurrentChunkSize = 0;
110          NewChunkSize     = uiBodySize;          NewChunkSize     = uiBodySize;
111      }      }
112    
113      Chunk::~Chunk() {      Chunk::~Chunk() {
114            if (pFile) pFile->UnlogResized(this);
115          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
116      }      }
117    
# Line 77  namespace RIFF { Line 119  namespace RIFF {
119          #if DEBUG          #if DEBUG
120          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << fPos << ") ";
121          #endif // DEBUG          #endif // DEBUG
122            ChunkID = 0;
123            NewChunkSize = CurrentChunkSize = 0;
124          #if POSIX          #if POSIX
125          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
126              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
127              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
128            #elif defined(WIN32)
129            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
130                DWORD dwBytesRead;
131                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
132                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
133          #else          #else
134          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
135              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
# Line 102  namespace RIFF { Line 151  namespace RIFF {
151              }              }
152              #if DEBUG              #if DEBUG
153              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
154              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << CurrentChunkSize << " ";
155              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
156              #endif // DEBUG              #endif // DEBUG
157              NewChunkSize = CurrentChunkSize;              NewChunkSize = CurrentChunkSize;
158          }          }
# Line 129  namespace RIFF { Line 178  namespace RIFF {
178              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
179              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &uiNewChunkSize, 4);
180          }          }
181            #elif defined(WIN32)
182            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
183                DWORD dwBytesWritten;
184                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
185                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
186            }
187          #else          #else
188          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
189              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
# Line 193  namespace RIFF { Line 248  namespace RIFF {
248         #if DEBUG         #if DEBUG
249         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;
250         #endif // DEBUG         #endif // DEBUG
251          return CurrentChunkSize - ulPos;          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;
252      }      }
253    
254      /**      /**
# Line 204  namespace RIFF { Line 259  namespace RIFF {
259       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
260       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
261       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
262       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
263       *    possible without SetPos()       *    possible without SetPos()
264       */       */
265      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
# Line 212  namespace RIFF { Line 267  namespace RIFF {
267        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
268        #endif // DEBUG        #endif // DEBUG
269          #if POSIX          #if POSIX
270          if (pFile->hFileRead == 0)    return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
271            #elif defined (WIN32)
272            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
273                return stream_closed;
274          #else          #else
275          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
276          #endif // POSIX          #endif // POSIX
# Line 239  namespace RIFF { Line 297  namespace RIFF {
297         #if DEBUG         #if DEBUG
298         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
299         #endif // DEBUG         #endif // DEBUG
300            //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
301          if (ulPos >= CurrentChunkSize) return 0;          if (ulPos >= CurrentChunkSize) return 0;
302          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
303          #if POSIX          #if POSIX
# Line 246  namespace RIFF { Line 305  namespace RIFF {
305          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
306          if (readWords < 1) return 0;          if (readWords < 1) return 0;
307          readWords /= WordSize;          readWords /= WordSize;
308            #elif defined(WIN32)
309            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
310            DWORD readWords;
311            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
312            if (readWords < 1) return 0;
313            readWords /= WordSize;
314          #else // standard C functions          #else // standard C functions
315          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
316          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
# Line 315  namespace RIFF { Line 380  namespace RIFF {
380          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
381          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");
382          writtenWords /= WordSize;          writtenWords /= WordSize;
383            #elif defined(WIN32)
384            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
385                throw Exception("Could not seek to position " + ToString(ulPos) +
386                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
387            }
388            DWORD writtenWords;
389            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
390            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
391            writtenWords /= WordSize;
392          #else // standard C functions          #else // standard C functions
393          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
394              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
# Line 537  namespace RIFF { Line 611  namespace RIFF {
611      }      }
612    
613      /**      /**
614         * Reads a null-padded string of size characters and copies it
615         * into the string \a s. The position within the chunk will
616         * automatically be incremented.
617         *
618         * @param s                 destination string
619         * @param size              number of characters to read
620         * @throws RIFF::Exception  if an error occured or less than
621         *                          \a size characters could be read!
622         */
623        void Chunk::ReadString(String& s, int size) {
624            char* buf = new char[size];
625            ReadSceptical(buf, 1, size);
626            s.assign(buf, std::find(buf, buf + size, '\0'));
627            delete[] buf;
628        }
629    
630        /**
631       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
632       * buffer pointed by \a pData to the chunk's body, directly to the       * buffer pointed by \a pData to the chunk's body, directly to the
633       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 676  namespace RIFF { Line 767  namespace RIFF {
767       * @see ReleaseChunkData()       * @see ReleaseChunkData()
768       */       */
769      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
770          if (!pChunkData && pFile->Filename != "") {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
771              #if POSIX              #if POSIX
772              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
773                #elif defined(WIN32)
774                if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;
775              #else              #else
776              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
777              #endif // POSIX              #endif // POSIX
# Line 688  namespace RIFF { Line 781  namespace RIFF {
781              memset(pChunkData, 0, ulBufferSize);              memset(pChunkData, 0, ulBufferSize);
782              #if POSIX              #if POSIX
783              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
784                #elif defined(WIN32)
785                DWORD readWords;
786                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
787              #else              #else
788              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
789              #endif // POSIX              #endif // POSIX
# Line 740  namespace RIFF { Line 836  namespace RIFF {
836       * @see File::Save()       * @see File::Save()
837       */       */
838      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
839          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0)
840                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
841          if (NewChunkSize == iNewSize) return;          if (NewChunkSize == iNewSize) return;
842          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
843          pFile->LogAsResized(this);          pFile->LogAsResized(this);
# Line 754  namespace RIFF { Line 851  namespace RIFF {
851       *                     chunk should be written to       *                     chunk should be written to
852       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ulCurrentDataOffset - offset of current (old) data within
853       *                              the file       *                              the file
854         * @param pProgress - optional: callback function for progress notification
855       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
856       *          \a ulWritePos incremented by this chunk's new size       *          \a ulWritePos incremented by this chunk's new size
857       *          (including its header size of course)       *          (including its header size of course)
858       */       */
859      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset, progress_t* pProgress) {
860          const unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
861          ulWritePos += CHUNK_HEADER_SIZE;          ulWritePos += CHUNK_HEADER_SIZE;
862    
# Line 775  namespace RIFF { Line 873  namespace RIFF {
873              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
874                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
875              }              }
876                #elif defined(WIN32)
877                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
878                DWORD dwBytesWritten;
879                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
880                if (dwBytesWritten != NewChunkSize) {
881                    throw Exception("Writing Chunk data (from RAM) failed");
882                }
883              #else              #else
884              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
885              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 785  namespace RIFF { Line 890  namespace RIFF {
890              // 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
891              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
892              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
893                #if defined(WIN32)
894                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
895                #else
896              int iBytesMoved = 1;              int iBytesMoved = 1;
897              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              #endif
898                for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
899                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
900                  #if POSIX                  #if POSIX
901                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
902                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
903                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
904                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
905                    #elif defined(WIN32)
906                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
907                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
908                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
909                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
910                  #else                  #else
911                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
912                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 808  namespace RIFF { Line 922  namespace RIFF {
922          CurrentChunkSize = NewChunkSize;          CurrentChunkSize = NewChunkSize;
923          WriteHeader(ulOriginalPos);          WriteHeader(ulOriginalPos);
924    
925            __notify_progress(pProgress, 1.0); // notify done
926    
927          // update chunk's position pointers          // update chunk's position pointers
928          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;
929          ulPos      = 0;          ulPos      = 0;
# Line 818  namespace RIFF { Line 934  namespace RIFF {
934              #if POSIX              #if POSIX
935              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
936              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
937                #elif defined(WIN32)
938                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
939                DWORD dwBytesWritten;
940                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
941              #else              #else
942              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
943              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
# Line 867  namespace RIFF { Line 987  namespace RIFF {
987        #if DEBUG        #if DEBUG
988        std::cout << "List::~List()" << std::endl;        std::cout << "List::~List()" << std::endl;
989        #endif // DEBUG        #endif // DEBUG
990            DeleteChunkList();
991        }
992    
993        void List::DeleteChunkList() {
994          if (pSubChunks) {          if (pSubChunks) {
995              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
996              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 875  namespace RIFF { Line 999  namespace RIFF {
999                  iter++;                  iter++;
1000              }              }
1001              delete pSubChunks;              delete pSubChunks;
1002                pSubChunks = NULL;
1003            }
1004            if (pSubChunksMap) {
1005                delete pSubChunksMap;
1006                pSubChunksMap = NULL;
1007          }          }
         if (pSubChunksMap) delete pSubChunksMap;  
1008      }      }
1009    
1010      /**      /**
# Line 1077  namespace RIFF { Line 1205  namespace RIFF {
1205          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1206          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1207          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(uiBodySize);
1208            NewChunkSize += CHUNK_HEADER_SIZE;
1209            pFile->LogAsResized(this);
1210          return pNewChunk;          return pNewChunk;
1211      }      }
1212    
1213        /** @brief Moves a sub chunk witin this list.
1214         *
1215         * Moves a sub chunk from one position in this list to another
1216         * position in the same list. The pSrc chunk is placed before the
1217         * pDst chunk.
1218         *
1219         * @param pSrc - sub chunk to be moved
1220         * @param pDst - the position to move to. pSrc will be placed
1221         *               before pDst. If pDst is 0, pSrc will be placed
1222         *               last in list.
1223         */
1224        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1225            if (!pSubChunks) LoadSubChunks();
1226            pSubChunks->remove(pSrc);
1227            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1228            pSubChunks->insert(iter, pSrc);
1229        }
1230    
1231        /** @brief Moves a sub chunk from this list to another list.
1232         *
1233         * Moves a sub chunk from this list list to the end of another
1234         * list.
1235         *
1236         * @param pSrc - sub chunk to be moved
1237         * @param pDst - destination list where the chunk shall be moved to
1238         */
1239        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1240            if (pNewParent == this || !pNewParent) return;
1241            if (!pSubChunks) LoadSubChunks();
1242            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1243            pSubChunks->remove(pSrc);
1244            pNewParent->pSubChunks->push_back(pSrc);
1245            // update chunk id map of this List
1246            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1247                pSubChunksMap->erase(pSrc->GetChunkID());
1248                // try to find another chunk of the same chunk ID
1249                ChunkList::iterator iter = pSubChunks->begin();
1250                ChunkList::iterator end  = pSubChunks->end();
1251                for (; iter != end; ++iter) {
1252                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1253                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1254                        break; // we're done, stop search
1255                    }
1256                }
1257            }
1258            // update chunk id map of other list
1259            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1260                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1261        }
1262    
1263      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1264       *       *
1265       * 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 1094  namespace RIFF { Line 1274  namespace RIFF {
1274          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1275          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1276          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1277            NewChunkSize += LIST_HEADER_SIZE;
1278            pFile->LogAsResized(this);
1279          return pNewListChunk;          return pNewListChunk;
1280      }      }
1281    
# Line 1101  namespace RIFF { Line 1283  namespace RIFF {
1283       *       *
1284       * 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
1285       * 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
1286       * 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,
1287       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1288         * should call File::Save() to make this change persistent at any time.
1289       *       *
1290       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1291       */       */
# Line 1129  namespace RIFF { Line 1312  namespace RIFF {
1312        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1313        #endif // DEBUG        #endif // DEBUG
1314          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1315            if (CurrentChunkSize < 4) return;
1316          NewChunkSize = CurrentChunkSize -= 4;          NewChunkSize = CurrentChunkSize -= 4;
1317          #if POSIX          #if POSIX
1318          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1319          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1320            #elif defined(WIN32)
1321            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1322            DWORD dwBytesRead;
1323            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1324          #else          #else
1325          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1326          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1153  namespace RIFF { Line 1341  namespace RIFF {
1341          #if POSIX          #if POSIX
1342          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1343          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1344            #elif defined(WIN32)
1345            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1346            DWORD dwBytesWritten;
1347            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1348          #else          #else
1349          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1350          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
1351          #endif // POSIX          #endif // POSIX
1352      }      }
1353    
1354      void List::LoadSubChunks() {      void List::LoadSubChunks(progress_t* pProgress) {
1355         #if DEBUG         #if DEBUG
1356         std::cout << "List::LoadSubChunks()";         std::cout << "List::LoadSubChunks()";
1357         #endif // DEBUG         #endif // DEBUG
1358          if (!pSubChunks) {          if (!pSubChunks) {
1359              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1360              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1361                #if defined(WIN32)
1362                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1363                #else
1364              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1365                #endif
1366              unsigned long uiOriginalPos = GetPos();              unsigned long uiOriginalPos = GetPos();
1367              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1368              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
# Line 1190  namespace RIFF { Line 1386  namespace RIFF {
1386              }              }
1387              SetPos(uiOriginalPos); // restore position before this call              SetPos(uiOriginalPos); // restore position before this call
1388          }          }
1389            __notify_progress(pProgress, 1.0); // notify done
1390        }
1391    
1392        void List::LoadSubChunksRecursively(progress_t* pProgress) {
1393            const int n = CountSubLists();
1394            int i = 0;
1395            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList(), ++i) {
1396                // divide local progress into subprogress
1397                progress_t subprogress;
1398                __divide_progress(pProgress, &subprogress, n, i);
1399                // do the actual work
1400                pList->LoadSubChunksRecursively(&subprogress);
1401            }
1402            __notify_progress(pProgress, 1.0); // notify done
1403      }      }
1404    
1405      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
# Line 1202  namespace RIFF { Line 1412  namespace RIFF {
1412       *                     list chunk should be written to       *                     list chunk should be written to
1413       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ulCurrentDataOffset - offset of current (old) data within
1414       *                              the file       *                              the file
1415         * @param pProgress - optional: callback function for progress notification
1416       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
1417       *          \a ulWritePos incremented by this list chunk's new size       *          \a ulWritePos incremented by this list chunk's new size
1418       *          (including its header size of course)       *          (including its header size of course)
1419       */       */
1420      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset, progress_t* pProgress) {
1421          const unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
1422          ulWritePos += LIST_HEADER_SIZE;          ulWritePos += LIST_HEADER_SIZE;
1423    
# Line 1215  namespace RIFF { Line 1426  namespace RIFF {
1426    
1427          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1428          if (pSubChunks) {          if (pSubChunks) {
1429              for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {              int i = 0;
1430                  ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);              const int n = pSubChunks->size();
1431                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1432                    // divide local progress into subprogress for loading current Instrument
1433                    progress_t subprogress;
1434                    __divide_progress(pProgress, &subprogress, n, i);
1435                    // do the actual work
1436                    ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset, &subprogress);
1437              }              }
1438          }          }
1439    
# Line 1227  namespace RIFF { Line 1444  namespace RIFF {
1444          // offset of this list chunk in new written file may have changed          // offset of this list chunk in new written file may have changed
1445          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1446    
1447             __notify_progress(pProgress, 1.0); // notify done
1448    
1449          return ulWritePos;          return ulWritePos;
1450      }      }
1451    
# Line 1251  namespace RIFF { Line 1470  namespace RIFF {
1470  // *************** File ***************  // *************** File ***************
1471  // *  // *
1472    
1473    //HACK: to avoid breaking DLL compatibility to older versions of libgig we roll the new std::set<Chunk*> into the old std::list<Chunk*> container, should be replaced on member variable level soon though
1474    #define _GET_RESIZED_CHUNKS() \
1475            (reinterpret_cast<std::set<Chunk*>*>(ResizedChunks.front()))
1476    
1477      /** @brief Create new RIFF file.      /** @brief Create new RIFF file.
1478       *       *
1479       * Use this constructor if you want to create a new RIFF file completely       * Use this constructor if you want to create a new RIFF file completely
1480       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1481       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1482       *       *
1483         * Note: by default, the RIFF file will be saved in native endian
1484         * format; that is, as a RIFF file on little-endian machines and
1485         * as a RIFX file on big-endian. To change this behaviour, call
1486         * SetByteOrder() before calling Save().
1487         *
1488       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1489       * @see AddSubChunk(), AddSubList()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1490       */       */
1491      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType)
1492            : List(this), bIsNewFile(true), Layout(layout_standard)
1493        {
1494            //HACK: see _GET_RESIZED_CHUNKS() comment
1495            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1496            #if defined(WIN32)
1497            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1498            #else
1499          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1500            #endif
1501          Mode = stream_mode_closed;          Mode = stream_mode_closed;
1502          bEndianNative = true;          bEndianNative = true;
1503          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
# Line 1276  namespace RIFF { Line 1512  namespace RIFF {
1512       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occured while trying to load the
1513       *                         given RIFF file       *                         given RIFF file
1514       */       */
1515      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path)
1516        #if DEBUG          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard)
1517        std::cout << "File::File("<<path<<")" << std::endl;      {
1518        #endif // DEBUG         #if DEBUG
1519           std::cout << "File::File("<<path<<")" << std::endl;
1520           #endif // DEBUG
1521          bEndianNative = true;          bEndianNative = true;
1522            try {
1523                __openExistingFile(path);
1524                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1525                    throw RIFF::Exception("Not a RIFF file");
1526                }
1527            }
1528            catch (...) {
1529                Cleanup();
1530                throw;
1531            }
1532        }
1533    
1534        /** @brief Load existing RIFF-like file.
1535         *
1536         * Loads an existing file, which is not a "real" RIFF file, but similar to
1537         * an ordinary RIFF file.
1538         *
1539         * A "real" RIFF file contains at top level a List chunk either with chunk
1540         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1541         * case, and if it finds the toplevel List chunk to have another chunk ID
1542         * than one of those two expected ones, it would throw an Exception and
1543         * would refuse to load the file accordingly.
1544         *
1545         * Since there are however a lot of file formats which use the same simple
1546         * principles of the RIFF format, with another toplevel List chunk ID
1547         * though, you can use this alternative constructor here to be able to load
1548         * and handle those files in the same way as you would do with "real" RIFF
1549         * files.
1550         *
1551         * @param path - path and file name of the RIFF-alike file to be opened
1552         * @param FileType - expected toplevel List chunk ID (this is the very
1553         *                   first chunk found in the file)
1554         * @param Endian - whether the file uses little endian or big endian layout
1555         * @param layout - general file structure type
1556         * @throws RIFF::Exception if error occured while trying to load the
1557         *                         given RIFF-alike file
1558         */
1559        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout)
1560            : List(this), Filename(path), bIsNewFile(false), Layout(layout)
1561        {
1562            SetByteOrder(Endian);
1563            try {
1564                __openExistingFile(path, &FileType);
1565            }
1566            catch (...) {
1567                Cleanup();
1568                throw;
1569            }
1570        }
1571    
1572        /**
1573         * Opens an already existing RIFF file or RIFF-alike file. This method
1574         * shall only be called once (in a File class constructor).
1575         *
1576         * @param path - path and file name of the RIFF file or RIFF-alike file to
1577         *               be opened
1578         * @param FileType - (optional) expected chunk ID of first chunk in file
1579         * @throws RIFF::Exception if error occured while trying to load the
1580         *                         given RIFF file or RIFF-alike file
1581         */
1582        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1583            //HACK: see _GET_RESIZED_CHUNKS() comment
1584            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1585          #if POSIX          #if POSIX
1586          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1587          if (hFileRead <= 0) {          if (hFileRead == -1) {
1588              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1589                String sError = strerror(errno);
1590                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1591            }
1592            #elif defined(WIN32)
1593            hFileRead = hFileWrite = CreateFile(
1594                                         path.c_str(), GENERIC_READ,
1595                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1596                                         NULL, OPEN_EXISTING,
1597                                         FILE_ATTRIBUTE_NORMAL |
1598                                         FILE_FLAG_RANDOM_ACCESS, NULL
1599                                     );
1600            if (hFileRead == INVALID_HANDLE_VALUE) {
1601                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1602              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1603          }          }
1604          #else          #else
1605          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1606          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1607          #endif // POSIX          #endif // POSIX
1608          Mode = stream_mode_read;          Mode = stream_mode_read;
1609          ulStartPos = RIFF_HEADER_SIZE;          switch (Layout) {
1610          ReadHeader(0);              case layout_standard: // this is a normal RIFF file
1611          if (ChunkID != CHUNK_ID_RIFF) {                  ulStartPos = RIFF_HEADER_SIZE;
1612              throw RIFF::Exception("Not a RIFF file");                  ReadHeader(0);
1613                    if (FileType && ChunkID != *FileType)
1614                        throw RIFF::Exception("Invalid file container ID");
1615                    break;
1616                case layout_flat: // non-standard RIFF-alike file
1617                    ulStartPos = 0;
1618                    NewChunkSize = CurrentChunkSize = GetFileSize();
1619                    if (FileType) {
1620                        uint32_t ckid;
1621                        if (Read(&ckid, 4, 1) != 4) {
1622                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1623                        } else if (ckid != *FileType) {
1624                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1625                            throw RIFF::Exception("Invalid file header ID" + s);
1626                        }
1627                        SetPos(0); // reset to first byte of file
1628                    }
1629                    LoadSubChunks();
1630                    break;
1631          }          }
1632      }      }
1633    
1634      String File::GetFileName() {      String File::GetFileName() {
1635          return Filename;          return Filename;
1636      }      }
1637        
1638        void File::SetFileName(const String& path) {
1639            Filename = path;
1640        }
1641    
1642      stream_mode_t File::GetMode() {      stream_mode_t File::GetMode() {
1643          return Mode;          return Mode;
1644      }      }
1645    
1646        layout_t File::GetLayout() const {
1647            return Layout;
1648        }
1649    
1650      /** @brief Change file access mode.      /** @brief Change file access mode.
1651       *       *
1652       * Changes files access mode either to read-only mode or to read/write       * Changes files access mode either to read-only mode or to read/write
# Line 1324  namespace RIFF { Line 1664  namespace RIFF {
1664                      #if POSIX                      #if POSIX
1665                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1666                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1667                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1668                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1669                            String sError = strerror(errno);
1670                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1671                        }
1672                        #elif defined(WIN32)
1673                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1674                        hFileRead = hFileWrite = CreateFile(
1675                                                     Filename.c_str(), GENERIC_READ,
1676                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1677                                                     NULL, OPEN_EXISTING,
1678                                                     FILE_ATTRIBUTE_NORMAL |
1679                                                     FILE_FLAG_RANDOM_ACCESS,
1680                                                     NULL
1681                                                 );
1682                        if (hFileRead == INVALID_HANDLE_VALUE) {
1683                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1684                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1685                      }                      }
1686                      #else                      #else
1687                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1688                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1689                      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");
1690                      #endif                      #endif
1691                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
# Line 1339  namespace RIFF { Line 1694  namespace RIFF {
1694                      #if POSIX                      #if POSIX
1695                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1696                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1697                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1698                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1699                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          String sError = strerror(errno);
1700                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1701                        }
1702                        #elif defined(WIN32)
1703                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1704                        hFileRead = hFileWrite = CreateFile(
1705                                                     Filename.c_str(),
1706                                                     GENERIC_READ | GENERIC_WRITE,
1707                                                     FILE_SHARE_READ,
1708                                                     NULL, OPEN_ALWAYS,
1709                                                     FILE_ATTRIBUTE_NORMAL |
1710                                                     FILE_FLAG_RANDOM_ACCESS,
1711                                                     NULL
1712                                                 );
1713                        if (hFileRead == INVALID_HANDLE_VALUE) {
1714                            hFileRead = hFileWrite = CreateFile(
1715                                                         Filename.c_str(), GENERIC_READ,
1716                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1717                                                         NULL, OPEN_EXISTING,
1718                                                         FILE_ATTRIBUTE_NORMAL |
1719                                                         FILE_FLAG_RANDOM_ACCESS,
1720                                                         NULL
1721                                                     );
1722                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1723                      }                      }
1724                      #else                      #else
1725                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1726                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1727                      if (!hFileRead) {                      if (!hFileRead) {
1728                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1729                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1730                      }                      }
1731                      #endif                      #endif
# Line 1357  namespace RIFF { Line 1735  namespace RIFF {
1735                      #if POSIX                      #if POSIX
1736                      if (hFileRead)  close(hFileRead);                      if (hFileRead)  close(hFileRead);
1737                      if (hFileWrite) close(hFileWrite);                      if (hFileWrite) close(hFileWrite);
1738                        #elif defined(WIN32)
1739                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1740                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1741                      #else                      #else
1742                      if (hFileRead)  fclose(hFileRead);                      if (hFileRead)  fclose(hFileRead);
1743                      if (hFileWrite) fclose(hFileWrite);                      if (hFileWrite) fclose(hFileWrite);
# Line 1372  namespace RIFF { Line 1753  namespace RIFF {
1753          return false;          return false;
1754      }      }
1755    
1756        /** @brief Set the byte order to be used when saving.
1757         *
1758         * Set the byte order to be used in the file. A value of
1759         * endian_little will create a RIFF file, endian_big a RIFX file
1760         * and endian_native will create a RIFF file on little-endian
1761         * machines and RIFX on big-endian machines.
1762         *
1763         * @param Endian - endianess to use when file is saved.
1764         */
1765        void File::SetByteOrder(endian_t Endian) {
1766            #if WORDS_BIGENDIAN
1767            bEndianNative = Endian != endian_little;
1768            #else
1769            bEndianNative = Endian != endian_big;
1770            #endif
1771        }
1772    
1773      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1774       *       *
1775       * Make all changes of all chunks persistent by writing them to the       * Make all changes of all chunks persistent by writing them to the
# Line 1379  namespace RIFF { Line 1777  namespace RIFF {
1777       * than it will have at the end of the saving process, in case chunks       * than it will have at the end of the saving process, in case chunks
1778       * were grown.       * were grown.
1779       *       *
1780         * @param pProgress - optional: callback function for progress notification
1781       * @throws RIFF::Exception if there is an empty chunk or empty list       * @throws RIFF::Exception if there is an empty chunk or empty list
1782       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1783       */       */
1784      void File::Save() {      void File::Save(progress_t* pProgress) {
1785            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1786            if (Layout == layout_flat)
1787                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1788    
1789            // make sure the RIFF tree is built (from the original file)
1790            {
1791                // divide progress into subprogress
1792                progress_t subprogress;
1793                __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
1794                // do the actual work
1795                LoadSubChunksRecursively(&subprogress);
1796                // notify subprogress done
1797                __notify_progress(&subprogress, 1.f);
1798            }
1799    
1800          // reopen file in write mode          // reopen file in write mode
1801          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1802    
# Line 1395  namespace RIFF { Line 1809  namespace RIFF {
1809    
1810          // 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)
1811          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1812          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          std::set<Chunk*>* resizedChunks = _GET_RESIZED_CHUNKS();
1813              if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)");          for (std::set<Chunk*>::const_iterator iter = resizedChunks->begin(), end = resizedChunks->end(); iter != end; ++iter) {
1814              if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {              if ((*iter)->GetNewSize() == 0) {
1815                  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));
                 ulPositiveSizeDiff += ulDiff;  
1816              }              }
1817                unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1818                unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1819                if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1820          }          }
1821    
1822          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
1823    
1824          // if there are positive size changes...          // if there are positive size changes...
1825          if (ulPositiveSizeDiff > 0) {          if (ulPositiveSizeDiff > 0) {
1826                // divide progress into subprogress
1827                progress_t subprogress;
1828                __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1829    
1830              // ... we enlarge this file first ...              // ... we enlarge this file first ...
1831              ulWorkingFileSize += ulPositiveSizeDiff;              ulWorkingFileSize += ulPositiveSizeDiff;
1832              ResizeFile(ulWorkingFileSize);              ResizeFile(ulWorkingFileSize);
1833              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1834              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1835              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1836                #if defined(WIN32)
1837                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1838                #else
1839              int iBytesMoved = 1;              int iBytesMoved = 1;
1840              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              #endif
1841                  const unsigned long ulToMove = ulFileSize - ulPos;              for (unsigned long ulPos = ulFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1842                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1843                    ulPos -= iBytesMoved;
1844                  #if POSIX                  #if POSIX
1845                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ulPos, SEEK_SET);
1846                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1847                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1848                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1849                    #elif defined(WIN32)
1850                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1851                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1852                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1853                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1854                  #else                  #else
1855                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1856                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1857                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1858                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1859                  #endif                  #endif
1860                    if (!(iNotif % 8) && iBytesMoved > 0)
1861                        __notify_progress(&subprogress, float(ulFileSize - ulPos) / float(ulFileSize));
1862              }              }
1863              delete[] pCopyBuffer;              delete[] pCopyBuffer;
1864              if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");              if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1865    
1866                __notify_progress(&subprogress, 1.f); // notify subprogress done
1867          }          }
1868    
1869          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree ...
1870          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);  
1871            // divide progress into subprogress
1872            progress_t subprogress;
1873            __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
1874            // do the actual work
1875            unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff, &subprogress);
1876          unsigned long ulActualSize = __GetFileSize(hFileWrite);          unsigned long ulActualSize = __GetFileSize(hFileWrite);
1877            // notify subprogress done
1878            __notify_progress(&subprogress, 1.f);
1879    
1880          // resize file to the final size          // resize file to the final size
1881          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1882    
1883          // forget all resized chunks          // forget all resized chunks
1884          ResizedChunks.clear();          resizedChunks->clear();
1885    
1886            __notify_progress(pProgress, 1.0); // notify done
1887      }      }
1888    
1889      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1456  namespace RIFF { Line 1898  namespace RIFF {
1898       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
1899       *       *
1900       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1901         * @param pProgress - optional: callback function for progress notification
1902       */       */
1903      void File::Save(const String& path) {      void File::Save(const String& path, progress_t* pProgress) {
1904          //TODO: we should make a check here if somebody tries to write to the same file and automatically call the other Save() method in that case          //TODO: we should make a check here if somebody tries to write to the same file and automatically call the other Save() method in that case
1905    
1906          if (Filename.length() > 0) SetMode(stream_mode_read);          //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1907            if (Layout == layout_flat)
1908                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1909    
1910            // make sure the RIFF tree is built (from the original file)
1911            {
1912                // divide progress into subprogress
1913                progress_t subprogress;
1914                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
1915                // do the actual work
1916                LoadSubChunksRecursively(&subprogress);
1917                // notify subprogress done
1918                __notify_progress(&subprogress, 1.f);
1919            }
1920    
1921            if (!bIsNewFile) SetMode(stream_mode_read);
1922          // 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
1923          #if POSIX          #if POSIX
1924          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1925          if (hFileWrite < 0) {          if (hFileWrite == -1) {
1926                hFileWrite = hFileRead;
1927                String sError = strerror(errno);
1928                throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
1929            }
1930            #elif defined(WIN32)
1931            hFileWrite = CreateFile(
1932                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1933                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1934                             FILE_FLAG_RANDOM_ACCESS, NULL
1935                         );
1936            if (hFileWrite == INVALID_HANDLE_VALUE) {
1937              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1938              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1939          }          }
# Line 1478  namespace RIFF { Line 1947  namespace RIFF {
1947          Mode = stream_mode_read_write;          Mode = stream_mode_read_write;
1948    
1949          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
1950          unsigned long ulTotalSize  = WriteChunk(0, 0);          unsigned long ulTotalSize;
1951            {
1952                // divide progress into subprogress
1953                progress_t subprogress;
1954                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
1955                // do the actual work
1956                ulTotalSize = WriteChunk(0, 0, &subprogress);
1957                // notify subprogress done
1958                __notify_progress(&subprogress, 1.f);
1959            }
1960          unsigned long ulActualSize = __GetFileSize(hFileWrite);          unsigned long ulActualSize = __GetFileSize(hFileWrite);
1961    
1962          // resize file to the final size (if the file was originally larger)          // resize file to the final size (if the file was originally larger)
1963          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1964    
1965          // forget all resized chunks          // forget all resized chunks
1966          ResizedChunks.clear();          _GET_RESIZED_CHUNKS()->clear();
1967    
1968          if (Filename.length() > 0) {          #if POSIX
1969              #if POSIX          if (hFileWrite) close(hFileWrite);
1970              close(hFileWrite);          #elif defined(WIN32)
1971              #else          if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1972              fclose(hFileWrite);          #else
1973              #endif          if (hFileWrite) fclose(hFileWrite);
1974              hFileWrite = hFileRead;          #endif
1975          }          hFileWrite = hFileRead;
1976    
1977          // associate new file with this File object from now on          // associate new file with this File object from now on
1978          Filename = path;          Filename = path;
1979            bIsNewFile = false;
1980          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1981          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
1982    
1983            __notify_progress(pProgress, 1.0); // notify done
1984      }      }
1985    
1986      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(unsigned long ulNewSize) {
1987          #if POSIX          #if POSIX
1988          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1989              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1990            #elif defined(WIN32)
1991            if (
1992                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1993                !SetEndOfFile(hFileWrite)
1994            ) throw Exception("Could not resize file \"" + Filename + "\"");
1995          #else          #else
1996          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1997          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1998          #endif          #endif
1999      }      }
# Line 1516  namespace RIFF { Line 2002  namespace RIFF {
2002         #if DEBUG         #if DEBUG
2003         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
2004         #endif // DEBUG         #endif // DEBUG
2005            Cleanup();
2006        }
2007        
2008        /**
2009         * Returns @c true if this file has been created new from scratch and
2010         * has not been stored to disk yet.
2011         */
2012        bool File::IsNew() const {
2013            return bIsNewFile;
2014        }
2015    
2016        void File::Cleanup() {
2017          #if POSIX          #if POSIX
2018          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
2019            #elif defined(WIN32)
2020            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
2021          #else          #else
2022          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
2023          #endif // POSIX          #endif // POSIX
2024            DeleteChunkList();
2025            pFile = NULL;
2026            //HACK: see _GET_RESIZED_CHUNKS() comment
2027            delete _GET_RESIZED_CHUNKS();
2028      }      }
2029    
2030      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {
2031          ResizedChunks.push_back(pResizedChunk);          _GET_RESIZED_CHUNKS()->insert(pResizedChunk);
2032        }
2033    
2034        void File::UnlogResized(Chunk* pResizedChunk) {
2035            _GET_RESIZED_CHUNKS()->erase(pResizedChunk);
2036      }      }
2037    
2038      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
# Line 1538  namespace RIFF { Line 2046  namespace RIFF {
2046          long size = filestat.st_size;          long size = filestat.st_size;
2047          return size;          return size;
2048      }      }
2049        #elif defined(WIN32)
2050        unsigned long File::__GetFileSize(HANDLE hFile) {
2051            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
2052            if (dwSize == INVALID_FILE_SIZE)
2053                throw Exception("Windows FS error: could not determine file size");
2054            return dwSize;
2055        }
2056      #else // standard C functions      #else // standard C functions
2057      unsigned long File::__GetFileSize(FILE* hFile) {      unsigned long File::__GetFileSize(FILE* hFile) {
2058          long curpos = ftell(hFile);          long curpos = ftell(hFile);

Legend:
Removed from v.808  
changed lines
  Added in v.2682

  ViewVC Help
Powered by ViewVC