/[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 384 by schoenebeck, Thu Feb 17 02:22:26 2005 UTC revision 1885 by persson, Thu Apr 16 18:25:31 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-2005 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  *
# 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            if (pFile) 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
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              #if DEBUG
136              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
137              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << CurrentChunkSize << " ";
138              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
139              #endif // DEBUG              #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",       *  Returns the String representation of the chunk's ID (e.g. "RIFF",
180       *  "LIST").       *  "LIST").
# Line 105  namespace RIFF { Line 187  namespace RIFF {
187       *  Sets the position within the chunk body, thus within the data portion       *  Sets the position within the chunk body, thus within the data portion
188       *  of the chunk (in bytes).       *  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)       *  @param Where  - position offset (in bytes)
194       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,
195       *                  if omitted \a Where relates to beginning of the chunk       *                  if omitted \a Where relates to beginning of the chunk
# Line 119  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 128  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    
# Line 144  namespace RIFF { Line 229  namespace RIFF {
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      /**      /**
# Line 157  namespace RIFF { Line 242  namespace RIFF {
242       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
243       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
244       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
245       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
246       *    possible without SetPos()       *    possible without SetPos()
247       */       */
248      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
# Line 165  namespace RIFF { Line 250  namespace RIFF {
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 192  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 (ulPos >= ChunkSize) 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 223  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 249  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 268  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 287  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 306  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 325  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 344  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 443  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 471  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 499  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;
952        #endif // DEBUG        #endif // DEBUG
953            DeleteChunkList();
954        }
955    
956        void List::DeleteChunkList() {
957          if (pSubChunks) {          if (pSubChunks) {
958              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
959              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 511  namespace RIFF { Line 962  namespace RIFF {
962                  iter++;                  iter++;
963              }              }
964              delete pSubChunks;              delete pSubChunks;
965                pSubChunks = NULL;
966            }
967            if (pSubChunksMap) {
968                delete pSubChunksMap;
969                pSubChunksMap = NULL;
970          }          }
         if (pSubChunksMap) delete pSubChunksMap;  
971      }      }
972    
973      /**      /**
# Line 642  namespace RIFF { Line 1097  namespace RIFF {
1097      }      }
1098    
1099      /**      /**
1100       *  Returns number subchunks within the list.       *  Returns number of subchunks within the list.
1101       */       */
1102      unsigned int List::CountSubChunks() {      unsigned int List::CountSubChunks() {
1103          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
# Line 693  namespace RIFF { Line 1148  namespace RIFF {
1148          return result;          return result;
1149      }      }
1150    
1151        /** @brief Creates a new sub chunk.
1152         *
1153         * Creates and adds a new sub chunk to this list chunk. Note that the
1154         * chunk's body size given by \a uiBodySize must be greater than zero.
1155         * You have to call File::Save() to make this change persistent to the
1156         * actual file and <b>before</b> performing any data write operations
1157         * on the new chunk!
1158         *
1159         * @param uiChunkID  - chunk ID of the new chunk
1160         * @param uiBodySize - size of the new chunk's body, that is its actual
1161         *                     data size (without header)
1162         * @throws RIFF::Exception if \a uiBodySize equals zero
1163         */
1164        Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1165            if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1166            if (!pSubChunks) LoadSubChunks();
1167            Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1168            pSubChunks->push_back(pNewChunk);
1169            (*pSubChunksMap)[uiChunkID] = pNewChunk;
1170            pNewChunk->Resize(uiBodySize);
1171            NewChunkSize += CHUNK_HEADER_SIZE;
1172            pFile->LogAsResized(this);
1173            return pNewChunk;
1174        }
1175    
1176        /** @brief Moves a sub chunk.
1177         *
1178         * Moves a sub chunk from one position in a list to another
1179         * position in the same list. The pSrc chunk is placed before the
1180         * pDst chunk.
1181         *
1182         * @param pSrc - sub chunk to be moved
1183         * @param pDst - the position to move to. pSrc will be placed
1184         *               before pDst. If pDst is 0, pSrc will be placed
1185         *               last in list.
1186         */
1187        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1188            if (!pSubChunks) LoadSubChunks();
1189            pSubChunks->remove(pSrc);
1190            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1191            pSubChunks->insert(iter, pSrc);
1192        }
1193    
1194        /** @brief Creates a new list sub chunk.
1195         *
1196         * Creates and adds a new list sub chunk to this list chunk. Note that
1197         * you have to add sub chunks / sub list chunks to the new created chunk
1198         * <b>before</b> trying to make this change persisten to the actual
1199         * file with File::Save()!
1200         *
1201         * @param uiListType - list ID of the new list chunk
1202         */
1203        List* List::AddSubList(uint32_t uiListType) {
1204            if (!pSubChunks) LoadSubChunks();
1205            List* pNewListChunk = new List(pFile, this, uiListType);
1206            pSubChunks->push_back(pNewListChunk);
1207            (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1208            NewChunkSize += LIST_HEADER_SIZE;
1209            pFile->LogAsResized(this);
1210            return pNewListChunk;
1211        }
1212    
1213        /** @brief Removes a sub chunk.
1214         *
1215         * Removes the sub chunk given by \a pSubChunk from this list and frees
1216         * it completely from RAM. The given chunk can either be a normal sub
1217         * chunk or a list sub chunk. In case the given chunk is a list chunk,
1218         * all its subchunks (if any) will be removed recursively as well. You
1219         * should call File::Save() to make this change persistent at any time.
1220         *
1221         * @param pSubChunk - sub chunk or sub list chunk to be removed
1222         */
1223        void List::DeleteSubChunk(Chunk* pSubChunk) {
1224            if (!pSubChunks) LoadSubChunks();
1225            pSubChunks->remove(pSubChunk);
1226            if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1227                pSubChunksMap->erase(pSubChunk->GetChunkID());
1228                // try to find another chunk of the same chunk ID
1229                ChunkList::iterator iter = pSubChunks->begin();
1230                ChunkList::iterator end  = pSubChunks->end();
1231                for (; iter != end; ++iter) {
1232                    if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1233                        (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1234                        break; // we're done, stop search
1235                    }
1236                }
1237            }
1238            delete pSubChunk;
1239        }
1240    
1241      void List::ReadHeader(unsigned long fPos) {      void List::ReadHeader(unsigned long fPos) {
1242        #if DEBUG        #if DEBUG
1243        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1244        #endif // DEBUG        #endif // DEBUG
1245          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1246          ChunkSize -= 4;          if (CurrentChunkSize < 4) return;
1247            NewChunkSize = CurrentChunkSize -= 4;
1248          #if POSIX          #if POSIX
1249          lseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1250          read(hFile, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1251            #elif defined(WIN32)
1252            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1253            DWORD dwBytesRead;
1254            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1255          #else          #else
1256          fseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1257          fread(&ListType, 4, 1, hFile);          fread(&ListType, 4, 1, pFile->hFileRead);
1258          #endif // POSIX          #endif // POSIX
1259        #if DEBUG        #if DEBUG
1260        std::cout << "listType=" << convertToString(ListType) << std::endl;        std::cout << "listType=" << convertToString(ListType) << std::endl;
1261        #endif // DEBUG        #endif // DEBUG
1262          if (!bEndianNative) {          if (!pFile->bEndianNative) {
1263              //swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1264          }          }
1265      }      }
1266    
1267        void List::WriteHeader(unsigned long fPos) {
1268            // the four list type bytes officially belong the chunk's body in the RIFF format
1269            NewChunkSize += 4;
1270            Chunk::WriteHeader(fPos);
1271            NewChunkSize -= 4; // just revert the +4 incrementation
1272            #if POSIX
1273            lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1274            write(pFile->hFileWrite, &ListType, 4);
1275            #elif defined(WIN32)
1276            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1277            DWORD dwBytesWritten;
1278            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1279            #else
1280            fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1281            fwrite(&ListType, 4, 1, pFile->hFileWrite);
1282            #endif // POSIX
1283        }
1284    
1285      void List::LoadSubChunks() {      void List::LoadSubChunks() {
1286         #if DEBUG         #if DEBUG
1287         std::cout << "List::LoadSubChunks()";         std::cout << "List::LoadSubChunks()";
# Line 721  namespace RIFF { Line 1289  namespace RIFF {
1289          if (!pSubChunks) {          if (!pSubChunks) {
1290              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1291              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1292                #if defined(WIN32)
1293                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1294                #else
1295                if (!pFile->hFileRead) return;
1296                #endif
1297                unsigned long uiOriginalPos = GetPos();
1298                SetPos(0); // jump to beginning of list chunk body
1299              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
1300                  Chunk* ck;                  Chunk* ck;
1301                  uint32_t ckid;                  uint32_t ckid;
# Line 729  namespace RIFF { Line 1304  namespace RIFF {
1304         std::cout << " ckid=" << convertToString(ckid) << std::endl;         std::cout << " ckid=" << convertToString(ckid) << std::endl;
1305         #endif // DEBUG         #endif // DEBUG
1306                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1307                      ck = new RIFF::List(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);
1308                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);
1309                  }                  }
1310                  else { // simple chunk                  else { // simple chunk
1311                      ck = new RIFF::Chunk(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);
1312                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);
1313                  }                  }
1314                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1315                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1316                  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
1317              }              }
1318                SetPos(uiOriginalPos); // restore position before this call
1319            }
1320        }
1321    
1322        void List::LoadSubChunksRecursively() {
1323            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1324                pList->LoadSubChunksRecursively();
1325        }
1326    
1327        /** @brief Write list chunk persistently e.g. to disk.
1328         *
1329         * Stores the list chunk persistently to its actual "physical" file. All
1330         * subchunks (including sub list chunks) will be stored recursively as
1331         * well.
1332         *
1333         * @param ulWritePos - position within the "physical" file where this
1334         *                     list chunk should be written to
1335         * @param ulCurrentDataOffset - offset of current (old) data within
1336         *                              the file
1337         * @returns new write position in the "physical" file, that is
1338         *          \a ulWritePos incremented by this list chunk's new size
1339         *          (including its header size of course)
1340         */
1341        unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1342            const unsigned long ulOriginalPos = ulWritePos;
1343            ulWritePos += LIST_HEADER_SIZE;
1344    
1345            if (pFile->Mode != stream_mode_read_write)
1346                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1347    
1348            // write all subchunks (including sub list chunks) recursively
1349            if (pSubChunks) {
1350                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1351                    ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);
1352                }
1353            }
1354    
1355            // update this list chunk's header
1356            CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1357            WriteHeader(ulOriginalPos);
1358    
1359            // offset of this list chunk in new written file may have changed
1360            ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1361    
1362            return ulWritePos;
1363        }
1364    
1365        void List::__resetPos() {
1366            Chunk::__resetPos();
1367            if (pSubChunks) {
1368                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1369                    (*iter)->__resetPos();
1370                }
1371          }          }
1372      }      }
1373    
# Line 755  namespace RIFF { Line 1383  namespace RIFF {
1383  // *************** File ***************  // *************** File ***************
1384  // *  // *
1385    
1386      File::File(const String& path) : List() {      /** @brief Create new RIFF file.
1387         *
1388         * Use this constructor if you want to create a new RIFF file completely
1389         * "from scratch". Note: there must be no empty chunks or empty list
1390         * chunks when trying to make the new RIFF file persistent with Save()!
1391         *
1392         * Note: by default, the RIFF file will be saved in native endian
1393         * format; that is, as a RIFF file on little-endian machines and
1394         * as a RIFX file on big-endian. To change this behaviour, call
1395         * SetByteOrder() before calling Save().
1396         *
1397         * @param FileType - four-byte identifier of the RIFF file type
1398         * @see AddSubChunk(), AddSubList(), SetByteOrder()
1399         */
1400        File::File(uint32_t FileType) : List(this) {
1401            #if defined(WIN32)
1402            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1403            #else
1404            hFileRead = hFileWrite = 0;
1405            #endif
1406            Mode = stream_mode_closed;
1407            bEndianNative = true;
1408            ulStartPos = RIFF_HEADER_SIZE;
1409            ListType = FileType;
1410        }
1411    
1412        /** @brief Load existing RIFF file.
1413         *
1414         * Loads an existing RIFF file with all its chunks.
1415         *
1416         * @param path - path and file name of the RIFF file to open
1417         * @throws RIFF::Exception if error occured while trying to load the
1418         *                         given RIFF file
1419         */
1420        File::File(const String& path) : List(this), Filename(path) {
1421        #if DEBUG        #if DEBUG
1422        std::cout << "File::File("<<path<<")" << std::endl;        std::cout << "File::File("<<path<<")" << std::endl;
1423        #endif // DEBUG        #endif // DEBUG
1424          bEndianNative = true;          bEndianNative = true;
1425          #if POSIX          #if POSIX
1426          hFile = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1427          if (hFile <= 0) {          if (hFileRead <= 0) {
1428              hFile = 0;              hFileRead = hFileWrite = 0;
1429                throw RIFF::Exception("Can't open \"" + path + "\"");
1430            }
1431            #elif defined(WIN32)
1432            hFileRead = hFileWrite = CreateFile(
1433                                         path.c_str(), GENERIC_READ,
1434                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1435                                         NULL, OPEN_EXISTING,
1436                                         FILE_ATTRIBUTE_NORMAL |
1437                                         FILE_FLAG_RANDOM_ACCESS, NULL
1438                                     );
1439            if (hFileRead == INVALID_HANDLE_VALUE) {
1440                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1441              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1442          }          }
1443          #else          #else
1444          hFile = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1445          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1446          #endif // POSIX          #endif // POSIX
1447            Mode = stream_mode_read;
1448          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1449          ReadHeader(0);          ReadHeader(0);
1450          if (ChunkID != CHUNK_ID_RIFF) {          if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1451              throw RIFF::Exception("Not a RIFF file");              throw RIFF::Exception("Not a RIFF file");
1452          }          }
1453      }      }
1454    
1455        String File::GetFileName() {
1456            return Filename;
1457        }
1458    
1459        stream_mode_t File::GetMode() {
1460            return Mode;
1461        }
1462    
1463        /** @brief Change file access mode.
1464         *
1465         * Changes files access mode either to read-only mode or to read/write
1466         * mode.
1467         *
1468         * @param NewMode - new file access mode
1469         * @returns true if mode was changed, false if current mode already
1470         *          equals new mode
1471         * @throws RIFF::Exception if new file access mode is unknown
1472         */
1473        bool File::SetMode(stream_mode_t NewMode) {
1474            if (NewMode != Mode) {
1475                switch (NewMode) {
1476                    case stream_mode_read:
1477                        #if POSIX
1478                        if (hFileRead) close(hFileRead);
1479                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1480                        if (hFileRead < 0) {
1481                            hFileRead = hFileWrite = 0;
1482                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1483                        }
1484                        #elif defined(WIN32)
1485                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1486                        hFileRead = hFileWrite = CreateFile(
1487                                                     Filename.c_str(), GENERIC_READ,
1488                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1489                                                     NULL, OPEN_EXISTING,
1490                                                     FILE_ATTRIBUTE_NORMAL |
1491                                                     FILE_FLAG_RANDOM_ACCESS,
1492                                                     NULL
1493                                                 );
1494                        if (hFileRead == INVALID_HANDLE_VALUE) {
1495                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1496                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1497                        }
1498                        #else
1499                        if (hFileRead) fclose(hFileRead);
1500                        hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1501                        if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1502                        #endif
1503                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1504                        break;
1505                    case stream_mode_read_write:
1506                        #if POSIX
1507                        if (hFileRead) close(hFileRead);
1508                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1509                        if (hFileRead < 0) {
1510                            hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1511                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1512                        }
1513                        #elif defined(WIN32)
1514                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1515                        hFileRead = hFileWrite = CreateFile(
1516                                                     Filename.c_str(),
1517                                                     GENERIC_READ | GENERIC_WRITE,
1518                                                     FILE_SHARE_READ,
1519                                                     NULL, OPEN_ALWAYS,
1520                                                     FILE_ATTRIBUTE_NORMAL |
1521                                                     FILE_FLAG_RANDOM_ACCESS,
1522                                                     NULL
1523                                                 );
1524                        if (hFileRead == INVALID_HANDLE_VALUE) {
1525                            hFileRead = hFileWrite = CreateFile(
1526                                                         Filename.c_str(), GENERIC_READ,
1527                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1528                                                         NULL, OPEN_EXISTING,
1529                                                         FILE_ATTRIBUTE_NORMAL |
1530                                                         FILE_FLAG_RANDOM_ACCESS,
1531                                                         NULL
1532                                                     );
1533                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1534                        }
1535                        #else
1536                        if (hFileRead) fclose(hFileRead);
1537                        hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1538                        if (!hFileRead) {
1539                            hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1540                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1541                        }
1542                        #endif
1543                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1544                        break;
1545                    case stream_mode_closed:
1546                        #if POSIX
1547                        if (hFileRead)  close(hFileRead);
1548                        if (hFileWrite) close(hFileWrite);
1549                        #elif defined(WIN32)
1550                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1551                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1552                        #else
1553                        if (hFileRead)  fclose(hFileRead);
1554                        if (hFileWrite) fclose(hFileWrite);
1555                        #endif
1556                        hFileRead = hFileWrite = 0;
1557                        break;
1558                    default:
1559                        throw Exception("Unknown file access mode");
1560                }
1561                Mode = NewMode;
1562                return true;
1563            }
1564            return false;
1565        }
1566    
1567        /** @brief Set the byte order to be used when saving.
1568         *
1569         * Set the byte order to be used in the file. A value of
1570         * endian_little will create a RIFF file, endian_big a RIFX file
1571         * and endian_native will create a RIFF file on little-endian
1572         * machines and RIFX on big-endian machines.
1573         *
1574         * @param Endian - endianess to use when file is saved.
1575         */
1576        void File::SetByteOrder(endian_t Endian) {
1577            #if WORDS_BIGENDIAN
1578            bEndianNative = Endian != endian_little;
1579            #else
1580            bEndianNative = Endian != endian_big;
1581            #endif
1582        }
1583    
1584        /** @brief Save changes to same file.
1585         *
1586         * Make all changes of all chunks persistent by writing them to the
1587         * actual (same) file. The file might temporarily grow to a higher size
1588         * than it will have at the end of the saving process, in case chunks
1589         * were grown.
1590         *
1591         * @throws RIFF::Exception if there is an empty chunk or empty list
1592         *                         chunk or any kind of IO error occured
1593         */
1594        void File::Save() {
1595            // make sure the RIFF tree is built (from the original file)
1596            LoadSubChunksRecursively();
1597    
1598            // reopen file in write mode
1599            SetMode(stream_mode_read_write);
1600    
1601            // to be able to save the whole file without loading everything into
1602            // RAM and without having to store the data in a temporary file, we
1603            // enlarge the file with the sum of all _positive_ chunk size
1604            // changes, move current data towards the end of the file with the
1605            // calculated sum and finally update / rewrite the file by copying
1606            // the old data back to the right position at the beginning of the file
1607    
1608            // first we sum up all positive chunk size changes (and skip all negative ones)
1609            unsigned long ulPositiveSizeDiff = 0;
1610            for (std::set<Chunk*>::const_iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1611                if ((*iter)->GetNewSize() == 0) {
1612                    throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
1613                }
1614                unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1615                unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1616                if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1617            }
1618    
1619            unsigned long ulWorkingFileSize = GetFileSize();
1620    
1621            // if there are positive size changes...
1622            if (ulPositiveSizeDiff > 0) {
1623                // ... we enlarge this file first ...
1624                ulWorkingFileSize += ulPositiveSizeDiff;
1625                ResizeFile(ulWorkingFileSize);
1626                // ... and move current data by the same amount towards end of file.
1627                int8_t* pCopyBuffer = new int8_t[4096];
1628                const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1629                #if defined(WIN32)
1630                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1631                #else
1632                int iBytesMoved = 1;
1633                #endif
1634                for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1635                    iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1636                    ulPos -= iBytesMoved;
1637                    #if POSIX
1638                    lseek(hFileRead, ulPos, SEEK_SET);
1639                    iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1640                    lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1641                    iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1642                    #elif defined(WIN32)
1643                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1644                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1645                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1646                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1647                    #else
1648                    fseek(hFileRead, ulPos, SEEK_SET);
1649                    iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1650                    fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1651                    iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1652                    #endif
1653                }
1654                delete[] pCopyBuffer;
1655                if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1656            }
1657    
1658            // rebuild / rewrite complete RIFF tree
1659            unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);
1660            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1661    
1662            // resize file to the final size
1663            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1664    
1665            // forget all resized chunks
1666            ResizedChunks.clear();
1667        }
1668    
1669        /** @brief Save changes to another file.
1670         *
1671         * Make all changes of all chunks persistent by writing them to another
1672         * file. <b>Caution:</b> this method is optimized for writing to
1673         * <b>another</b> file, do not use it to save the changes to the same
1674         * file! Use File::Save() in that case instead! Ignoring this might
1675         * result in a corrupted file, especially in case chunks were resized!
1676         *
1677         * After calling this method, this File object will be associated with
1678         * the new file (given by \a path) afterwards.
1679         *
1680         * @param path - path and file name where everything should be written to
1681         */
1682        void File::Save(const String& path) {
1683            //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
1684    
1685            // make sure the RIFF tree is built (from the original file)
1686            LoadSubChunksRecursively();
1687    
1688            if (Filename.length() > 0) SetMode(stream_mode_read);
1689            // open the other (new) file for writing and truncate it to zero size
1690            #if POSIX
1691            hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1692            if (hFileWrite < 0) {
1693                hFileWrite = hFileRead;
1694                throw Exception("Could not open file \"" + path + "\" for writing");
1695            }
1696            #elif defined(WIN32)
1697            hFileWrite = CreateFile(
1698                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1699                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1700                             FILE_FLAG_RANDOM_ACCESS, NULL
1701                         );
1702            if (hFileWrite == INVALID_HANDLE_VALUE) {
1703                hFileWrite = hFileRead;
1704                throw Exception("Could not open file \"" + path + "\" for writing");
1705            }
1706            #else
1707            hFileWrite = fopen(path.c_str(), "w+b");
1708            if (!hFileWrite) {
1709                hFileWrite = hFileRead;
1710                throw Exception("Could not open file \"" + path + "\" for writing");
1711            }
1712            #endif // POSIX
1713            Mode = stream_mode_read_write;
1714    
1715            // write complete RIFF tree to the other (new) file
1716            unsigned long ulTotalSize  = WriteChunk(0, 0);
1717            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1718    
1719            // resize file to the final size (if the file was originally larger)
1720            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1721    
1722            // forget all resized chunks
1723            ResizedChunks.clear();
1724    
1725            #if POSIX
1726            if (hFileWrite) close(hFileWrite);
1727            #elif defined(WIN32)
1728            if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1729            #else
1730            if (hFileWrite) fclose(hFileWrite);
1731            #endif
1732            hFileWrite = hFileRead;
1733    
1734            // associate new file with this File object from now on
1735            Filename = path;
1736            Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1737            SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
1738        }
1739    
1740        void File::ResizeFile(unsigned long ulNewSize) {
1741            #if POSIX
1742            if (ftruncate(hFileWrite, ulNewSize) < 0)
1743                throw Exception("Could not resize file \"" + Filename + "\"");
1744            #elif defined(WIN32)
1745            if (
1746                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1747                !SetEndOfFile(hFileWrite)
1748            ) throw Exception("Could not resize file \"" + Filename + "\"");
1749            #else
1750            # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1751            # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1752            #endif
1753        }
1754    
1755      File::~File() {      File::~File() {
1756         #if DEBUG         #if DEBUG
1757         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
1758         #endif // DEBUG         #endif // DEBUG
1759          #if POSIX          #if POSIX
1760          if (hFile) close(hFile);          if (hFileRead) close(hFileRead);
1761            #elif defined(WIN32)
1762            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1763          #else          #else
1764          if (hFile) fclose(hFile);          if (hFileRead) fclose(hFileRead);
1765          #endif // POSIX          #endif // POSIX
1766            DeleteChunkList();
1767            pFile = NULL;
1768        }
1769    
1770        void File::LogAsResized(Chunk* pResizedChunk) {
1771            ResizedChunks.insert(pResizedChunk);
1772        }
1773    
1774        void File::UnlogResized(Chunk* pResizedChunk) {
1775            ResizedChunks.erase(pResizedChunk);
1776      }      }
1777    
1778      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
1779          #if POSIX          return __GetFileSize(hFileRead);
1780        }
1781    
1782        #if POSIX
1783        unsigned long File::__GetFileSize(int hFile) {
1784          struct stat filestat;          struct stat filestat;
1785          fstat(hFile, &filestat);          fstat(hFile, &filestat);
1786          long size = filestat.st_size;          long size = filestat.st_size;
1787          #else // standard C functions          return size;
1788        }
1789        #elif defined(WIN32)
1790        unsigned long File::__GetFileSize(HANDLE hFile) {
1791            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1792            if (dwSize == INVALID_FILE_SIZE)
1793                throw Exception("Windows FS error: could not determine file size");
1794            return dwSize;
1795        }
1796        #else // standard C functions
1797        unsigned long File::__GetFileSize(FILE* hFile) {
1798          long curpos = ftell(hFile);          long curpos = ftell(hFile);
1799          fseek(hFile, 0, SEEK_END);          fseek(hFile, 0, SEEK_END);
1800          long size = ftell(hFile);          long size = ftell(hFile);
1801          fseek(hFile, curpos, SEEK_SET);          fseek(hFile, curpos, SEEK_SET);
         #endif // POSIX  
1802          return size;          return size;
1803      }      }
1804        #endif
1805    
1806    
1807  // *************** Exception ***************  // *************** Exception ***************
# Line 811  namespace RIFF { Line 1811  namespace RIFF {
1811          std::cout << "RIFF::Exception: " << Message << std::endl;          std::cout << "RIFF::Exception: " << Message << std::endl;
1812      }      }
1813    
1814    
1815    // *************** functions ***************
1816    // *
1817    
1818        /**
1819         * Returns the name of this C++ library. This is usually "libgig" of
1820         * course. This call is equivalent to DLS::libraryName() and
1821         * gig::libraryName().
1822         */
1823        String libraryName() {
1824            return PACKAGE;
1825        }
1826    
1827        /**
1828         * Returns version of this C++ library. This call is equivalent to
1829         * DLS::libraryVersion() and gig::libraryVersion().
1830         */
1831        String libraryVersion() {
1832            return VERSION;
1833        }
1834    
1835  } // namespace RIFF  } // namespace RIFF
 #endif  

Legend:
Removed from v.384  
changed lines
  Added in v.1885

  ViewVC Help
Powered by ViewVC