/[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 2 by schoenebeck, Sat Oct 25 20:15:04 2003 UTC revision 1863 by schoenebeck, Fri Mar 13 10:57:24 2009 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 by Christian Schoenebeck                           *   *   Copyright (C) 2003-2009 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  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 20  Line 20 
20   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston,                 *   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston,                 *
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23  #if 1  
24    #include <algorithm>
25    #include <string.h>
26    
27  #include "RIFF.h"  #include "RIFF.h"
28    
29    #include "helper.h"
30    
31  namespace RIFF {  namespace RIFF {
32    
33    // *************** Internal functions **************
34    // *
35    
36        /// Returns a human readable path of the given chunk.
37        static String __resolveChunkPath(Chunk* pCk) {
38            String sPath;
39            for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
40                if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
41                    List* pList = (List*) pChunk;
42                    sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
43                } else {
44                    sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
45                }
46            }
47            return sPath;
48        }
49    
50    
51    
52  // *************** Chunk **************  // *************** Chunk **************
53  // *  // *
54    
55      Chunk::Chunk() {      Chunk::Chunk(File* pFile) {
56          #if DEBUG          #if DEBUG
57          std::cout << "Chunk::Chunk()" << std::endl;          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
58          #endif // DEBUG          #endif // DEBUG
59          ulPos      = 0;          ulPos      = 0;
60          pParent    = NULL;          pParent    = NULL;
61          pChunkData = NULL;          pChunkData = NULL;
62            CurrentChunkSize = 0;
63            NewChunkSize = 0;
64            ulChunkDataSize = 0;
65            ChunkID    = CHUNK_ID_RIFF;
66            this->pFile = pFile;
67      }      }
68    
69      #if POSIX      Chunk::Chunk(File* pFile, unsigned long StartPos, List* Parent) {
     Chunk::Chunk(int hFile, unsigned long StartPos, bool EndianNative, List* Parent) {  
     #else  
     Chunk::Chunk(FILE* hFile, unsigned long StartPos, bool EndianNative, List* Parent) {  
     #endif // POSIX  
70          #if DEBUG          #if DEBUG
71          std::cout << "Chunk::Chunk(FILE,ulong,bool,List*),StartPos=" << StartPos << std::endl;          std::cout << "Chunk::Chunk(File*,ulong,bool,List*),StartPos=" << StartPos << std::endl;
72          #endif // DEBUG          #endif // DEBUG
73          Chunk::hFile  = hFile;          this->pFile   = pFile;
74          ulStartPos    = StartPos + CHUNK_HEADER_SIZE;          ulStartPos    = StartPos + CHUNK_HEADER_SIZE;
         bEndianNative = EndianNative;  
75          pParent       = Parent;          pParent       = Parent;
76          ulPos         = 0;          ulPos         = 0;
77          pChunkData    = NULL;          pChunkData    = NULL;
78            CurrentChunkSize = 0;
79            NewChunkSize = 0;
80            ulChunkDataSize = 0;
81          ReadHeader(StartPos);          ReadHeader(StartPos);
82      }      }
83    
84        Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, uint uiBodySize) {
85            this->pFile      = pFile;
86            ulStartPos       = 0; // arbitrary usually, since it will be updated when we write the chunk
87            this->pParent    = pParent;
88            ulPos            = 0;
89            pChunkData       = NULL;
90            ChunkID          = uiChunkID;
91            ulChunkDataSize  = 0;
92            CurrentChunkSize = 0;
93            NewChunkSize     = uiBodySize;
94        }
95    
96      Chunk::~Chunk() {      Chunk::~Chunk() {
97            pFile->UnlogResized(this);
98          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
99      }      }
100    
# Line 62  namespace RIFF { Line 102  namespace RIFF {
102          #if DEBUG          #if DEBUG
103          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << fPos << ") ";
104          #endif // DEBUG          #endif // DEBUG
105            ChunkID = 0;
106            NewChunkSize = CurrentChunkSize = 0;
107          #if POSIX          #if POSIX
108          if (lseek(hFile, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
109              read(hFile, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
110              read(hFile, &ChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
111          #else          #elif defined(WIN32)
112          if (!fseek(hFile, fPos, SEEK_SET)) {          if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
113              fread(&ChunkID, 4, 1, hFile);              DWORD dwBytesRead;
114              fread(&ChunkSize, 4, 1, hFile);              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
115                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
116            #else
117            if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
118                fread(&ChunkID, 4, 1, pFile->hFileRead);
119                fread(&CurrentChunkSize, 4, 1, pFile->hFileRead);
120          #endif // POSIX          #endif // POSIX
         #if DEBUG  
         std::cout << "ckID=" << convertToString(ChunkID) << " ";  
         std::cout << "ckSize=" << ChunkSize << std::endl;  
         #endif // DEBUG  
121              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
122              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
123                  bEndianNative = false;                  pFile->bEndianNative = false;
124              }              }
125              #else // little endian              #else // little endian
126              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
127                  bEndianNative = false;                  pFile->bEndianNative = false;
128                  ChunkID = CHUNK_ID_RIFF;                  ChunkID = CHUNK_ID_RIFF;
129              }              }
130              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
131              if (!bEndianNative) {              if (!pFile->bEndianNative) {
132                  swapBytes_32(&ChunkID);                  //swapBytes_32(&ChunkID);
133                  swapBytes_32(&ChunkSize);                  swapBytes_32(&CurrentChunkSize);
134              }              }
135                #if DEBUG
136                std::cout << "ckID=" << convertToString(ChunkID) << " ";
137                std::cout << "ckSize=" << CurrentChunkSize << " ";
138                std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
139                #endif // DEBUG
140                NewChunkSize = CurrentChunkSize;
141            }
142        }
143    
144        void Chunk::WriteHeader(unsigned long fPos) {
145            uint32_t uiNewChunkID = ChunkID;
146            if (ChunkID == CHUNK_ID_RIFF) {
147                #if WORDS_BIGENDIAN
148                if (pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
149                #else // little endian
150                if (!pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
151                #endif // WORDS_BIGENDIAN
152            }
153    
154            uint32_t uiNewChunkSize = NewChunkSize;
155            if (!pFile->bEndianNative) {
156                swapBytes_32(&uiNewChunkSize);
157          }          }
158    
159            #if POSIX
160            if (lseek(pFile->hFileWrite, fPos, SEEK_SET) != -1) {
161                write(pFile->hFileWrite, &uiNewChunkID, 4);
162                write(pFile->hFileWrite, &uiNewChunkSize, 4);
163            }
164            #elif defined(WIN32)
165            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
166                DWORD dwBytesWritten;
167                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
168                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
169            }
170            #else
171            if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
172                fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
173                fwrite(&uiNewChunkSize, 4, 1, pFile->hFileWrite);
174            }
175            #endif // POSIX
176      }      }
177    
178        /**
179         *  Returns the String representation of the chunk's ID (e.g. "RIFF",
180         *  "LIST").
181         */
182      String Chunk::GetChunkIDString() {      String Chunk::GetChunkIDString() {
183          return convertToString(ChunkID);          return convertToString(ChunkID);
184      }      }
185    
186        /**
187         *  Sets the position within the chunk body, thus within the data portion
188         *  of the chunk (in bytes).
189         *
190         *  <b>Caution:</b> the position will be reset to zero whenever
191         *  File::Save() was called.
192         *
193         *  @param Where  - position offset (in bytes)
194         *  @param Whence - optional: defines to what <i>\a Where</i> relates to,
195         *                  if omitted \a Where relates to beginning of the chunk
196         *                  data
197         */
198      unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {      unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {
199       #if DEBUG       #if DEBUG
200       std::cout << "Chunk::SetPos(ulong)" << std::endl;       std::cout << "Chunk::SetPos(ulong)" << std::endl;
# Line 105  namespace RIFF { Line 204  namespace RIFF {
204                  ulPos += Where;                  ulPos += Where;
205                  break;                  break;
206              case stream_end:              case stream_end:
207                  ulPos = ChunkSize - 1 - Where;                  ulPos = CurrentChunkSize - 1 - Where;
208                  break;                  break;
209              case stream_backward:              case stream_backward:
210                  ulPos -= Where;                  ulPos -= Where;
# Line 114  namespace RIFF { Line 213  namespace RIFF {
213                  ulPos = Where;                  ulPos = Where;
214                  break;                  break;
215          }          }
216          if (ulPos > ChunkSize) ulPos = ChunkSize;          if (ulPos > CurrentChunkSize) ulPos = CurrentChunkSize;
217          return ulPos;          return ulPos;
218      }      }
219    
220        /**
221         *  Returns the number of bytes left to read in the chunk body.
222         *  When reading data from the chunk using the Read*() Methods, the
223         *  position within the chunk data (that is the chunk body) will be
224         *  incremented by the number of read bytes and RemainingBytes() returns
225         *  how much data is left to read from the current position to the end
226         *  of the chunk data.
227         *
228         *  @returns  number of bytes left to read
229         */
230      unsigned long Chunk::RemainingBytes() {      unsigned long Chunk::RemainingBytes() {
231         #if DEBUG         #if DEBUG
232         std::cout << "Chunk::Remainingbytes()=" << ChunkSize - ulPos << std::endl;         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;
233         #endif // DEBUG         #endif // DEBUG
234          return ChunkSize - ulPos;          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;
235      }      }
236    
237        /**
238         *  Returns the current state of the chunk object.
239         *  Following values are possible:
240         *  - RIFF::stream_ready :
241         *    chunk data can be read (this is the usual case)
242         *  - RIFF::stream_closed :
243         *    the data stream was closed somehow, no more reading possible
244         *  - RIFF::stream_end_reached :
245         *    already reached the end of the chunk data, no more reading
246         *    possible without SetPos()
247         */
248      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
249        #if DEBUG        #if DEBUG
250        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
251        #endif // DEBUG        #endif // DEBUG
252          #if POSIX          #if POSIX
253          if (hFile == 0)        return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
254            #elif defined (WIN32)
255            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
256                return stream_closed;
257          #else          #else
258          if (hFile == NULL)     return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
259          #endif // POSIX          #endif // POSIX
260          if (ulPos < ChunkSize) return stream_ready;          if (ulPos < CurrentChunkSize) return stream_ready;
261          else                   return stream_end_reached;          else                          return stream_end_reached;
262      }      }
263    
264      /**      /**
# Line 157  namespace RIFF { Line 280  namespace RIFF {
280         #if DEBUG         #if DEBUG
281         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
282         #endif // DEBUG         #endif // DEBUG
283          if (ChunkSize - ulPos <= 0) return 0;          if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
284          if (ulPos + WordCount * WordSize >= ChunkSize) WordCount = (ChunkSize - ulPos) / WordSize;          if (ulPos >= CurrentChunkSize) return 0;
285            if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
286          #if POSIX          #if POSIX
287          if (lseek(hFile, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;
288          unsigned long readWords = read(hFile, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
289            if (readWords < 1) return 0;
290            readWords /= WordSize;
291            #elif defined(WIN32)
292            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
293            DWORD readWords;
294            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
295          if (readWords < 1) return 0;          if (readWords < 1) return 0;
296          readWords /= WordSize;          readWords /= WordSize;
297          #else // standard C functions          #else // standard C functions
298          if (fseek(hFile, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
299          unsigned long readWords = fread(pData, WordSize, WordCount, hFile);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
300          #endif // POSIX          #endif // POSIX
301          if (!bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
302              switch (WordSize) {              switch (WordSize) {
303                  case 2:                  case 2:
304                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (unsigned long iWord = 0; iWord < readWords; iWord++)
# Line 188  namespace RIFF { Line 318  namespace RIFF {
318          return readWords;          return readWords;
319      }      }
320    
321        /**
322         *  Writes \a WordCount number of data words with given \a WordSize from
323         *  the buffer pointed by \a pData. Be sure to provide the correct
324         *  \a WordSize, as this will be important and taken into account for
325         *  eventual endian correction (swapping of bytes due to different
326         *  native byte order of a system). The position within the chunk will
327         *  automatically be incremented.
328         *
329         *  @param pData      source buffer (containing the data)
330         *  @param WordCount  number of data words to write
331         *  @param WordSize   size of each data word to write
332         *  @returns          number of successfully written data words
333         *  @throws RIFF::Exception  if write operation would exceed current
334         *                           chunk size or any IO error occured
335         *  @see Resize()
336         */
337        unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {
338            if (pFile->Mode != stream_mode_read_write)
339                throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
340            if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)
341                throw Exception("End of chunk reached while trying to write data");
342            if (!pFile->bEndianNative && WordSize != 1) {
343                switch (WordSize) {
344                    case 2:
345                        for (unsigned long iWord = 0; iWord < WordCount; iWord++)
346                            swapBytes_16((uint16_t*) pData + iWord);
347                        break;
348                    case 4:
349                        for (unsigned long iWord = 0; iWord < WordCount; iWord++)
350                            swapBytes_32((uint32_t*) pData + iWord);
351                        break;
352                    default:
353                        for (unsigned long iWord = 0; iWord < WordCount; iWord++)
354                            swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
355                        break;
356                }
357            }
358            #if POSIX
359            if (lseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET) < 0) {
360                throw Exception("Could not seek to position " + ToString(ulPos) +
361                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
362            }
363            unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
364            if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
365            writtenWords /= WordSize;
366            #elif defined(WIN32)
367            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
368                throw Exception("Could not seek to position " + ToString(ulPos) +
369                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
370            }
371            DWORD writtenWords;
372            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
373            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
374            writtenWords /= WordSize;
375            #else // standard C functions
376            if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
377                throw Exception("Could not seek to position " + ToString(ulPos) +
378                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
379            }
380            unsigned long writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
381            #endif // POSIX
382            SetPos(writtenWords * WordSize, stream_curpos);
383            return writtenWords;
384        }
385    
386      /** Just an internal wrapper for the main <i>Read()</i> method with additional Exception throwing on errors. */      /** Just an internal wrapper for the main <i>Read()</i> method with additional Exception throwing on errors. */
387      unsigned long Chunk::ReadSceptical(void* pData, unsigned long WordCount, unsigned long WordSize) {      unsigned long Chunk::ReadSceptical(void* pData, unsigned long WordCount, unsigned long WordSize) {
388          unsigned long readWords = Read(pData, WordCount, WordSize);          unsigned long readWords = Read(pData, WordCount, WordSize);
# Line 214  namespace RIFF { Line 409  namespace RIFF {
409      }      }
410    
411      /**      /**
412         * Writes \a WordCount number of 8 Bit signed integer words from the
413         * buffer pointed by \a pData to the chunk's body, directly to the
414         * actual "physical" file. The position within the chunk will
415         * automatically be incremented. Note: you cannot write beyond the
416         * boundaries of the chunk, to append data to the chunk call Resize()
417         * before.
418         *
419         * @param pData             source buffer (containing the data)
420         * @param WordCount         number of 8 Bit signed integers to write
421         * @returns                 number of written integers
422         * @throws RIFF::Exception  if an IO error occured
423         * @see Resize()
424         */
425        unsigned long Chunk::WriteInt8(int8_t* pData, unsigned long WordCount) {
426            return Write(pData, WordCount, 1);
427        }
428    
429        /**
430       * Reads \a WordCount number of 8 Bit unsigned integer words and copies       * Reads \a WordCount number of 8 Bit unsigned integer words and copies
431       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
432       * allocated. The position within the chunk will automatically be       * allocated. The position within the chunk will automatically be
# Line 233  namespace RIFF { Line 446  namespace RIFF {
446      }      }
447    
448      /**      /**
449         * Writes \a WordCount number of 8 Bit unsigned integer words from the
450         * buffer pointed by \a pData to the chunk's body, directly to the
451         * actual "physical" file. The position within the chunk will
452         * automatically be incremented. Note: you cannot write beyond the
453         * boundaries of the chunk, to append data to the chunk call Resize()
454         * before.
455         *
456         * @param pData             source buffer (containing the data)
457         * @param WordCount         number of 8 Bit unsigned integers to write
458         * @returns                 number of written integers
459         * @throws RIFF::Exception  if an IO error occured
460         * @see Resize()
461         */
462        unsigned long Chunk::WriteUint8(uint8_t* pData, unsigned long WordCount) {
463            return Write(pData, WordCount, 1);
464        }
465    
466        /**
467       * Reads \a WordCount number of 16 Bit signed integer words and copies       * Reads \a WordCount number of 16 Bit signed integer words and copies
468       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
469       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 252  namespace RIFF { Line 483  namespace RIFF {
483      }      }
484    
485      /**      /**
486         * Writes \a WordCount number of 16 Bit signed integer words from the
487         * buffer pointed by \a pData to the chunk's body, directly to the
488         * actual "physical" file. The position within the chunk will
489         * automatically be incremented. Note: you cannot write beyond the
490         * boundaries of the chunk, to append data to the chunk call Resize()
491         * before.
492         *
493         * @param pData             source buffer (containing the data)
494         * @param WordCount         number of 16 Bit signed integers to write
495         * @returns                 number of written integers
496         * @throws RIFF::Exception  if an IO error occured
497         * @see Resize()
498         */
499        unsigned long Chunk::WriteInt16(int16_t* pData, unsigned long WordCount) {
500            return Write(pData, WordCount, 2);
501        }
502    
503        /**
504       * Reads \a WordCount number of 16 Bit unsigned integer words and copies       * Reads \a WordCount number of 16 Bit unsigned integer words and copies
505       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
506       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 271  namespace RIFF { Line 520  namespace RIFF {
520      }      }
521    
522      /**      /**
523         * Writes \a WordCount number of 16 Bit unsigned integer words from the
524         * buffer pointed by \a pData to the chunk's body, directly to the
525         * actual "physical" file. The position within the chunk will
526         * automatically be incremented. Note: you cannot write beyond the
527         * boundaries of the chunk, to append data to the chunk call Resize()
528         * before.
529         *
530         * @param pData             source buffer (containing the data)
531         * @param WordCount         number of 16 Bit unsigned integers to write
532         * @returns                 number of written integers
533         * @throws RIFF::Exception  if an IO error occured
534         * @see Resize()
535         */
536        unsigned long Chunk::WriteUint16(uint16_t* pData, unsigned long WordCount) {
537            return Write(pData, WordCount, 2);
538        }
539    
540        /**
541       * Reads \a WordCount number of 32 Bit signed integer words and copies       * Reads \a WordCount number of 32 Bit signed integer words and copies
542       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
543       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 290  namespace RIFF { Line 557  namespace RIFF {
557      }      }
558    
559      /**      /**
560         * Writes \a WordCount number of 32 Bit signed integer words from the
561         * buffer pointed by \a pData to the chunk's body, directly to the
562         * actual "physical" file. The position within the chunk will
563         * automatically be incremented. Note: you cannot write beyond the
564         * boundaries of the chunk, to append data to the chunk call Resize()
565         * before.
566         *
567         * @param pData             source buffer (containing the data)
568         * @param WordCount         number of 32 Bit signed integers to write
569         * @returns                 number of written integers
570         * @throws RIFF::Exception  if an IO error occured
571         * @see Resize()
572         */
573        unsigned long Chunk::WriteInt32(int32_t* pData, unsigned long WordCount) {
574            return Write(pData, WordCount, 4);
575        }
576    
577        /**
578       * Reads \a WordCount number of 32 Bit unsigned integer words and copies       * Reads \a WordCount number of 32 Bit unsigned integer words and copies
579       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
580       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 309  namespace RIFF { Line 594  namespace RIFF {
594      }      }
595    
596      /**      /**
597         * Writes \a WordCount number of 32 Bit unsigned integer words from the
598         * buffer pointed by \a pData to the chunk's body, directly to the
599         * actual "physical" file. The position within the chunk will
600         * automatically be incremented. Note: you cannot write beyond the
601         * boundaries of the chunk, to append data to the chunk call Resize()
602         * before.
603         *
604         * @param pData             source buffer (containing the data)
605         * @param WordCount         number of 32 Bit unsigned integers to write
606         * @returns                 number of written integers
607         * @throws RIFF::Exception  if an IO error occured
608         * @see Resize()
609         */
610        unsigned long Chunk::WriteUint32(uint32_t* pData, unsigned long WordCount) {
611            return Write(pData, WordCount, 4);
612        }
613    
614        /**
615       * Reads one 8 Bit signed integer word and increments the position within       * Reads one 8 Bit signed integer word and increments the position within
616       * the chunk.       * the chunk.
617       *       *
# Line 408  namespace RIFF { Line 711  namespace RIFF {
711          return word;          return word;
712      }      }
713    
714        /** @brief Load chunk body into RAM.
715         *
716         * Loads the whole chunk body into memory. You can modify the data in
717         * RAM and save the data by calling File::Save() afterwards.
718         *
719         * <b>Caution:</b> the buffer pointer will be invalidated once
720         * File::Save() was called. You have to call LoadChunkData() again to
721         * get a new, valid pointer whenever File::Save() was called.
722         *
723         * You can call LoadChunkData() again if you previously scheduled to
724         * enlarge this chunk with a Resize() call. In that case the buffer will
725         * be enlarged to the new, scheduled chunk size and you can already
726         * place the new chunk data to the buffer and finally call File::Save()
727         * to enlarge the chunk physically and write the new data in one rush.
728         * This approach is definitely recommended if you have to enlarge and
729         * write new data to a lot of chunks.
730         *
731         * @returns a pointer to the data in RAM on success, NULL otherwise
732         * @throws Exception if data buffer could not be enlarged
733         * @see ReleaseChunkData()
734         */
735      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
736          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {
737              #if POSIX              #if POSIX
738              if (lseek(hFile, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
739              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
740              if (!pChunkData) return NULL;              if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;
             unsigned long readWords = read(hFile, pChunkData, GetSize());  
741              #else              #else
742              if (fseek(hFile, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
743              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
744                unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
745                pChunkData = new uint8_t[ulBufferSize];
746              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
747              unsigned long readWords = fread(pChunkData, 1, GetSize(), hFile);              memset(pChunkData, 0, ulBufferSize);
748                #if POSIX
749                unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
750                #elif defined(WIN32)
751                DWORD readWords;
752                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
753                #else
754                unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
755              #endif // POSIX              #endif // POSIX
756              if (readWords != GetSize()) {              if (readWords != GetSize()) {
757                  delete[] pChunkData;                  delete[] pChunkData;
758                  return (pChunkData = NULL);                  return (pChunkData = NULL);
759              }              }
760                ulChunkDataSize = ulBufferSize;
761            } else if (NewChunkSize > ulChunkDataSize) {
762                uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
763                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
764                memset(pNewBuffer, 0 , NewChunkSize);
765                memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
766                delete[] pChunkData;
767                pChunkData      = pNewBuffer;
768                ulChunkDataSize = NewChunkSize;
769          }          }
770          return pChunkData;          return pChunkData;
771      }      }
772    
773        /** @brief Free loaded chunk body from RAM.
774         *
775         * Frees loaded chunk body data from memory (RAM). You should call
776         * File::Save() before calling this method if you modified the data to
777         * make the changes persistent.
778         */
779      void Chunk::ReleaseChunkData() {      void Chunk::ReleaseChunkData() {
780          if (pChunkData) {          if (pChunkData) {
781              delete[] pChunkData;              delete[] pChunkData;
# Line 436  namespace RIFF { Line 783  namespace RIFF {
783          }          }
784      }      }
785    
786        /** @brief Resize chunk.
787         *
788         * Resizes this chunk's body, that is the actual size of data possible
789         * to be written to this chunk. This call will return immediately and
790         * just schedule the resize operation. You should call File::Save() to
791         * actually perform the resize operation(s) "physically" to the file.
792         * As this can take a while on large files, it is recommended to call
793         * Resize() first on all chunks which have to be resized and finally to
794         * call File::Save() to perform all those resize operations in one rush.
795         *
796         * <b>Caution:</b> You cannot directly write to enlarged chunks before
797         * calling File::Save() as this might exceed the current chunk's body
798         * boundary!
799         *
800         * @param iNewSize - new chunk body size in bytes (must be greater than zero)
801         * @throws RIFF::Exception  if \a iNewSize is less than 1
802         * @see File::Save()
803         */
804        void Chunk::Resize(int iNewSize) {
805            if (iNewSize <= 0)
806                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
807            if (NewChunkSize == iNewSize) return;
808            NewChunkSize = iNewSize;
809            pFile->LogAsResized(this);
810        }
811    
812        /** @brief Write chunk persistently e.g. to disk.
813         *
814         * Stores the chunk persistently to its actual "physical" file.
815         *
816         * @param ulWritePos - position within the "physical" file where this
817         *                     chunk should be written to
818         * @param ulCurrentDataOffset - offset of current (old) data within
819         *                              the file
820         * @returns new write position in the "physical" file, that is
821         *          \a ulWritePos incremented by this chunk's new size
822         *          (including its header size of course)
823         */
824        unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
825            const unsigned long ulOriginalPos = ulWritePos;
826            ulWritePos += CHUNK_HEADER_SIZE;
827    
828            if (pFile->Mode != stream_mode_read_write)
829                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
830    
831            // if the whole chunk body was loaded into RAM
832            if (pChunkData) {
833                // make sure chunk data buffer in RAM is at least as large as the new chunk size
834                LoadChunkData();
835                // write chunk data from RAM persistently to the file
836                #if POSIX
837                lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
838                if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
839                    throw Exception("Writing Chunk data (from RAM) failed");
840                }
841                #elif defined(WIN32)
842                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
843                DWORD dwBytesWritten;
844                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
845                if (dwBytesWritten != NewChunkSize) {
846                    throw Exception("Writing Chunk data (from RAM) failed");
847                }
848                #else
849                fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
850                if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
851                    throw Exception("Writing Chunk data (from RAM) failed");
852                }
853                #endif // POSIX
854            } else {
855                // move chunk data from the end of the file to the appropriate position
856                int8_t* pCopyBuffer = new int8_t[4096];
857                unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
858                #if defined(WIN32)
859                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
860                #else
861                int iBytesMoved = 1;
862                #endif
863                for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
864                    iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
865                    #if POSIX
866                    lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
867                    iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
868                    lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
869                    iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
870                    #elif defined(WIN32)
871                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
872                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
873                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
874                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
875                    #else
876                    fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
877                    iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
878                    fseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
879                    iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
880                    #endif
881                }
882                delete[] pCopyBuffer;
883                if (iBytesMoved < 0) throw Exception("Writing Chunk data (from file) failed");
884            }
885    
886            // update this chunk's header
887            CurrentChunkSize = NewChunkSize;
888            WriteHeader(ulOriginalPos);
889    
890            // update chunk's position pointers
891            ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;
892            ulPos      = 0;
893    
894            // add pad byte if needed
895            if ((ulStartPos + NewChunkSize) % 2 != 0) {
896                const char cPadByte = 0;
897                #if POSIX
898                lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
899                write(pFile->hFileWrite, &cPadByte, 1);
900                #elif defined(WIN32)
901                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
902                DWORD dwBytesWritten;
903                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
904                #else
905                fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
906                fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
907                #endif
908                return ulStartPos + NewChunkSize + 1;
909            }
910    
911            return ulStartPos + NewChunkSize;
912        }
913    
914        void Chunk::__resetPos() {
915            ulPos = 0;
916        }
917    
918    
919    
920  // *************** List ***************  // *************** List ***************
921  // *  // *
922    
923      List::List() : Chunk() {      List::List(File* pFile) : Chunk(pFile) {
924        #if DEBUG        #if DEBUG
925        std::cout << "List::List()" << std::endl;        std::cout << "List::List(File* pFile)" << std::endl;
926        #endif // DEBUG        #endif // DEBUG
927          pSubChunks    = NULL;          pSubChunks    = NULL;
928          pSubChunksMap = NULL;          pSubChunksMap = NULL;
929      }      }
930    
931      #if POSIX      List::List(File* pFile, unsigned long StartPos, List* Parent)
932      List::List(int hFile, unsigned long StartPos, bool EndianNative, List* Parent)        : Chunk(pFile, StartPos, Parent) {
     #else  
     List::List(FILE* hFile, unsigned long StartPos, bool EndianNative, List* Parent)  
     #endif // POSIX  
       : Chunk(hFile, StartPos, EndianNative, Parent) {  
933          #if DEBUG          #if DEBUG
934          std::cout << "List::List(FILE*,ulong,bool,List*)" << std::endl;          std::cout << "List::List(File*,ulong,bool,List*)" << std::endl;
935          #endif // DEBUG          #endif // DEBUG
936          pSubChunks    = NULL;          pSubChunks    = NULL;
937          pSubChunksMap = NULL;          pSubChunksMap = NULL;
# Line 464  namespace RIFF { Line 939  namespace RIFF {
939          ulStartPos    = StartPos + LIST_HEADER_SIZE;          ulStartPos    = StartPos + LIST_HEADER_SIZE;
940      }      }
941    
942        List::List(File* pFile, List* pParent, uint32_t uiListID)
943          : Chunk(pFile, pParent, CHUNK_ID_LIST, 0) {
944            pSubChunks    = NULL;
945            pSubChunksMap = NULL;
946            ListType      = uiListID;
947        }
948    
949      List::~List() {      List::~List() {
950        #if DEBUG        #if DEBUG
951        std::cout << "List::~List()" << std::endl;        std::cout << "List::~List()" << std::endl;
# Line 480  namespace RIFF { Line 962  namespace RIFF {
962          if (pSubChunksMap) delete pSubChunksMap;          if (pSubChunksMap) delete pSubChunksMap;
963      }      }
964    
965        /**
966         *  Returns subchunk with chunk ID <i>\a ChunkID</i> within this chunk
967         *  list. Use this method if you expect only one subchunk of that type in
968         *  the list. It there are more than one, it's undetermined which one of
969         *  them will be returned! If there are no subchunks with that desired
970         *  chunk ID, NULL will be returned.
971         *
972         *  @param ChunkID - chunk ID of the sought subchunk
973         *  @returns         pointer to the subchunk or NULL if there is none of
974         *                   that ID
975         */
976      Chunk* List::GetSubChunk(uint32_t ChunkID) {      Chunk* List::GetSubChunk(uint32_t ChunkID) {
977        #if DEBUG        #if DEBUG
978        std::cout << "List::GetSubChunk(uint32_t)" << std::endl;        std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
# Line 488  namespace RIFF { Line 981  namespace RIFF {
981          return (*pSubChunksMap)[ChunkID];          return (*pSubChunksMap)[ChunkID];
982      }      }
983    
984        /**
985         *  Returns sublist chunk with list type <i>\a ListType</i> within this
986         *  chunk list. Use this method if you expect only one sublist chunk of
987         *  that type in the list. It there are more than one, it's undetermined
988         *  which one of them will be returned! If there are no sublists with
989         *  that desired list type, NULL will be returned.
990         *
991         *  @param ListType - list type of the sought sublist
992         *  @returns          pointer to the sublist or NULL if there is none of
993         *                    that type
994         */
995      List* List::GetSubList(uint32_t ListType) {      List* List::GetSubList(uint32_t ListType) {
996          #if DEBUG          #if DEBUG
997          std::cout << "List::GetSubList(uint32_t)" << std::endl;          std::cout << "List::GetSubList(uint32_t)" << std::endl;
# Line 505  namespace RIFF { Line 1009  namespace RIFF {
1009          return NULL;          return NULL;
1010      }      }
1011    
1012        /**
1013         *  Returns the first subchunk within the list. You have to call this
1014         *  method before you can call GetNextSubChunk(). Recall it when you want
1015         *  to start from the beginning of the list again.
1016         *
1017         *  @returns  pointer to the first subchunk within the list, NULL
1018         *            otherwise
1019         */
1020      Chunk* List::GetFirstSubChunk() {      Chunk* List::GetFirstSubChunk() {
1021          #if DEBUG          #if DEBUG
1022          std::cout << "List::GetFirstSubChunk()" << std::endl;          std::cout << "List::GetFirstSubChunk()" << std::endl;
# Line 514  namespace RIFF { Line 1026  namespace RIFF {
1026          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1027      }      }
1028    
1029        /**
1030         *  Returns the next subchunk within the list. You have to call
1031         *  GetFirstSubChunk() before you can use this method!
1032         *
1033         *  @returns  pointer to the next subchunk within the list or NULL if
1034         *            end of list is reached
1035         */
1036      Chunk* List::GetNextSubChunk() {      Chunk* List::GetNextSubChunk() {
1037          #if DEBUG          #if DEBUG
1038          std::cout << "List::GetNextSubChunk()" << std::endl;          std::cout << "List::GetNextSubChunk()" << std::endl;
# Line 523  namespace RIFF { Line 1042  namespace RIFF {
1042          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1043      }      }
1044    
1045        /**
1046         *  Returns the first sublist within the list (that is a subchunk with
1047         *  chunk ID "LIST"). You have to call this method before you can call
1048         *  GetNextSubList(). Recall it when you want to start from the beginning
1049         *  of the list again.
1050         *
1051         *  @returns  pointer to the first sublist within the list, NULL
1052         *            otherwise
1053         */
1054      List* List::GetFirstSubList() {      List* List::GetFirstSubList() {
1055          #if DEBUG          #if DEBUG
1056          std::cout << "List::GetFirstSubList()" << std::endl;          std::cout << "List::GetFirstSubList()" << std::endl;
# Line 537  namespace RIFF { Line 1065  namespace RIFF {
1065          return NULL;          return NULL;
1066      }      }
1067    
1068        /**
1069         *  Returns the next sublist (that is a subchunk with chunk ID "LIST")
1070         *  within the list. You have to call GetFirstSubList() before you can
1071         *  use this method!
1072         *
1073         *  @returns  pointer to the next sublist within the list, NULL if
1074         *            end of list is reached
1075         */
1076      List* List::GetNextSubList() {      List* List::GetNextSubList() {
1077          #if DEBUG          #if DEBUG
1078          std::cout << "List::GetNextSubList()" << std::endl;          std::cout << "List::GetNextSubList()" << std::endl;
# Line 552  namespace RIFF { Line 1088  namespace RIFF {
1088          return NULL;          return NULL;
1089      }      }
1090    
1091        /**
1092         *  Returns number of subchunks within the list.
1093         */
1094      unsigned int List::CountSubChunks() {      unsigned int List::CountSubChunks() {
1095          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1096          return pSubChunks->size();          return pSubChunks->size();
1097      }      }
1098    
1099        /**
1100         *  Returns number of subchunks within the list with chunk ID
1101         *  <i>\a ChunkId</i>.
1102         */
1103      unsigned int List::CountSubChunks(uint32_t ChunkID) {      unsigned int List::CountSubChunks(uint32_t ChunkID) {
1104          unsigned int result = 0;          unsigned int result = 0;
1105          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
# Line 571  namespace RIFF { Line 1114  namespace RIFF {
1114          return result;          return result;
1115      }      }
1116    
1117        /**
1118         *  Returns number of sublists within the list.
1119         */
1120      unsigned int List::CountSubLists() {      unsigned int List::CountSubLists() {
1121          return CountSubChunks(CHUNK_ID_LIST);          return CountSubChunks(CHUNK_ID_LIST);
1122      }      }
1123    
1124        /**
1125         *  Returns number of sublists within the list with list type
1126         *  <i>\a ListType</i>
1127         */
1128      unsigned int List::CountSubLists(uint32_t ListType) {      unsigned int List::CountSubLists(uint32_t ListType) {
1129          unsigned int result = 0;          unsigned int result = 0;
1130          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
# Line 590  namespace RIFF { Line 1140  namespace RIFF {
1140          return result;          return result;
1141      }      }
1142    
1143        /** @brief Creates a new sub chunk.
1144         *
1145         * Creates and adds a new sub chunk to this list chunk. Note that the
1146         * chunk's body size given by \a uiBodySize must be greater than zero.
1147         * You have to call File::Save() to make this change persistent to the
1148         * actual file and <b>before</b> performing any data write operations
1149         * on the new chunk!
1150         *
1151         * @param uiChunkID  - chunk ID of the new chunk
1152         * @param uiBodySize - size of the new chunk's body, that is its actual
1153         *                     data size (without header)
1154         * @throws RIFF::Exception if \a uiBodySize equals zero
1155         */
1156        Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1157            if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1158            if (!pSubChunks) LoadSubChunks();
1159            Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1160            pSubChunks->push_back(pNewChunk);
1161            (*pSubChunksMap)[uiChunkID] = pNewChunk;
1162            pNewChunk->Resize(uiBodySize);
1163            NewChunkSize += CHUNK_HEADER_SIZE;
1164            pFile->LogAsResized(this);
1165            return pNewChunk;
1166        }
1167    
1168        /** @brief Moves a sub chunk.
1169         *
1170         * Moves a sub chunk from one position in a list to another
1171         * position in the same list. The pSrc chunk is placed before the
1172         * pDst chunk.
1173         *
1174         * @param pSrc - sub chunk to be moved
1175         * @param pDst - the position to move to. pSrc will be placed
1176         *               before pDst. If pDst is 0, pSrc will be placed
1177         *               last in list.
1178         */
1179        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1180            if (!pSubChunks) LoadSubChunks();
1181            pSubChunks->remove(pSrc);
1182            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1183            pSubChunks->insert(iter, pSrc);
1184        }
1185    
1186        /** @brief Creates a new list sub chunk.
1187         *
1188         * Creates and adds a new list sub chunk to this list chunk. Note that
1189         * you have to add sub chunks / sub list chunks to the new created chunk
1190         * <b>before</b> trying to make this change persisten to the actual
1191         * file with File::Save()!
1192         *
1193         * @param uiListType - list ID of the new list chunk
1194         */
1195        List* List::AddSubList(uint32_t uiListType) {
1196            if (!pSubChunks) LoadSubChunks();
1197            List* pNewListChunk = new List(pFile, this, uiListType);
1198            pSubChunks->push_back(pNewListChunk);
1199            (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1200            NewChunkSize += LIST_HEADER_SIZE;
1201            pFile->LogAsResized(this);
1202            return pNewListChunk;
1203        }
1204    
1205        /** @brief Removes a sub chunk.
1206         *
1207         * Removes the sub chunk given by \a pSubChunk from this list and frees
1208         * it completely from RAM. The given chunk can either be a normal sub
1209         * chunk or a list sub chunk. In case the given chunk is a list chunk,
1210         * all its subchunks (if any) will be removed recursively as well. You
1211         * should call File::Save() to make this change persistent at any time.
1212         *
1213         * @param pSubChunk - sub chunk or sub list chunk to be removed
1214         */
1215        void List::DeleteSubChunk(Chunk* pSubChunk) {
1216            if (!pSubChunks) LoadSubChunks();
1217            pSubChunks->remove(pSubChunk);
1218            if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1219                pSubChunksMap->erase(pSubChunk->GetChunkID());
1220                // try to find another chunk of the same chunk ID
1221                ChunkList::iterator iter = pSubChunks->begin();
1222                ChunkList::iterator end  = pSubChunks->end();
1223                for (; iter != end; ++iter) {
1224                    if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1225                        (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1226                        break; // we're done, stop search
1227                    }
1228                }
1229            }
1230            delete pSubChunk;
1231        }
1232    
1233      void List::ReadHeader(unsigned long fPos) {      void List::ReadHeader(unsigned long fPos) {
1234        #if DEBUG        #if DEBUG
1235        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1236        #endif // DEBUG        #endif // DEBUG
1237          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1238          ChunkSize -= 4;          if (CurrentChunkSize < 8) return;
1239            NewChunkSize = CurrentChunkSize -= 4;
1240          #if POSIX          #if POSIX
1241          lseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1242          read(hFile, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1243            #elif defined(WIN32)
1244            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1245            DWORD dwBytesRead;
1246            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1247          #else          #else
1248          fseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1249          fread(&ListType, 4, 1, hFile);          fread(&ListType, 4, 1, pFile->hFileRead);
1250          #endif // POSIX          #endif // POSIX
1251        #if DEBUG        #if DEBUG
1252        std::cout << "listType=" << convertToString(ListType) << std::endl;        std::cout << "listType=" << convertToString(ListType) << std::endl;
1253        #endif // DEBUG        #endif // DEBUG
1254          if (!bEndianNative) {          if (!pFile->bEndianNative) {
1255              swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1256          }          }
1257      }      }
1258    
1259        void List::WriteHeader(unsigned long fPos) {
1260            // the four list type bytes officially belong the chunk's body in the RIFF format
1261            NewChunkSize += 4;
1262            Chunk::WriteHeader(fPos);
1263            NewChunkSize -= 4; // just revert the +4 incrementation
1264            #if POSIX
1265            lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1266            write(pFile->hFileWrite, &ListType, 4);
1267            #elif defined(WIN32)
1268            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1269            DWORD dwBytesWritten;
1270            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1271            #else
1272            fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1273            fwrite(&ListType, 4, 1, pFile->hFileWrite);
1274            #endif // POSIX
1275        }
1276    
1277      void List::LoadSubChunks() {      void List::LoadSubChunks() {
1278         #if DEBUG         #if DEBUG
1279         std::cout << "List::LoadSubChunks()";         std::cout << "List::LoadSubChunks()";
# Line 618  namespace RIFF { Line 1281  namespace RIFF {
1281          if (!pSubChunks) {          if (!pSubChunks) {
1282              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1283              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1284                #if defined(WIN32)
1285                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1286                #else
1287                if (!pFile->hFileRead) return;
1288                #endif
1289                unsigned long uiOriginalPos = GetPos();
1290                SetPos(0); // jump to beginning of list chunk body
1291              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
1292                  Chunk* ck;                  Chunk* ck;
1293                  uint32_t ckid = ReadUint32();                  uint32_t ckid;
1294                    Read(&ckid, 4, 1);
1295         #if DEBUG         #if DEBUG
1296         std::cout << " ckid=" << convertToString(ckid) << std::endl;         std::cout << " ckid=" << convertToString(ckid) << std::endl;
1297         #endif // DEBUG         #endif // DEBUG
1298                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1299                      ck = new RIFF::List(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);
1300                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);
1301                  }                  }
1302                  else { // simple chunk                  else { // simple chunk
1303                      ck = new RIFF::Chunk(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);
1304                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);
1305                  }                  }
1306                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1307                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1308                  if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte                  if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte
1309              }              }
1310                SetPos(uiOriginalPos); // restore position before this call
1311            }
1312        }
1313    
1314        void List::LoadSubChunksRecursively() {
1315            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1316                pList->LoadSubChunksRecursively();
1317        }
1318    
1319        /** @brief Write list chunk persistently e.g. to disk.
1320         *
1321         * Stores the list chunk persistently to its actual "physical" file. All
1322         * subchunks (including sub list chunks) will be stored recursively as
1323         * well.
1324         *
1325         * @param ulWritePos - position within the "physical" file where this
1326         *                     list chunk should be written to
1327         * @param ulCurrentDataOffset - offset of current (old) data within
1328         *                              the file
1329         * @returns new write position in the "physical" file, that is
1330         *          \a ulWritePos incremented by this list chunk's new size
1331         *          (including its header size of course)
1332         */
1333        unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1334            const unsigned long ulOriginalPos = ulWritePos;
1335            ulWritePos += LIST_HEADER_SIZE;
1336    
1337            if (pFile->Mode != stream_mode_read_write)
1338                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1339    
1340            // write all subchunks (including sub list chunks) recursively
1341            if (pSubChunks) {
1342                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1343                    ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);
1344                }
1345            }
1346    
1347            // update this list chunk's header
1348            CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1349            WriteHeader(ulOriginalPos);
1350    
1351            // offset of this list chunk in new written file may have changed
1352            ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1353    
1354            return ulWritePos;
1355        }
1356    
1357        void List::__resetPos() {
1358            Chunk::__resetPos();
1359            if (pSubChunks) {
1360                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1361                    (*iter)->__resetPos();
1362                }
1363          }          }
1364      }      }
1365    
1366        /**
1367         *  Returns string representation of the lists's id
1368         */
1369      String List::GetListTypeString() {      String List::GetListTypeString() {
1370          return convertToString(ListType);          return convertToString(ListType);
1371      }      }
# Line 648  namespace RIFF { Line 1375  namespace RIFF {
1375  // *************** File ***************  // *************** File ***************
1376  // *  // *
1377    
1378      File::File(const String& path) : List() {      /** @brief Create new RIFF file.
1379         *
1380         * Use this constructor if you want to create a new RIFF file completely
1381         * "from scratch". Note: there must be no empty chunks or empty list
1382         * chunks when trying to make the new RIFF file persistent with Save()!
1383         *
1384         * Note: by default, the RIFF file will be saved in native endian
1385         * format; that is, as a RIFF file on little-endian machines and
1386         * as a RIFX file on big-endian. To change this behaviour, call
1387         * SetByteOrder() before calling Save().
1388         *
1389         * @param FileType - four-byte identifier of the RIFF file type
1390         * @see AddSubChunk(), AddSubList(), SetByteOrder()
1391         */
1392        File::File(uint32_t FileType) : List(this) {
1393            #if defined(WIN32)
1394            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1395            #else
1396            hFileRead = hFileWrite = 0;
1397            #endif
1398            Mode = stream_mode_closed;
1399            bEndianNative = true;
1400            ulStartPos = RIFF_HEADER_SIZE;
1401            ListType = FileType;
1402        }
1403    
1404        /** @brief Load existing RIFF file.
1405         *
1406         * Loads an existing RIFF file with all its chunks.
1407         *
1408         * @param path - path and file name of the RIFF file to open
1409         * @throws RIFF::Exception if error occured while trying to load the
1410         *                         given RIFF file
1411         */
1412        File::File(const String& path) : List(this), Filename(path) {
1413        #if DEBUG        #if DEBUG
1414        std::cout << "File::File("<<path<<")" << std::endl;        std::cout << "File::File("<<path<<")" << std::endl;
1415        #endif // DEBUG        #endif // DEBUG
1416          bEndianNative = true;          bEndianNative = true;
1417          #if POSIX          #if POSIX
1418          hFile = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1419          if (hFile <= 0) {          if (hFileRead <= 0) {
1420              hFile = 0;              hFileRead = hFileWrite = 0;
1421                throw RIFF::Exception("Can't open \"" + path + "\"");
1422            }
1423            #elif defined(WIN32)
1424            hFileRead = hFileWrite = CreateFile(
1425                                         path.c_str(), GENERIC_READ,
1426                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1427                                         NULL, OPEN_EXISTING,
1428                                         FILE_ATTRIBUTE_NORMAL |
1429                                         FILE_FLAG_RANDOM_ACCESS, NULL
1430                                     );
1431            if (hFileRead == INVALID_HANDLE_VALUE) {
1432                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1433              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1434          }          }
1435          #else          #else
1436          hFile = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1437          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1438          #endif // POSIX          #endif // POSIX
1439            Mode = stream_mode_read;
1440          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1441          ReadHeader(0);          ReadHeader(0);
1442          if (ChunkID != CHUNK_ID_RIFF) {          if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1443              throw RIFF::Exception("Not a RIFF file");              throw RIFF::Exception("Not a RIFF file");
1444          }          }
1445      }      }
1446    
1447        String File::GetFileName() {
1448            return Filename;
1449        }
1450    
1451        stream_mode_t File::GetMode() {
1452            return Mode;
1453        }
1454    
1455        /** @brief Change file access mode.
1456         *
1457         * Changes files access mode either to read-only mode or to read/write
1458         * mode.
1459         *
1460         * @param NewMode - new file access mode
1461         * @returns true if mode was changed, false if current mode already
1462         *          equals new mode
1463         * @throws RIFF::Exception if new file access mode is unknown
1464         */
1465        bool File::SetMode(stream_mode_t NewMode) {
1466            if (NewMode != Mode) {
1467                switch (NewMode) {
1468                    case stream_mode_read:
1469                        #if POSIX
1470                        if (hFileRead) close(hFileRead);
1471                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1472                        if (hFileRead < 0) {
1473                            hFileRead = hFileWrite = 0;
1474                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1475                        }
1476                        #elif defined(WIN32)
1477                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1478                        hFileRead = hFileWrite = CreateFile(
1479                                                     Filename.c_str(), GENERIC_READ,
1480                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1481                                                     NULL, OPEN_EXISTING,
1482                                                     FILE_ATTRIBUTE_NORMAL |
1483                                                     FILE_FLAG_RANDOM_ACCESS,
1484                                                     NULL
1485                                                 );
1486                        if (hFileRead == INVALID_HANDLE_VALUE) {
1487                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1488                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1489                        }
1490                        #else
1491                        if (hFileRead) fclose(hFileRead);
1492                        hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1493                        if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1494                        #endif
1495                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1496                        break;
1497                    case stream_mode_read_write:
1498                        #if POSIX
1499                        if (hFileRead) close(hFileRead);
1500                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1501                        if (hFileRead < 0) {
1502                            hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1503                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1504                        }
1505                        #elif defined(WIN32)
1506                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1507                        hFileRead = hFileWrite = CreateFile(
1508                                                     Filename.c_str(),
1509                                                     GENERIC_READ | GENERIC_WRITE,
1510                                                     FILE_SHARE_READ,
1511                                                     NULL, OPEN_ALWAYS,
1512                                                     FILE_ATTRIBUTE_NORMAL |
1513                                                     FILE_FLAG_RANDOM_ACCESS,
1514                                                     NULL
1515                                                 );
1516                        if (hFileRead == INVALID_HANDLE_VALUE) {
1517                            hFileRead = hFileWrite = CreateFile(
1518                                                         Filename.c_str(), GENERIC_READ,
1519                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1520                                                         NULL, OPEN_EXISTING,
1521                                                         FILE_ATTRIBUTE_NORMAL |
1522                                                         FILE_FLAG_RANDOM_ACCESS,
1523                                                         NULL
1524                                                     );
1525                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1526                        }
1527                        #else
1528                        if (hFileRead) fclose(hFileRead);
1529                        hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1530                        if (!hFileRead) {
1531                            hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1532                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1533                        }
1534                        #endif
1535                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1536                        break;
1537                    case stream_mode_closed:
1538                        #if POSIX
1539                        if (hFileRead)  close(hFileRead);
1540                        if (hFileWrite) close(hFileWrite);
1541                        #elif defined(WIN32)
1542                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1543                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1544                        #else
1545                        if (hFileRead)  fclose(hFileRead);
1546                        if (hFileWrite) fclose(hFileWrite);
1547                        #endif
1548                        hFileRead = hFileWrite = 0;
1549                        break;
1550                    default:
1551                        throw Exception("Unknown file access mode");
1552                }
1553                Mode = NewMode;
1554                return true;
1555            }
1556            return false;
1557        }
1558    
1559        /** @brief Set the byte order to be used when saving.
1560         *
1561         * Set the byte order to be used in the file. A value of
1562         * endian_little will create a RIFF file, endian_big a RIFX file
1563         * and endian_native will create a RIFF file on little-endian
1564         * machines and RIFX on big-endian machines.
1565         *
1566         * @param Endian - endianess to use when file is saved.
1567         */
1568        void File::SetByteOrder(endian_t Endian) {
1569            #if WORDS_BIGENDIAN
1570            bEndianNative = Endian != endian_little;
1571            #else
1572            bEndianNative = Endian != endian_big;
1573            #endif
1574        }
1575    
1576        /** @brief Save changes to same file.
1577         *
1578         * Make all changes of all chunks persistent by writing them to the
1579         * actual (same) file. The file might temporarily grow to a higher size
1580         * than it will have at the end of the saving process, in case chunks
1581         * were grown.
1582         *
1583         * @throws RIFF::Exception if there is an empty chunk or empty list
1584         *                         chunk or any kind of IO error occured
1585         */
1586        void File::Save() {
1587            // make sure the RIFF tree is built (from the original file)
1588            LoadSubChunksRecursively();
1589    
1590            // reopen file in write mode
1591            SetMode(stream_mode_read_write);
1592    
1593            // to be able to save the whole file without loading everything into
1594            // RAM and without having to store the data in a temporary file, we
1595            // enlarge the file with the sum of all _positive_ chunk size
1596            // changes, move current data towards the end of the file with the
1597            // calculated sum and finally update / rewrite the file by copying
1598            // the old data back to the right position at the beginning of the file
1599    
1600            // first we sum up all positive chunk size changes (and skip all negative ones)
1601            unsigned long ulPositiveSizeDiff = 0;
1602            for (std::set<Chunk*>::const_iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1603                if ((*iter)->GetNewSize() == 0) {
1604                    throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
1605                }
1606                unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1607                unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1608                if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1609            }
1610    
1611            unsigned long ulWorkingFileSize = GetFileSize();
1612    
1613            // if there are positive size changes...
1614            if (ulPositiveSizeDiff > 0) {
1615                // ... we enlarge this file first ...
1616                ulWorkingFileSize += ulPositiveSizeDiff;
1617                ResizeFile(ulWorkingFileSize);
1618                // ... and move current data by the same amount towards end of file.
1619                int8_t* pCopyBuffer = new int8_t[4096];
1620                const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1621                #if defined(WIN32)
1622                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1623                #else
1624                int iBytesMoved = 1;
1625                #endif
1626                for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1627                    iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1628                    ulPos -= iBytesMoved;
1629                    #if POSIX
1630                    lseek(hFileRead, ulPos, SEEK_SET);
1631                    iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1632                    lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1633                    iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1634                    #elif defined(WIN32)
1635                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1636                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1637                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1638                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1639                    #else
1640                    fseek(hFileRead, ulPos, SEEK_SET);
1641                    iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1642                    fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1643                    iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1644                    #endif
1645                }
1646                delete[] pCopyBuffer;
1647                if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1648            }
1649    
1650            // rebuild / rewrite complete RIFF tree
1651            unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);
1652            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1653    
1654            // resize file to the final size
1655            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1656    
1657            // forget all resized chunks
1658            ResizedChunks.clear();
1659        }
1660    
1661        /** @brief Save changes to another file.
1662         *
1663         * Make all changes of all chunks persistent by writing them to another
1664         * file. <b>Caution:</b> this method is optimized for writing to
1665         * <b>another</b> file, do not use it to save the changes to the same
1666         * file! Use File::Save() in that case instead! Ignoring this might
1667         * result in a corrupted file, especially in case chunks were resized!
1668         *
1669         * After calling this method, this File object will be associated with
1670         * the new file (given by \a path) afterwards.
1671         *
1672         * @param path - path and file name where everything should be written to
1673         */
1674        void File::Save(const String& path) {
1675            //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
1676    
1677            // make sure the RIFF tree is built (from the original file)
1678            LoadSubChunksRecursively();
1679    
1680            if (Filename.length() > 0) SetMode(stream_mode_read);
1681            // open the other (new) file for writing and truncate it to zero size
1682            #if POSIX
1683            hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1684            if (hFileWrite < 0) {
1685                hFileWrite = hFileRead;
1686                throw Exception("Could not open file \"" + path + "\" for writing");
1687            }
1688            #elif defined(WIN32)
1689            hFileWrite = CreateFile(
1690                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1691                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1692                             FILE_FLAG_RANDOM_ACCESS, NULL
1693                         );
1694            if (hFileWrite == INVALID_HANDLE_VALUE) {
1695                hFileWrite = hFileRead;
1696                throw Exception("Could not open file \"" + path + "\" for writing");
1697            }
1698            #else
1699            hFileWrite = fopen(path.c_str(), "w+b");
1700            if (!hFileWrite) {
1701                hFileWrite = hFileRead;
1702                throw Exception("Could not open file \"" + path + "\" for writing");
1703            }
1704            #endif // POSIX
1705            Mode = stream_mode_read_write;
1706    
1707            // write complete RIFF tree to the other (new) file
1708            unsigned long ulTotalSize  = WriteChunk(0, 0);
1709            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1710    
1711            // resize file to the final size (if the file was originally larger)
1712            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1713    
1714            // forget all resized chunks
1715            ResizedChunks.clear();
1716    
1717            #if POSIX
1718            if (hFileWrite) close(hFileWrite);
1719            #elif defined(WIN32)
1720            if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1721            #else
1722            if (hFileWrite) fclose(hFileWrite);
1723            #endif
1724            hFileWrite = hFileRead;
1725    
1726            // associate new file with this File object from now on
1727            Filename = path;
1728            Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1729            SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
1730        }
1731    
1732        void File::ResizeFile(unsigned long ulNewSize) {
1733            #if POSIX
1734            if (ftruncate(hFileWrite, ulNewSize) < 0)
1735                throw Exception("Could not resize file \"" + Filename + "\"");
1736            #elif defined(WIN32)
1737            if (
1738                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1739                !SetEndOfFile(hFileWrite)
1740            ) throw Exception("Could not resize file \"" + Filename + "\"");
1741            #else
1742            # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1743            # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1744            #endif
1745        }
1746    
1747      File::~File() {      File::~File() {
1748         #if DEBUG         #if DEBUG
1749         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
1750         #endif // DEBUG         #endif // DEBUG
1751          #if POSIX          #if POSIX
1752          if (hFile) close(hFile);          if (hFileRead) close(hFileRead);
1753            #elif defined(WIN32)
1754            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1755          #else          #else
1756          if (hFile) fclose(hFile);          if (hFileRead) fclose(hFileRead);
1757          #endif // POSIX          #endif // POSIX
1758      }      }
1759    
1760        void File::LogAsResized(Chunk* pResizedChunk) {
1761            ResizedChunks.insert(pResizedChunk);
1762        }
1763    
1764        void File::UnlogResized(Chunk* pResizedChunk) {
1765            ResizedChunks.erase(pResizedChunk);
1766        }
1767    
1768      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
1769          #if POSIX          return __GetFileSize(hFileRead);
1770        }
1771    
1772        #if POSIX
1773        unsigned long File::__GetFileSize(int hFile) {
1774          struct stat filestat;          struct stat filestat;
1775          fstat(hFile, &filestat);          fstat(hFile, &filestat);
1776          long size = filestat.st_size;          long size = filestat.st_size;
1777          #else // standard C functions          return size;
1778        }
1779        #elif defined(WIN32)
1780        unsigned long File::__GetFileSize(HANDLE hFile) {
1781            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1782            if (dwSize == INVALID_FILE_SIZE)
1783                throw Exception("Windows FS error: could not determine file size");
1784            return dwSize;
1785        }
1786        #else // standard C functions
1787        unsigned long File::__GetFileSize(FILE* hFile) {
1788          long curpos = ftell(hFile);          long curpos = ftell(hFile);
1789          fseek(hFile, 0, SEEK_END);          fseek(hFile, 0, SEEK_END);
1790          long size = ftell(hFile);          long size = ftell(hFile);
1791          fseek(hFile, curpos, SEEK_SET);          fseek(hFile, curpos, SEEK_SET);
         #endif // POSIX  
1792          return size;          return size;
1793      }      }
1794        #endif
1795    
1796    
1797  // *************** Exception ***************  // *************** Exception ***************
# Line 704  namespace RIFF { Line 1801  namespace RIFF {
1801          std::cout << "RIFF::Exception: " << Message << std::endl;          std::cout << "RIFF::Exception: " << Message << std::endl;
1802      }      }
1803    
1804    
1805    // *************** functions ***************
1806    // *
1807    
1808        /**
1809         * Returns the name of this C++ library. This is usually "libgig" of
1810         * course. This call is equivalent to DLS::libraryName() and
1811         * gig::libraryName().
1812         */
1813        String libraryName() {
1814            return PACKAGE;
1815        }
1816    
1817        /**
1818         * Returns version of this C++ library. This call is equivalent to
1819         * DLS::libraryVersion() and gig::libraryVersion().
1820         */
1821        String libraryVersion() {
1822            return VERSION;
1823        }
1824    
1825  } // namespace RIFF  } // namespace RIFF
 #endif  

Legend:
Removed from v.2  
changed lines
  Added in v.1863

  ViewVC Help
Powered by ViewVC