/[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 933 by schoenebeck, Fri Nov 24 12:50:05 2006 UTC revision 2675 by schoenebeck, Sun Sep 14 16:07:34 2014 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2006 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  // *************** Chunk **************  // *************** Chunk **************
58  // *  // *
59    
# Line 39  namespace RIFF { Line 64  namespace RIFF {
64          ulPos      = 0;          ulPos      = 0;
65          pParent    = NULL;          pParent    = NULL;
66          pChunkData = NULL;          pChunkData = NULL;
67            CurrentChunkSize = 0;
68            NewChunkSize = 0;
69          ulChunkDataSize = 0;          ulChunkDataSize = 0;
70          ChunkID    = CHUNK_ID_RIFF;          ChunkID    = CHUNK_ID_RIFF;
71          this->pFile = pFile;          this->pFile = pFile;
# Line 53  namespace RIFF { Line 80  namespace RIFF {
80          pParent       = Parent;          pParent       = Parent;
81          ulPos         = 0;          ulPos         = 0;
82          pChunkData    = NULL;          pChunkData    = NULL;
83            CurrentChunkSize = 0;
84            NewChunkSize = 0;
85          ulChunkDataSize = 0;          ulChunkDataSize = 0;
86          ReadHeader(StartPos);          ReadHeader(StartPos);
87      }      }
# Line 63  namespace RIFF { Line 92  namespace RIFF {
92          this->pParent    = pParent;          this->pParent    = pParent;
93          ulPos            = 0;          ulPos            = 0;
94          pChunkData       = NULL;          pChunkData       = NULL;
         ulChunkDataSize  = 0;  
95          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
96            ulChunkDataSize  = 0;
97          CurrentChunkSize = 0;          CurrentChunkSize = 0;
98          NewChunkSize     = uiBodySize;          NewChunkSize     = uiBodySize;
99      }      }
100    
101      Chunk::~Chunk() {      Chunk::~Chunk() {
102            if (pFile) pFile->UnlogResized(this);
103          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
104      }      }
105    
# Line 77  namespace RIFF { Line 107  namespace RIFF {
107          #if DEBUG          #if DEBUG
108          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << fPos << ") ";
109          #endif // DEBUG          #endif // DEBUG
110            ChunkID = 0;
111            NewChunkSize = CurrentChunkSize = 0;
112          #if POSIX          #if POSIX
113          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
114              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
115              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
116            #elif defined(WIN32)
117            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
118                DWORD dwBytesRead;
119                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
120                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
121          #else          #else
122          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
123              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
# Line 102  namespace RIFF { Line 139  namespace RIFF {
139              }              }
140              #if DEBUG              #if DEBUG
141              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
142              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << CurrentChunkSize << " ";
143              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
144              #endif // DEBUG              #endif // DEBUG
145              NewChunkSize = CurrentChunkSize;              NewChunkSize = CurrentChunkSize;
146          }          }
# Line 129  namespace RIFF { Line 166  namespace RIFF {
166              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
167              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &uiNewChunkSize, 4);
168          }          }
169            #elif defined(WIN32)
170            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
171                DWORD dwBytesWritten;
172                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
173                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
174            }
175          #else          #else
176          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
177              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
# Line 193  namespace RIFF { Line 236  namespace RIFF {
236         #if DEBUG         #if DEBUG
237         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;
238         #endif // DEBUG         #endif // DEBUG
239          return CurrentChunkSize - ulPos;          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;
240      }      }
241    
242      /**      /**
# Line 204  namespace RIFF { Line 247  namespace RIFF {
247       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
248       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
249       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
250       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
251       *    possible without SetPos()       *    possible without SetPos()
252       */       */
253      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
# Line 212  namespace RIFF { Line 255  namespace RIFF {
255        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
256        #endif // DEBUG        #endif // DEBUG
257          #if POSIX          #if POSIX
258          if (pFile->hFileRead == 0)    return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
259            #elif defined (WIN32)
260            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
261                return stream_closed;
262          #else          #else
263          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
264          #endif // POSIX          #endif // POSIX
# Line 239  namespace RIFF { Line 285  namespace RIFF {
285         #if DEBUG         #if DEBUG
286         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
287         #endif // DEBUG         #endif // DEBUG
288            //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
289          if (ulPos >= CurrentChunkSize) return 0;          if (ulPos >= CurrentChunkSize) return 0;
290          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
291          #if POSIX          #if POSIX
# Line 246  namespace RIFF { Line 293  namespace RIFF {
293          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
294          if (readWords < 1) return 0;          if (readWords < 1) return 0;
295          readWords /= WordSize;          readWords /= WordSize;
296            #elif defined(WIN32)
297            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
298            DWORD readWords;
299            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
300            if (readWords < 1) return 0;
301            readWords /= WordSize;
302          #else // standard C functions          #else // standard C functions
303          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
304          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
# Line 315  namespace RIFF { Line 368  namespace RIFF {
368          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
369          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");
370          writtenWords /= WordSize;          writtenWords /= WordSize;
371            #elif defined(WIN32)
372            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
373                throw Exception("Could not seek to position " + ToString(ulPos) +
374                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
375            }
376            DWORD writtenWords;
377            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
378            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
379            writtenWords /= WordSize;
380          #else // standard C functions          #else // standard C functions
381          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
382              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
# Line 537  namespace RIFF { Line 599  namespace RIFF {
599      }      }
600    
601      /**      /**
602         * Reads a null-padded string of size characters and copies it
603         * into the string \a s. The position within the chunk will
604         * automatically be incremented.
605         *
606         * @param s                 destination string
607         * @param size              number of characters to read
608         * @throws RIFF::Exception  if an error occured or less than
609         *                          \a size characters could be read!
610         */
611        void Chunk::ReadString(String& s, int size) {
612            char* buf = new char[size];
613            ReadSceptical(buf, 1, size);
614            s.assign(buf, std::find(buf, buf + size, '\0'));
615            delete[] buf;
616        }
617    
618        /**
619       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
620       * 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
621       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 676  namespace RIFF { Line 755  namespace RIFF {
755       * @see ReleaseChunkData()       * @see ReleaseChunkData()
756       */       */
757      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
758          if (!pChunkData && pFile->Filename != "") {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
759              #if POSIX              #if POSIX
760              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
761                #elif defined(WIN32)
762                if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;
763              #else              #else
764              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
765              #endif // POSIX              #endif // POSIX
# Line 688  namespace RIFF { Line 769  namespace RIFF {
769              memset(pChunkData, 0, ulBufferSize);              memset(pChunkData, 0, ulBufferSize);
770              #if POSIX              #if POSIX
771              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
772                #elif defined(WIN32)
773                DWORD readWords;
774                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
775              #else              #else
776              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
777              #endif // POSIX              #endif // POSIX
# Line 740  namespace RIFF { Line 824  namespace RIFF {
824       * @see File::Save()       * @see File::Save()
825       */       */
826      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
827          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0)
828                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
829          if (NewChunkSize == iNewSize) return;          if (NewChunkSize == iNewSize) return;
830          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
831          pFile->LogAsResized(this);          pFile->LogAsResized(this);
# Line 775  namespace RIFF { Line 860  namespace RIFF {
860              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
861                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
862              }              }
863                #elif defined(WIN32)
864                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
865                DWORD dwBytesWritten;
866                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
867                if (dwBytesWritten != NewChunkSize) {
868                    throw Exception("Writing Chunk data (from RAM) failed");
869                }
870              #else              #else
871              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
872              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 785  namespace RIFF { Line 877  namespace RIFF {
877              // 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
878              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
879              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
880                #if defined(WIN32)
881                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
882                #else
883              int iBytesMoved = 1;              int iBytesMoved = 1;
884              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              #endif
885                for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
886                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
887                  #if POSIX                  #if POSIX
888                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
889                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
890                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
891                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
892                    #elif defined(WIN32)
893                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
894                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
895                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
896                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
897                  #else                  #else
898                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
899                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 818  namespace RIFF { Line 919  namespace RIFF {
919              #if POSIX              #if POSIX
920              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
921              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
922                #elif defined(WIN32)
923                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
924                DWORD dwBytesWritten;
925                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
926              #else              #else
927              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
928              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
# Line 867  namespace RIFF { Line 972  namespace RIFF {
972        #if DEBUG        #if DEBUG
973        std::cout << "List::~List()" << std::endl;        std::cout << "List::~List()" << std::endl;
974        #endif // DEBUG        #endif // DEBUG
975            DeleteChunkList();
976        }
977    
978        void List::DeleteChunkList() {
979          if (pSubChunks) {          if (pSubChunks) {
980              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
981              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 875  namespace RIFF { Line 984  namespace RIFF {
984                  iter++;                  iter++;
985              }              }
986              delete pSubChunks;              delete pSubChunks;
987                pSubChunks = NULL;
988            }
989            if (pSubChunksMap) {
990                delete pSubChunksMap;
991                pSubChunksMap = NULL;
992          }          }
         if (pSubChunksMap) delete pSubChunksMap;  
993      }      }
994    
995      /**      /**
# Line 1077  namespace RIFF { Line 1190  namespace RIFF {
1190          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1191          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1192          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(uiBodySize);
1193            NewChunkSize += CHUNK_HEADER_SIZE;
1194            pFile->LogAsResized(this);
1195          return pNewChunk;          return pNewChunk;
1196      }      }
1197    
1198        /** @brief Moves a sub chunk witin this list.
1199         *
1200         * Moves a sub chunk from one position in this list to another
1201         * position in the same list. The pSrc chunk is placed before the
1202         * pDst chunk.
1203         *
1204         * @param pSrc - sub chunk to be moved
1205         * @param pDst - the position to move to. pSrc will be placed
1206         *               before pDst. If pDst is 0, pSrc will be placed
1207         *               last in list.
1208         */
1209        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1210            if (!pSubChunks) LoadSubChunks();
1211            pSubChunks->remove(pSrc);
1212            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1213            pSubChunks->insert(iter, pSrc);
1214        }
1215    
1216        /** @brief Moves a sub chunk from this list to another list.
1217         *
1218         * Moves a sub chunk from this list list to the end of another
1219         * list.
1220         *
1221         * @param pSrc - sub chunk to be moved
1222         * @param pDst - destination list where the chunk shall be moved to
1223         */
1224        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1225            if (pNewParent == this || !pNewParent) return;
1226            if (!pSubChunks) LoadSubChunks();
1227            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1228            pSubChunks->remove(pSrc);
1229            pNewParent->pSubChunks->push_back(pSrc);
1230            // update chunk id map of this List
1231            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1232                pSubChunksMap->erase(pSrc->GetChunkID());
1233                // try to find another chunk of the same chunk ID
1234                ChunkList::iterator iter = pSubChunks->begin();
1235                ChunkList::iterator end  = pSubChunks->end();
1236                for (; iter != end; ++iter) {
1237                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1238                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1239                        break; // we're done, stop search
1240                    }
1241                }
1242            }
1243            // update chunk id map of other list
1244            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1245                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1246        }
1247    
1248      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1249       *       *
1250       * 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 1259  namespace RIFF {
1259          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1260          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1261          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1262            NewChunkSize += LIST_HEADER_SIZE;
1263            pFile->LogAsResized(this);
1264          return pNewListChunk;          return pNewListChunk;
1265      }      }
1266    
# Line 1101  namespace RIFF { Line 1268  namespace RIFF {
1268       *       *
1269       * 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
1270       * 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
1271       * 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,
1272       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1273         * should call File::Save() to make this change persistent at any time.
1274       *       *
1275       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1276       */       */
# Line 1129  namespace RIFF { Line 1297  namespace RIFF {
1297        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1298        #endif // DEBUG        #endif // DEBUG
1299          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1300            if (CurrentChunkSize < 4) return;
1301          NewChunkSize = CurrentChunkSize -= 4;          NewChunkSize = CurrentChunkSize -= 4;
1302          #if POSIX          #if POSIX
1303          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1304          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1305            #elif defined(WIN32)
1306            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1307            DWORD dwBytesRead;
1308            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1309          #else          #else
1310          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1311          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1153  namespace RIFF { Line 1326  namespace RIFF {
1326          #if POSIX          #if POSIX
1327          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1328          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1329            #elif defined(WIN32)
1330            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1331            DWORD dwBytesWritten;
1332            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1333          #else          #else
1334          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1335          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
# Line 1166  namespace RIFF { Line 1343  namespace RIFF {
1343          if (!pSubChunks) {          if (!pSubChunks) {
1344              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1345              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1346                #if defined(WIN32)
1347                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1348                #else
1349              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1350                #endif
1351              unsigned long uiOriginalPos = GetPos();              unsigned long uiOriginalPos = GetPos();
1352              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1353              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
# Line 1256  namespace RIFF { Line 1437  namespace RIFF {
1437  // *************** File ***************  // *************** File ***************
1438  // *  // *
1439    
1440    //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
1441    #define _GET_RESIZED_CHUNKS() \
1442            (reinterpret_cast<std::set<Chunk*>*>(ResizedChunks.front()))
1443    
1444      /** @brief Create new RIFF file.      /** @brief Create new RIFF file.
1445       *       *
1446       * 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
1447       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1448       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1449       *       *
1450         * Note: by default, the RIFF file will be saved in native endian
1451         * format; that is, as a RIFF file on little-endian machines and
1452         * as a RIFX file on big-endian. To change this behaviour, call
1453         * SetByteOrder() before calling Save().
1454         *
1455       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1456       * @see AddSubChunk(), AddSubList()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1457       */       */
1458      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType)
1459            : List(this), bIsNewFile(true), Layout(layout_standard)
1460        {
1461            //HACK: see _GET_RESIZED_CHUNKS() comment
1462            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1463            #if defined(WIN32)
1464            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1465            #else
1466          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1467            #endif
1468          Mode = stream_mode_closed;          Mode = stream_mode_closed;
1469          bEndianNative = true;          bEndianNative = true;
1470          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
# Line 1281  namespace RIFF { Line 1479  namespace RIFF {
1479       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occured while trying to load the
1480       *                         given RIFF file       *                         given RIFF file
1481       */       */
1482      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path)
1483        #if DEBUG          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard)
1484        std::cout << "File::File("<<path<<")" << std::endl;      {
1485        #endif // DEBUG         #if DEBUG
1486           std::cout << "File::File("<<path<<")" << std::endl;
1487           #endif // DEBUG
1488          bEndianNative = true;          bEndianNative = true;
1489            try {
1490                __openExistingFile(path);
1491                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1492                    throw RIFF::Exception("Not a RIFF file");
1493                }
1494            }
1495            catch (...) {
1496                Cleanup();
1497                throw;
1498            }
1499        }
1500    
1501        /** @brief Load existing RIFF-like file.
1502         *
1503         * Loads an existing file, which is not a "real" RIFF file, but similar to
1504         * an ordinary RIFF file.
1505         *
1506         * A "real" RIFF file contains at top level a List chunk either with chunk
1507         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1508         * case, and if it finds the toplevel List chunk to have another chunk ID
1509         * than one of those two expected ones, it would throw an Exception and
1510         * would refuse to load the file accordingly.
1511         *
1512         * Since there are however a lot of file formats which use the same simple
1513         * principles of the RIFF format, with another toplevel List chunk ID
1514         * though, you can use this alternative constructor here to be able to load
1515         * and handle those files in the same way as you would do with "real" RIFF
1516         * files.
1517         *
1518         * @param path - path and file name of the RIFF-alike file to be opened
1519         * @param FileType - expected toplevel List chunk ID (this is the very
1520         *                   first chunk found in the file)
1521         * @param Endian - whether the file uses little endian or big endian layout
1522         * @param layout - general file structure type
1523         * @throws RIFF::Exception if error occured while trying to load the
1524         *                         given RIFF-alike file
1525         */
1526        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout)
1527            : List(this), Filename(path), bIsNewFile(false), Layout(layout)
1528        {
1529            SetByteOrder(Endian);
1530            try {
1531                __openExistingFile(path, &FileType);
1532            }
1533            catch (...) {
1534                Cleanup();
1535                throw;
1536            }
1537        }
1538    
1539        /**
1540         * Opens an already existing RIFF file or RIFF-alike file. This method
1541         * shall only be called once (in a File class constructor).
1542         *
1543         * @param path - path and file name of the RIFF file or RIFF-alike file to
1544         *               be opened
1545         * @param FileType - (optional) expected chunk ID of first chunk in file
1546         * @throws RIFF::Exception if error occured while trying to load the
1547         *                         given RIFF file or RIFF-alike file
1548         */
1549        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1550            //HACK: see _GET_RESIZED_CHUNKS() comment
1551            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1552          #if POSIX          #if POSIX
1553          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1554          if (hFileRead <= 0) {          if (hFileRead == -1) {
1555              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1556                String sError = strerror(errno);
1557                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1558            }
1559            #elif defined(WIN32)
1560            hFileRead = hFileWrite = CreateFile(
1561                                         path.c_str(), GENERIC_READ,
1562                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1563                                         NULL, OPEN_EXISTING,
1564                                         FILE_ATTRIBUTE_NORMAL |
1565                                         FILE_FLAG_RANDOM_ACCESS, NULL
1566                                     );
1567            if (hFileRead == INVALID_HANDLE_VALUE) {
1568                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1569              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1570          }          }
1571          #else          #else
1572          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1573          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1574          #endif // POSIX          #endif // POSIX
1575          Mode = stream_mode_read;          Mode = stream_mode_read;
1576          ulStartPos = RIFF_HEADER_SIZE;          switch (Layout) {
1577          ReadHeader(0);              case layout_standard: // this is a normal RIFF file
1578          if (ChunkID != CHUNK_ID_RIFF) {                  ulStartPos = RIFF_HEADER_SIZE;
1579              throw RIFF::Exception("Not a RIFF file");                  ReadHeader(0);
1580                    if (FileType && ChunkID != *FileType)
1581                        throw RIFF::Exception("Invalid file container ID");
1582                    break;
1583                case layout_flat: // non-standard RIFF-alike file
1584                    ulStartPos = 0;
1585                    NewChunkSize = CurrentChunkSize = GetFileSize();
1586                    if (FileType) {
1587                        uint32_t ckid;
1588                        if (Read(&ckid, 4, 1) != 4) {
1589                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1590                        } else if (ckid != *FileType) {
1591                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1592                            throw RIFF::Exception("Invalid file header ID" + s);
1593                        }
1594                        SetPos(0); // reset to first byte of file
1595                    }
1596                    LoadSubChunks();
1597                    break;
1598          }          }
1599      }      }
1600    
1601      String File::GetFileName() {      String File::GetFileName() {
1602          return Filename;          return Filename;
1603      }      }
1604        
1605        void File::SetFileName(const String& path) {
1606            Filename = path;
1607        }
1608    
1609      stream_mode_t File::GetMode() {      stream_mode_t File::GetMode() {
1610          return Mode;          return Mode;
1611      }      }
1612    
1613        layout_t File::GetLayout() const {
1614            return Layout;
1615        }
1616    
1617      /** @brief Change file access mode.      /** @brief Change file access mode.
1618       *       *
1619       * 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 1329  namespace RIFF { Line 1631  namespace RIFF {
1631                      #if POSIX                      #if POSIX
1632                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1633                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1634                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1635                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1636                            String sError = strerror(errno);
1637                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1638                        }
1639                        #elif defined(WIN32)
1640                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1641                        hFileRead = hFileWrite = CreateFile(
1642                                                     Filename.c_str(), GENERIC_READ,
1643                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1644                                                     NULL, OPEN_EXISTING,
1645                                                     FILE_ATTRIBUTE_NORMAL |
1646                                                     FILE_FLAG_RANDOM_ACCESS,
1647                                                     NULL
1648                                                 );
1649                        if (hFileRead == INVALID_HANDLE_VALUE) {
1650                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1651                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1652                      }                      }
1653                      #else                      #else
1654                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1655                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1656                      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");
1657                      #endif                      #endif
1658                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
# Line 1344  namespace RIFF { Line 1661  namespace RIFF {
1661                      #if POSIX                      #if POSIX
1662                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1663                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1664                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1665                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1666                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          String sError = strerror(errno);
1667                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1668                        }
1669                        #elif defined(WIN32)
1670                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1671                        hFileRead = hFileWrite = CreateFile(
1672                                                     Filename.c_str(),
1673                                                     GENERIC_READ | GENERIC_WRITE,
1674                                                     FILE_SHARE_READ,
1675                                                     NULL, OPEN_ALWAYS,
1676                                                     FILE_ATTRIBUTE_NORMAL |
1677                                                     FILE_FLAG_RANDOM_ACCESS,
1678                                                     NULL
1679                                                 );
1680                        if (hFileRead == INVALID_HANDLE_VALUE) {
1681                            hFileRead = hFileWrite = CreateFile(
1682                                                         Filename.c_str(), GENERIC_READ,
1683                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1684                                                         NULL, OPEN_EXISTING,
1685                                                         FILE_ATTRIBUTE_NORMAL |
1686                                                         FILE_FLAG_RANDOM_ACCESS,
1687                                                         NULL
1688                                                     );
1689                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1690                      }                      }
1691                      #else                      #else
1692                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1693                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1694                      if (!hFileRead) {                      if (!hFileRead) {
1695                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1696                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1697                      }                      }
1698                      #endif                      #endif
# Line 1362  namespace RIFF { Line 1702  namespace RIFF {
1702                      #if POSIX                      #if POSIX
1703                      if (hFileRead)  close(hFileRead);                      if (hFileRead)  close(hFileRead);
1704                      if (hFileWrite) close(hFileWrite);                      if (hFileWrite) close(hFileWrite);
1705                        #elif defined(WIN32)
1706                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1707                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1708                      #else                      #else
1709                      if (hFileRead)  fclose(hFileRead);                      if (hFileRead)  fclose(hFileRead);
1710                      if (hFileWrite) fclose(hFileWrite);                      if (hFileWrite) fclose(hFileWrite);
# Line 1377  namespace RIFF { Line 1720  namespace RIFF {
1720          return false;          return false;
1721      }      }
1722    
1723        /** @brief Set the byte order to be used when saving.
1724         *
1725         * Set the byte order to be used in the file. A value of
1726         * endian_little will create a RIFF file, endian_big a RIFX file
1727         * and endian_native will create a RIFF file on little-endian
1728         * machines and RIFX on big-endian machines.
1729         *
1730         * @param Endian - endianess to use when file is saved.
1731         */
1732        void File::SetByteOrder(endian_t Endian) {
1733            #if WORDS_BIGENDIAN
1734            bEndianNative = Endian != endian_little;
1735            #else
1736            bEndianNative = Endian != endian_big;
1737            #endif
1738        }
1739    
1740      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1741       *       *
1742       * 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 1388  namespace RIFF { Line 1748  namespace RIFF {
1748       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1749       */       */
1750      void File::Save() {      void File::Save() {
1751            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1752            if (Layout == layout_flat)
1753                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1754    
1755          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1756          LoadSubChunksRecursively();          LoadSubChunksRecursively();
1757    
# Line 1403  namespace RIFF { Line 1767  namespace RIFF {
1767    
1768          // 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)
1769          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1770          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          std::set<Chunk*>* resizedChunks = _GET_RESIZED_CHUNKS();
1771              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) {
1772              if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {              if ((*iter)->GetNewSize() == 0) {
1773                  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;  
1774              }              }
1775                unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1776                unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1777                if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1778          }          }
1779    
1780          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1421  namespace RIFF { Line 1787  namespace RIFF {
1787              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1788              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1789              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1790                #if defined(WIN32)
1791                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1792                #else
1793              int iBytesMoved = 1;              int iBytesMoved = 1;
1794              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              #endif
1795                  const unsigned long ulToMove = ulFileSize - ulPos;              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1796                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1797                    ulPos -= iBytesMoved;
1798                  #if POSIX                  #if POSIX
1799                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ulPos, SEEK_SET);
1800                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1801                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1802                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1803                    #elif defined(WIN32)
1804                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1805                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1806                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1807                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1808                  #else                  #else
1809                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1810                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
# Line 1449  namespace RIFF { Line 1824  namespace RIFF {
1824          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1825    
1826          // forget all resized chunks          // forget all resized chunks
1827          ResizedChunks.clear();          resizedChunks->clear();
1828      }      }
1829    
1830      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1468  namespace RIFF { Line 1843  namespace RIFF {
1843      void File::Save(const String& path) {      void File::Save(const String& path) {
1844          //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
1845    
1846            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1847            if (Layout == layout_flat)
1848                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1849    
1850          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1851          LoadSubChunksRecursively();          LoadSubChunksRecursively();
1852    
1853          if (Filename.length() > 0) SetMode(stream_mode_read);          if (!bIsNewFile) SetMode(stream_mode_read);
1854          // 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
1855          #if POSIX          #if POSIX
1856          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);
1857          if (hFileWrite < 0) {          if (hFileWrite == -1) {
1858                hFileWrite = hFileRead;
1859                String sError = strerror(errno);
1860                throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
1861            }
1862            #elif defined(WIN32)
1863            hFileWrite = CreateFile(
1864                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1865                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1866                             FILE_FLAG_RANDOM_ACCESS, NULL
1867                         );
1868            if (hFileWrite == INVALID_HANDLE_VALUE) {
1869              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1870              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1871          }          }
# Line 1496  namespace RIFF { Line 1886  namespace RIFF {
1886          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1887    
1888          // forget all resized chunks          // forget all resized chunks
1889          ResizedChunks.clear();          _GET_RESIZED_CHUNKS()->clear();
1890    
1891          if (Filename.length() > 0) {          #if POSIX
1892              #if POSIX          if (hFileWrite) close(hFileWrite);
1893              close(hFileWrite);          #elif defined(WIN32)
1894              #else          if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1895              fclose(hFileWrite);          #else
1896              #endif          if (hFileWrite) fclose(hFileWrite);
1897              hFileWrite = hFileRead;          #endif
1898          }          hFileWrite = hFileRead;
1899    
1900          // associate new file with this File object from now on          // associate new file with this File object from now on
1901          Filename = path;          Filename = path;
1902            bIsNewFile = false;
1903          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1904          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.
1905      }      }
# Line 1517  namespace RIFF { Line 1908  namespace RIFF {
1908          #if POSIX          #if POSIX
1909          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1910              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1911            #elif defined(WIN32)
1912            if (
1913                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1914                !SetEndOfFile(hFileWrite)
1915            ) throw Exception("Could not resize file \"" + Filename + "\"");
1916          #else          #else
1917          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1918          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1919          #endif          #endif
1920      }      }
# Line 1527  namespace RIFF { Line 1923  namespace RIFF {
1923         #if DEBUG         #if DEBUG
1924         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
1925         #endif // DEBUG         #endif // DEBUG
1926            Cleanup();
1927        }
1928        
1929        /**
1930         * Returns @c true if this file has been created new from scratch and
1931         * has not been stored to disk yet.
1932         */
1933        bool File::IsNew() const {
1934            return bIsNewFile;
1935        }
1936    
1937        void File::Cleanup() {
1938          #if POSIX          #if POSIX
1939          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1940            #elif defined(WIN32)
1941            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1942          #else          #else
1943          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1944          #endif // POSIX          #endif // POSIX
1945            DeleteChunkList();
1946            pFile = NULL;
1947            //HACK: see _GET_RESIZED_CHUNKS() comment
1948            delete _GET_RESIZED_CHUNKS();
1949      }      }
1950    
1951      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {
1952          ResizedChunks.push_back(pResizedChunk);          _GET_RESIZED_CHUNKS()->insert(pResizedChunk);
1953        }
1954    
1955        void File::UnlogResized(Chunk* pResizedChunk) {
1956            _GET_RESIZED_CHUNKS()->erase(pResizedChunk);
1957      }      }
1958    
1959      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
# Line 1549  namespace RIFF { Line 1967  namespace RIFF {
1967          long size = filestat.st_size;          long size = filestat.st_size;
1968          return size;          return size;
1969      }      }
1970        #elif defined(WIN32)
1971        unsigned long File::__GetFileSize(HANDLE hFile) {
1972            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1973            if (dwSize == INVALID_FILE_SIZE)
1974                throw Exception("Windows FS error: could not determine file size");
1975            return dwSize;
1976        }
1977      #else // standard C functions      #else // standard C functions
1978      unsigned long File::__GetFileSize(FILE* hFile) {      unsigned long File::__GetFileSize(FILE* hFile) {
1979          long curpos = ftell(hFile);          long curpos = ftell(hFile);

Legend:
Removed from v.933  
changed lines
  Added in v.2675

  ViewVC Help
Powered by ViewVC