/[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 666 by persson, Sun Jun 19 15:18:59 2005 UTC revision 2912 by schoenebeck, Tue May 17 14:30:10 2016 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-2016 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 <set>
26    #include <string.h>
27    
28  #include "RIFF.h"  #include "RIFF.h"
29    
30    #include "helper.h"
31    
32    #if POSIX
33    # include <errno.h>
34    #endif
35    
36  namespace RIFF {  namespace RIFF {
37    
38    // *************** Internal functions **************
39    // *
40    
41        /// Returns a human readable path of the given chunk.
42        static String __resolveChunkPath(Chunk* pCk) {
43            String sPath;
44            for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
45                if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
46                    List* pList = (List*) pChunk;
47                    sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
48                } else {
49                    sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
50                }
51            }
52            return sPath;
53        }
54    
55    
56    
57    // *************** progress_t ***************
58    // *
59    
60        progress_t::progress_t() {
61            callback    = NULL;
62            custom      = NULL;
63            __range_min = 0.0f;
64            __range_max = 1.0f;
65        }
66    
67    
68    
69  // *************** Chunk **************  // *************** Chunk **************
70  // *  // *
71    
72      Chunk::Chunk() {      Chunk::Chunk(File* pFile) {
73          #if DEBUG          #if DEBUG
74          std::cout << "Chunk::Chunk()" << std::endl;          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
75          #endif // DEBUG          #endif // DEBUG
76          ulPos      = 0;          ullPos     = 0;
77          pParent    = NULL;          pParent    = NULL;
78          pChunkData = NULL;          pChunkData = NULL;
79            ullCurrentChunkSize = 0;
80            ullNewChunkSize = 0;
81            ullChunkDataSize = 0;
82            ChunkID    = CHUNK_ID_RIFF;
83            this->pFile = pFile;
84      }      }
85    
86      #if POSIX      Chunk::Chunk(File* pFile, file_offset_t StartPos, List* Parent) {
87      Chunk::Chunk(int hFile, unsigned long StartPos, bool EndianNative, List* Parent) {          #if DEBUG
88      #else          std::cout << "Chunk::Chunk(File*,file_offset_t,List*),StartPos=" << StartPos << std::endl;
89      Chunk::Chunk(FILE* hFile, unsigned long StartPos, bool EndianNative, List* Parent) {          #endif // DEBUG
90      #endif // POSIX          this->pFile   = pFile;
91          #if DEBUG          ullStartPos   = StartPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
         std::cout << "Chunk::Chunk(FILE,ulong,bool,List*),StartPos=" << StartPos << std::endl;  
         #endif // DEBUG  
         Chunk::hFile  = hFile;  
         ulStartPos    = StartPos + CHUNK_HEADER_SIZE;  
         bEndianNative = EndianNative;  
92          pParent       = Parent;          pParent       = Parent;
93          ulPos         = 0;          ullPos        = 0;
94          pChunkData    = NULL;          pChunkData    = NULL;
95            ullCurrentChunkSize = 0;
96            ullNewChunkSize = 0;
97            ullChunkDataSize = 0;
98          ReadHeader(StartPos);          ReadHeader(StartPos);
99      }      }
100    
101        Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, file_offset_t ullBodySize) {
102            this->pFile      = pFile;
103            ullStartPos      = 0; // arbitrary usually, since it will be updated when we write the chunk
104            this->pParent    = pParent;
105            ullPos           = 0;
106            pChunkData       = NULL;
107            ChunkID          = uiChunkID;
108            ullChunkDataSize = 0;
109            ullCurrentChunkSize = 0;
110            ullNewChunkSize  = ullBodySize;
111        }
112    
113      Chunk::~Chunk() {      Chunk::~Chunk() {
114          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
115      }      }
116    
117      void Chunk::ReadHeader(unsigned long fPos) {      void Chunk::ReadHeader(file_offset_t filePos) {
118          #if DEBUG          #if DEBUG
119          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << filePos << ") ";
120          #endif // DEBUG          #endif // DEBUG
121            ChunkID = 0;
122            ullNewChunkSize = ullCurrentChunkSize = 0;
123          #if POSIX          #if POSIX
124          if (lseek(hFile, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, filePos, SEEK_SET) != -1) {
125              read(hFile, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
126              read(hFile, &ChunkSize, 4);              read(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize);
127            #elif defined(WIN32)
128            if (SetFilePointerEx(pFile->hFileRead, filePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
129                DWORD dwBytesRead;
130                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
131                ReadFile(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize, &dwBytesRead, NULL);
132          #else          #else
133          if (!fseek(hFile, fPos, SEEK_SET)) {          if (!fseeko(pFile->hFileRead, filePos, SEEK_SET)) {
134              fread(&ChunkID, 4, 1, hFile);              fread(&ChunkID, 4, 1, pFile->hFileRead);
135              fread(&ChunkSize, 4, 1, hFile);              fread(&ullCurrentChunkSize, pFile->FileOffsetSize, 1, pFile->hFileRead);
136          #endif // POSIX          #endif // POSIX
137              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
138              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
139                  bEndianNative = false;                  pFile->bEndianNative = false;
140              }              }
141              #else // little endian              #else // little endian
142              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
143                  bEndianNative = false;                  pFile->bEndianNative = false;
144                  ChunkID = CHUNK_ID_RIFF;                  ChunkID = CHUNK_ID_RIFF;
145              }              }
146              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
147              if (!bEndianNative) {              if (!pFile->bEndianNative) {
148                  //swapBytes_32(&ChunkID);                  //swapBytes_32(&ChunkID);
149                  swapBytes_32(&ChunkSize);                  if (pFile->FileOffsetSize == 4)
150                        swapBytes_32(&ullCurrentChunkSize);
151                    else
152                        swapBytes_64(&ullCurrentChunkSize);
153              }              }
154              #if DEBUG              #if DEBUG
155              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
156              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << ullCurrentChunkSize << " ";
157              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
158              #endif // DEBUG              #endif // DEBUG
159                ullNewChunkSize = ullCurrentChunkSize;
160          }          }
161      }      }
162    
163        void Chunk::WriteHeader(file_offset_t filePos) {
164            uint32_t uiNewChunkID = ChunkID;
165            if (ChunkID == CHUNK_ID_RIFF) {
166                #if WORDS_BIGENDIAN
167                if (pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
168                #else // little endian
169                if (!pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
170                #endif // WORDS_BIGENDIAN
171            }
172    
173            uint64_t ullNewChunkSize = this->ullNewChunkSize;
174            if (!pFile->bEndianNative) {
175                if (pFile->FileOffsetSize == 4)
176                    swapBytes_32(&ullNewChunkSize);
177                else
178                    swapBytes_64(&ullNewChunkSize);
179            }
180    
181            #if POSIX
182            if (lseek(pFile->hFileWrite, filePos, SEEK_SET) != -1) {
183                write(pFile->hFileWrite, &uiNewChunkID, 4);
184                write(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize);
185            }
186            #elif defined(WIN32)
187            if (SetFilePointerEx(pFile->hFileWrite, filePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
188                DWORD dwBytesWritten;
189                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
190                WriteFile(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize, &dwBytesWritten, NULL);
191            }
192            #else
193            if (!fseeko(pFile->hFileWrite, filePos, SEEK_SET)) {
194                fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
195                fwrite(&ullNewChunkSize, pFile->FileOffsetSize, 1, pFile->hFileWrite);
196            }
197            #endif // POSIX
198        }
199    
200      /**      /**
201       *  Returns the String representation of the chunk's ID (e.g. "RIFF",       *  Returns the String representation of the chunk's ID (e.g. "RIFF",
202       *  "LIST").       *  "LIST").
203       */       */
204      String Chunk::GetChunkIDString() {      String Chunk::GetChunkIDString() const {
205          return convertToString(ChunkID);          return convertToString(ChunkID);
206      }      }
207    
# Line 105  namespace RIFF { Line 209  namespace RIFF {
209       *  Sets the position within the chunk body, thus within the data portion       *  Sets the position within the chunk body, thus within the data portion
210       *  of the chunk (in bytes).       *  of the chunk (in bytes).
211       *       *
212         *  <b>Caution:</b> the position will be reset to zero whenever
213         *  File::Save() was called.
214         *
215       *  @param Where  - position offset (in bytes)       *  @param Where  - position offset (in bytes)
216       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,
217       *                  if omitted \a Where relates to beginning of the chunk       *                  if omitted \a Where relates to beginning of the chunk
218       *                  data       *                  data
219       */       */
220      unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {      file_offset_t Chunk::SetPos(file_offset_t Where, stream_whence_t Whence) {
221       #if DEBUG          #if DEBUG
222       std::cout << "Chunk::SetPos(ulong)" << std::endl;          std::cout << "Chunk::SetPos(file_offset_t,stream_whence_t)" << std::endl;
223       #endif // DEBUG          #endif // DEBUG
224          switch (Whence) {          switch (Whence) {
225              case stream_curpos:              case stream_curpos:
226                  ulPos += Where;                  ullPos += Where;
227                  break;                  break;
228              case stream_end:              case stream_end:
229                  ulPos = ChunkSize - 1 - Where;                  ullPos = ullCurrentChunkSize - 1 - Where;
230                  break;                  break;
231              case stream_backward:              case stream_backward:
232                  ulPos -= Where;                  ullPos -= Where;
233                  break;                  break;
234              case stream_start: default:              case stream_start: default:
235                  ulPos = Where;                  ullPos = Where;
236                  break;                  break;
237          }          }
238          if (ulPos > ChunkSize) ulPos = ChunkSize;          if (ullPos > ullCurrentChunkSize) ullPos = ullCurrentChunkSize;
239          return ulPos;          return ullPos;
240      }      }
241    
242      /**      /**
# Line 142  namespace RIFF { Line 249  namespace RIFF {
249       *       *
250       *  @returns  number of bytes left to read       *  @returns  number of bytes left to read
251       */       */
252      unsigned long Chunk::RemainingBytes() {      file_offset_t Chunk::RemainingBytes() const {
253         #if DEBUG          #if DEBUG
254         std::cout << "Chunk::Remainingbytes()=" << ChunkSize - ulPos << std::endl;          std::cout << "Chunk::Remainingbytes()=" << ullCurrentChunkSize - ullPos << std::endl;
255         #endif // DEBUG          #endif // DEBUG
256          return ChunkSize - ulPos;          return (ullCurrentChunkSize > ullPos) ? ullCurrentChunkSize - ullPos : 0;
257        }
258    
259        /**
260         *  Returns the actual total size in bytes (including header) of this Chunk
261         *  if being stored to a file.
262         *
263         *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
264         *                          being saved to a file
265         */
266        file_offset_t Chunk::RequiredPhysicalSize(int fileOffsetSize) {
267            return CHUNK_HEADER_SIZE(fileOffsetSize) + // RIFF chunk header
268                   ullNewChunkSize + // chunks's actual data body
269                   ullNewChunkSize % 2; // optional pad byte
270      }      }
271    
272      /**      /**
# Line 157  namespace RIFF { Line 277  namespace RIFF {
277       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
278       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
279       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
280       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
281       *    possible without SetPos()       *    possible without SetPos()
282       */       */
283      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() const {
284        #if DEBUG          #if DEBUG
285        std::cout << "Chunk::GetState()" << std::endl;          std::cout << "Chunk::GetState()" << std::endl;
286        #endif // DEBUG          #endif // DEBUG
287          #if POSIX          #if POSIX
288          if (hFile == 0)        return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
289            #elif defined (WIN32)
290            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
291                return stream_closed;
292          #else          #else
293          if (hFile == NULL)     return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
294          #endif // POSIX          #endif // POSIX
295          if (ulPos < ChunkSize) return stream_ready;          if (ullPos < ullCurrentChunkSize) return stream_ready;
296          else                   return stream_end_reached;          else                              return stream_end_reached;
297      }      }
298    
299      /**      /**
# Line 188  namespace RIFF { Line 311  namespace RIFF {
311       *  @returns          number of successfully read data words or 0 if end       *  @returns          number of successfully read data words or 0 if end
312       *                    of file reached or error occured       *                    of file reached or error occured
313       */       */
314      unsigned long Chunk::Read(void* pData, unsigned long WordCount, unsigned long WordSize) {      file_offset_t Chunk::Read(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
315         #if DEBUG          #if DEBUG
316         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;          std::cout << "Chunk::Read(void*,file_offset_t,file_offset_t)" << std::endl;
317         #endif // DEBUG          #endif // DEBUG
318          if (ulPos >= ChunkSize) return 0;          //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
319          if (ulPos + WordCount * WordSize >= ChunkSize) WordCount = (ChunkSize - ulPos) / WordSize;          if (ullPos >= ullCurrentChunkSize) return 0;
320            if (ullPos + WordCount * WordSize >= ullCurrentChunkSize) WordCount = (ullCurrentChunkSize - ullPos) / WordSize;
321          #if POSIX          #if POSIX
322          if (lseek(hFile, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET) < 0) return 0;
323          unsigned long readWords = read(hFile, pData, WordCount * WordSize);          ssize_t readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
324            if (readWords < 1) {
325                #if DEBUG
326                std::cerr << "POSIX read() failed: " << strerror(errno) << std::endl << std::flush;
327                #endif // DEBUG
328                return 0;
329            }
330            readWords /= WordSize;
331            #elif defined(WIN32)
332            if (!SetFilePointerEx(pFile->hFileRead, ullStartPos + ullPos, NULL/*new pos pointer*/, FILE_BEGIN))
333                return 0;
334            DWORD readWords;
335            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL); //FIXME: does not work for reading buffers larger than 2GB (even though this should rarely be the case in practice)
336          if (readWords < 1) return 0;          if (readWords < 1) return 0;
337          readWords /= WordSize;          readWords /= WordSize;
338          #else // standard C functions          #else // standard C functions
339          if (fseek(hFile, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseeko(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET)) return 0;
340          unsigned long readWords = fread(pData, WordSize, WordCount, hFile);          file_offset_t readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
341          #endif // POSIX          #endif // POSIX
342          if (!bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
343              switch (WordSize) {              switch (WordSize) {
344                  case 2:                  case 2:
345                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
346                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
347                      break;                      break;
348                  case 4:                  case 4:
349                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
350                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
351                      break;                      break;
352                    case 8:
353                        for (file_offset_t iWord = 0; iWord < readWords; iWord++)
354                            swapBytes_64((uint64_t*) pData + iWord);
355                        break;
356                  default:                  default:
357                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
358                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
359                      break;                      break;
360              }              }
# Line 223  namespace RIFF { Line 363  namespace RIFF {
363          return readWords;          return readWords;
364      }      }
365    
366        /**
367         *  Writes \a WordCount number of data words with given \a WordSize from
368         *  the buffer pointed by \a pData. Be sure to provide the correct
369         *  \a WordSize, as this will be important and taken into account for
370         *  eventual endian correction (swapping of bytes due to different
371         *  native byte order of a system). The position within the chunk will
372         *  automatically be incremented.
373         *
374         *  @param pData      source buffer (containing the data)
375         *  @param WordCount  number of data words to write
376         *  @param WordSize   size of each data word to write
377         *  @returns          number of successfully written data words
378         *  @throws RIFF::Exception  if write operation would exceed current
379         *                           chunk size or any IO error occured
380         *  @see Resize()
381         */
382        file_offset_t Chunk::Write(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
383            if (pFile->Mode != stream_mode_read_write)
384                throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
385            if (ullPos >= ullCurrentChunkSize || ullPos + WordCount * WordSize > ullCurrentChunkSize)
386                throw Exception("End of chunk reached while trying to write data");
387            if (!pFile->bEndianNative && WordSize != 1) {
388                switch (WordSize) {
389                    case 2:
390                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
391                            swapBytes_16((uint16_t*) pData + iWord);
392                        break;
393                    case 4:
394                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
395                            swapBytes_32((uint32_t*) pData + iWord);
396                        break;
397                    case 8:
398                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
399                            swapBytes_64((uint64_t*) pData + iWord);
400                        break;
401                    default:
402                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
403                            swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
404                        break;
405                }
406            }
407            #if POSIX
408            if (lseek(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET) < 0) {
409                throw Exception("Could not seek to position " + ToString(ullPos) +
410                                " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
411            }
412            ssize_t writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
413            if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
414            writtenWords /= WordSize;
415            #elif defined(WIN32)
416            if (!SetFilePointerEx(pFile->hFileWrite, ullStartPos + ullPos, NULL/*new pos pointer*/, FILE_BEGIN)) {
417                throw Exception("Could not seek to position " + ToString(ullPos) +
418                                " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
419            }
420            DWORD writtenWords;
421            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL); //FIXME: does not work for writing buffers larger than 2GB (even though this should rarely be the case in practice)
422            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
423            writtenWords /= WordSize;
424            #else // standard C functions
425            if (fseeko(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET)) {
426                throw Exception("Could not seek to position " + ToString(ullPos) +
427                                " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
428            }
429            file_offset_t writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
430            #endif // POSIX
431            SetPos(writtenWords * WordSize, stream_curpos);
432            return writtenWords;
433        }
434    
435      /** 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. */
436      unsigned long Chunk::ReadSceptical(void* pData, unsigned long WordCount, unsigned long WordSize) {      file_offset_t Chunk::ReadSceptical(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
437          unsigned long readWords = Read(pData, WordCount, WordSize);          file_offset_t readWords = Read(pData, WordCount, WordSize);
438          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");
439          return readWords;          return readWords;
440      }      }
# Line 241  namespace RIFF { Line 450  namespace RIFF {
450       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
451       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
452       */       */
453      unsigned long Chunk::ReadInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt8(int8_t* pData, file_offset_t WordCount) {
454         #if DEBUG          #if DEBUG
455         std::cout << "Chunk::ReadInt8(int8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt8(int8_t*,file_offset_t)" << std::endl;
456         #endif // DEBUG          #endif // DEBUG
457          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
458      }      }
459    
460      /**      /**
461         * Writes \a WordCount number of 8 Bit signed integer words from the
462         * buffer pointed by \a pData to the chunk's body, directly to the
463         * actual "physical" file. The position within the chunk will
464         * automatically be incremented. Note: you cannot write beyond the
465         * boundaries of the chunk, to append data to the chunk call Resize()
466         * before.
467         *
468         * @param pData             source buffer (containing the data)
469         * @param WordCount         number of 8 Bit signed integers to write
470         * @returns                 number of written integers
471         * @throws RIFF::Exception  if an IO error occured
472         * @see Resize()
473         */
474        file_offset_t Chunk::WriteInt8(int8_t* pData, file_offset_t WordCount) {
475            return Write(pData, WordCount, 1);
476        }
477    
478        /**
479       * Reads \a WordCount number of 8 Bit unsigned integer words and copies       * Reads \a WordCount number of 8 Bit unsigned integer words and copies
480       * 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
481       * allocated. The position within the chunk will automatically be       * allocated. The position within the chunk will automatically be
# Line 260  namespace RIFF { Line 487  namespace RIFF {
487       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
488       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
489       */       */
490      unsigned long Chunk::ReadUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint8(uint8_t* pData, file_offset_t WordCount) {
491         #if DEBUG          #if DEBUG
492         std::cout << "Chunk::ReadUint8(uint8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint8(uint8_t*,file_offset_t)" << std::endl;
493         #endif // DEBUG          #endif // DEBUG
494          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
495      }      }
496    
497      /**      /**
498         * Writes \a WordCount number of 8 Bit unsigned integer words from the
499         * buffer pointed by \a pData to the chunk's body, directly to the
500         * actual "physical" file. The position within the chunk will
501         * automatically be incremented. Note: you cannot write beyond the
502         * boundaries of the chunk, to append data to the chunk call Resize()
503         * before.
504         *
505         * @param pData             source buffer (containing the data)
506         * @param WordCount         number of 8 Bit unsigned integers to write
507         * @returns                 number of written integers
508         * @throws RIFF::Exception  if an IO error occured
509         * @see Resize()
510         */
511        file_offset_t Chunk::WriteUint8(uint8_t* pData, file_offset_t WordCount) {
512            return Write(pData, WordCount, 1);
513        }
514    
515        /**
516       * Reads \a WordCount number of 16 Bit signed integer words and copies       * Reads \a WordCount number of 16 Bit signed integer words and copies
517       * 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
518       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 279  namespace RIFF { Line 524  namespace RIFF {
524       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
525       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
526       */       */
527      unsigned long Chunk::ReadInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt16(int16_t* pData, file_offset_t WordCount) {
528        #if DEBUG          #if DEBUG
529        std::cout << "Chunk::ReadInt16(int16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt16(int16_t*,file_offset_t)" << std::endl;
530        #endif // DEBUG          #endif // DEBUG
531          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
532      }      }
533    
534      /**      /**
535         * Writes \a WordCount number of 16 Bit signed integer words from the
536         * buffer pointed by \a pData to the chunk's body, directly to the
537         * actual "physical" file. The position within the chunk will
538         * automatically be incremented. Note: you cannot write beyond the
539         * boundaries of the chunk, to append data to the chunk call Resize()
540         * before.
541         *
542         * @param pData             source buffer (containing the data)
543         * @param WordCount         number of 16 Bit signed integers to write
544         * @returns                 number of written integers
545         * @throws RIFF::Exception  if an IO error occured
546         * @see Resize()
547         */
548        file_offset_t Chunk::WriteInt16(int16_t* pData, file_offset_t WordCount) {
549            return Write(pData, WordCount, 2);
550        }
551    
552        /**
553       * Reads \a WordCount number of 16 Bit unsigned integer words and copies       * Reads \a WordCount number of 16 Bit unsigned integer words and copies
554       * 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
555       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 298  namespace RIFF { Line 561  namespace RIFF {
561       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
562       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
563       */       */
564      unsigned long Chunk::ReadUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint16(uint16_t* pData, file_offset_t WordCount) {
565        #if DEBUG          #if DEBUG
566        std::cout << "Chunk::ReadUint16(uint16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint16(uint16_t*,file_offset_t)" << std::endl;
567        #endif // DEBUG          #endif // DEBUG
568          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
569      }      }
570    
571      /**      /**
572         * Writes \a WordCount number of 16 Bit unsigned integer words from the
573         * buffer pointed by \a pData to the chunk's body, directly to the
574         * actual "physical" file. The position within the chunk will
575         * automatically be incremented. Note: you cannot write beyond the
576         * boundaries of the chunk, to append data to the chunk call Resize()
577         * before.
578         *
579         * @param pData             source buffer (containing the data)
580         * @param WordCount         number of 16 Bit unsigned integers to write
581         * @returns                 number of written integers
582         * @throws RIFF::Exception  if an IO error occured
583         * @see Resize()
584         */
585        file_offset_t Chunk::WriteUint16(uint16_t* pData, file_offset_t WordCount) {
586            return Write(pData, WordCount, 2);
587        }
588    
589        /**
590       * Reads \a WordCount number of 32 Bit signed integer words and copies       * Reads \a WordCount number of 32 Bit signed integer words and copies
591       * 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
592       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 317  namespace RIFF { Line 598  namespace RIFF {
598       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
599       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
600       */       */
601      unsigned long Chunk::ReadInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt32(int32_t* pData, file_offset_t WordCount) {
602         #if DEBUG          #if DEBUG
603         std::cout << "Chunk::ReadInt32(int32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt32(int32_t*,file_offset_t)" << std::endl;
604         #endif // DEBUG          #endif // DEBUG
605          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
606      }      }
607    
608      /**      /**
609         * Writes \a WordCount number of 32 Bit signed integer words from the
610         * buffer pointed by \a pData to the chunk's body, directly to the
611         * actual "physical" file. The position within the chunk will
612         * automatically be incremented. Note: you cannot write beyond the
613         * boundaries of the chunk, to append data to the chunk call Resize()
614         * before.
615         *
616         * @param pData             source buffer (containing the data)
617         * @param WordCount         number of 32 Bit signed integers to write
618         * @returns                 number of written integers
619         * @throws RIFF::Exception  if an IO error occured
620         * @see Resize()
621         */
622        file_offset_t Chunk::WriteInt32(int32_t* pData, file_offset_t WordCount) {
623            return Write(pData, WordCount, 4);
624        }
625    
626        /**
627       * Reads \a WordCount number of 32 Bit unsigned integer words and copies       * Reads \a WordCount number of 32 Bit unsigned integer words and copies
628       * 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
629       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 336  namespace RIFF { Line 635  namespace RIFF {
635       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
636       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
637       */       */
638      unsigned long Chunk::ReadUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint32(uint32_t* pData, file_offset_t WordCount) {
639         #if DEBUG          #if DEBUG
640         std::cout << "Chunk::ReadUint32(uint32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint32(uint32_t*,file_offset_t)" << std::endl;
641         #endif // DEBUG          #endif // DEBUG
642          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
643      }      }
644    
645      /**      /**
646         * Reads a null-padded string of size characters and copies it
647         * into the string \a s. The position within the chunk will
648         * automatically be incremented.
649         *
650         * @param s                 destination string
651         * @param size              number of characters to read
652         * @throws RIFF::Exception  if an error occured or less than
653         *                          \a size characters could be read!
654         */
655        void Chunk::ReadString(String& s, int size) {
656            char* buf = new char[size];
657            ReadSceptical(buf, 1, size);
658            s.assign(buf, std::find(buf, buf + size, '\0'));
659            delete[] buf;
660        }
661    
662        /**
663         * Writes \a WordCount number of 32 Bit unsigned integer words from the
664         * buffer pointed by \a pData to the chunk's body, directly to the
665         * actual "physical" file. The position within the chunk will
666         * automatically be incremented. Note: you cannot write beyond the
667         * boundaries of the chunk, to append data to the chunk call Resize()
668         * before.
669         *
670         * @param pData             source buffer (containing the data)
671         * @param WordCount         number of 32 Bit unsigned integers to write
672         * @returns                 number of written integers
673         * @throws RIFF::Exception  if an IO error occured
674         * @see Resize()
675         */
676        file_offset_t Chunk::WriteUint32(uint32_t* pData, file_offset_t WordCount) {
677            return Write(pData, WordCount, 4);
678        }
679    
680        /**
681       * Reads one 8 Bit signed integer word and increments the position within       * Reads one 8 Bit signed integer word and increments the position within
682       * the chunk.       * the chunk.
683       *       *
# Line 351  namespace RIFF { Line 685  namespace RIFF {
685       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
686       */       */
687      int8_t Chunk::ReadInt8() {      int8_t Chunk::ReadInt8() {
688        #if DEBUG          #if DEBUG
689        std::cout << "Chunk::ReadInt8()" << std::endl;          std::cout << "Chunk::ReadInt8()" << std::endl;
690        #endif // DEBUG          #endif // DEBUG
691          int8_t word;          int8_t word;
692          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
693          return word;          return word;
# Line 367  namespace RIFF { Line 701  namespace RIFF {
701       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
702       */       */
703      uint8_t Chunk::ReadUint8() {      uint8_t Chunk::ReadUint8() {
704        #if DEBUG          #if DEBUG
705        std::cout << "Chunk::ReadUint8()" << std::endl;          std::cout << "Chunk::ReadUint8()" << std::endl;
706        #endif // DEBUG          #endif // DEBUG
707          uint8_t word;          uint8_t word;
708          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
709          return word;          return word;
# Line 384  namespace RIFF { Line 718  namespace RIFF {
718       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
719       */       */
720      int16_t Chunk::ReadInt16() {      int16_t Chunk::ReadInt16() {
721        #if DEBUG          #if DEBUG
722        std::cout << "Chunk::ReadInt16()" << std::endl;          std::cout << "Chunk::ReadInt16()" << std::endl;
723        #endif // DEBUG          #endif // DEBUG
724          int16_t word;          int16_t word;
725          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
726          return word;          return word;
# Line 401  namespace RIFF { Line 735  namespace RIFF {
735       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
736       */       */
737      uint16_t Chunk::ReadUint16() {      uint16_t Chunk::ReadUint16() {
738        #if DEBUG          #if DEBUG
739        std::cout << "Chunk::ReadUint16()" << std::endl;          std::cout << "Chunk::ReadUint16()" << std::endl;
740        #endif // DEBUG          #endif // DEBUG
741          uint16_t word;          uint16_t word;
742          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
743          return word;          return word;
# Line 418  namespace RIFF { Line 752  namespace RIFF {
752       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
753       */       */
754      int32_t Chunk::ReadInt32() {      int32_t Chunk::ReadInt32() {
755        #if DEBUG          #if DEBUG
756        std::cout << "Chunk::ReadInt32()" << std::endl;          std::cout << "Chunk::ReadInt32()" << std::endl;
757        #endif // DEBUG          #endif // DEBUG
758          int32_t word;          int32_t word;
759          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
760          return word;          return word;
# Line 435  namespace RIFF { Line 769  namespace RIFF {
769       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
770       */       */
771      uint32_t Chunk::ReadUint32() {      uint32_t Chunk::ReadUint32() {
772        #if DEBUG          #if DEBUG
773        std::cout << "Chunk::ReadUint32()" << std::endl;          std::cout << "Chunk::ReadUint32()" << std::endl;
774        #endif // DEBUG          #endif // DEBUG
775          uint32_t word;          uint32_t word;
776          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
777          return word;          return word;
778      }      }
779    
780        /** @brief Load chunk body into RAM.
781         *
782         * Loads the whole chunk body into memory. You can modify the data in
783         * RAM and save the data by calling File::Save() afterwards.
784         *
785         * <b>Caution:</b> the buffer pointer will be invalidated once
786         * File::Save() was called. You have to call LoadChunkData() again to
787         * get a new, valid pointer whenever File::Save() was called.
788         *
789         * You can call LoadChunkData() again if you previously scheduled to
790         * enlarge this chunk with a Resize() call. In that case the buffer will
791         * be enlarged to the new, scheduled chunk size and you can already
792         * place the new chunk data to the buffer and finally call File::Save()
793         * to enlarge the chunk physically and write the new data in one rush.
794         * This approach is definitely recommended if you have to enlarge and
795         * write new data to a lot of chunks.
796         *
797         * @returns a pointer to the data in RAM on success, NULL otherwise
798         * @throws Exception if data buffer could not be enlarged
799         * @see ReleaseChunkData()
800         */
801      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
802          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
803              #if POSIX              #if POSIX
804              if (lseek(hFile, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ullStartPos, SEEK_SET) == -1) return NULL;
805              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
806              if (!pChunkData) return NULL;              if (!SetFilePointerEx(pFile->hFileRead, ullStartPos, NULL/*new pos pointer*/, FILE_BEGIN)) return NULL;
             unsigned long readWords = read(hFile, pChunkData, GetSize());  
807              #else              #else
808              if (fseek(hFile, ulStartPos, SEEK_SET)) return NULL;              if (fseeko(pFile->hFileRead, ullStartPos, SEEK_SET)) return NULL;
809              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
810                file_offset_t ullBufferSize = (ullCurrentChunkSize > ullNewChunkSize) ? ullCurrentChunkSize : ullNewChunkSize;
811                pChunkData = new uint8_t[ullBufferSize];
812              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
813              unsigned long readWords = fread(pChunkData, 1, GetSize(), hFile);              memset(pChunkData, 0, ullBufferSize);
814                #if POSIX
815                file_offset_t readWords = read(pFile->hFileRead, pChunkData, GetSize());
816                #elif defined(WIN32)
817                DWORD readWords;
818                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL); //FIXME: won't load chunks larger than 2GB !
819                #else
820                file_offset_t readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
821              #endif // POSIX              #endif // POSIX
822              if (readWords != GetSize()) {              if (readWords != GetSize()) {
823                  delete[] pChunkData;                  delete[] pChunkData;
824                  return (pChunkData = NULL);                  return (pChunkData = NULL);
825              }              }
826                ullChunkDataSize = ullBufferSize;
827            } else if (ullNewChunkSize > ullChunkDataSize) {
828                uint8_t* pNewBuffer = new uint8_t[ullNewChunkSize];
829                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(ullNewChunkSize) + " bytes");
830                memset(pNewBuffer, 0 , ullNewChunkSize);
831                memcpy(pNewBuffer, pChunkData, ullChunkDataSize);
832                delete[] pChunkData;
833                pChunkData       = pNewBuffer;
834                ullChunkDataSize = ullNewChunkSize;
835          }          }
836          return pChunkData;          return pChunkData;
837      }      }
838    
839        /** @brief Free loaded chunk body from RAM.
840         *
841         * Frees loaded chunk body data from memory (RAM). You should call
842         * File::Save() before calling this method if you modified the data to
843         * make the changes persistent.
844         */
845      void Chunk::ReleaseChunkData() {      void Chunk::ReleaseChunkData() {
846          if (pChunkData) {          if (pChunkData) {
847              delete[] pChunkData;              delete[] pChunkData;
# Line 471  namespace RIFF { Line 849  namespace RIFF {
849          }          }
850      }      }
851    
852        /** @brief Resize chunk.
853         *
854         * Resizes this chunk's body, that is the actual size of data possible
855         * to be written to this chunk. This call will return immediately and
856         * just schedule the resize operation. You should call File::Save() to
857         * actually perform the resize operation(s) "physically" to the file.
858         * As this can take a while on large files, it is recommended to call
859         * Resize() first on all chunks which have to be resized and finally to
860         * call File::Save() to perform all those resize operations in one rush.
861         *
862         * <b>Caution:</b> You cannot directly write to enlarged chunks before
863         * calling File::Save() as this might exceed the current chunk's body
864         * boundary!
865         *
866         * @param NewSize - new chunk body size in bytes (must be greater than zero)
867         * @throws RIFF::Exception  if \a NewSize is less than 1 or Unrealistic large
868         * @see File::Save()
869         */
870        void Chunk::Resize(file_offset_t NewSize) {
871            if (NewSize == 0)
872                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
873            if ((NewSize >> 48) != 0)
874                throw Exception("Unrealistic high chunk size detected: " + __resolveChunkPath(this));
875            if (ullNewChunkSize == NewSize) return;
876            ullNewChunkSize = NewSize;
877        }
878    
879        /** @brief Write chunk persistently e.g. to disk.
880         *
881         * Stores the chunk persistently to its actual "physical" file.
882         *
883         * @param ullWritePos - position within the "physical" file where this
884         *                     chunk should be written to
885         * @param ullCurrentDataOffset - offset of current (old) data within
886         *                              the file
887         * @param pProgress - optional: callback function for progress notification
888         * @returns new write position in the "physical" file, that is
889         *          \a ullWritePos incremented by this chunk's new size
890         *          (including its header size of course)
891         */
892        file_offset_t Chunk::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
893            const file_offset_t ullOriginalPos = ullWritePos;
894            ullWritePos += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
895    
896            if (pFile->Mode != stream_mode_read_write)
897                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
898    
899            // if the whole chunk body was loaded into RAM
900            if (pChunkData) {
901                // make sure chunk data buffer in RAM is at least as large as the new chunk size
902                LoadChunkData();
903                // write chunk data from RAM persistently to the file
904                #if POSIX
905                lseek(pFile->hFileWrite, ullWritePos, SEEK_SET);
906                if (write(pFile->hFileWrite, pChunkData, ullNewChunkSize) != ullNewChunkSize) {
907                    throw Exception("Writing Chunk data (from RAM) failed");
908                }
909                #elif defined(WIN32)
910                SetFilePointerEx(pFile->hFileWrite, ullWritePos, NULL/*new pos pointer*/, FILE_BEGIN);
911                DWORD dwBytesWritten;
912                WriteFile(pFile->hFileWrite, pChunkData, ullNewChunkSize, &dwBytesWritten, NULL); //FIXME: won't save chunks larger than 2GB !
913                if (dwBytesWritten != ullNewChunkSize) {
914                    throw Exception("Writing Chunk data (from RAM) failed");
915                }
916                #else
917                fseeko(pFile->hFileWrite, ullWritePos, SEEK_SET);
918                if (fwrite(pChunkData, 1, ullNewChunkSize, pFile->hFileWrite) != ullNewChunkSize) {
919                    throw Exception("Writing Chunk data (from RAM) failed");
920                }
921                #endif // POSIX
922            } else {
923                // move chunk data from the end of the file to the appropriate position
924                int8_t* pCopyBuffer = new int8_t[4096];
925                file_offset_t ullToMove = (ullNewChunkSize < ullCurrentChunkSize) ? ullNewChunkSize : ullCurrentChunkSize;
926                #if defined(WIN32)
927                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
928                #else
929                int iBytesMoved = 1;
930                #endif
931                for (file_offset_t ullOffset = 0; ullToMove > 0 && iBytesMoved > 0; ullOffset += iBytesMoved, ullToMove -= iBytesMoved) {
932                    iBytesMoved = (ullToMove < 4096) ? ullToMove : 4096;
933                    #if POSIX
934                    lseek(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
935                    iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
936                    lseek(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
937                    iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
938                    #elif defined(WIN32)
939                    SetFilePointerEx(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, NULL/*new pos pointer*/, FILE_BEGIN);
940                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
941                    SetFilePointerEx(pFile->hFileWrite, ullWritePos + ullOffset, NULL/*new pos pointer*/, FILE_BEGIN);
942                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
943                    #else
944                    fseeko(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
945                    iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
946                    fseeko(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
947                    iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
948                    #endif
949                }
950                delete[] pCopyBuffer;
951                if (iBytesMoved < 0) throw Exception("Writing Chunk data (from file) failed");
952            }
953    
954            // update this chunk's header
955            ullCurrentChunkSize = ullNewChunkSize;
956            WriteHeader(ullOriginalPos);
957    
958            __notify_progress(pProgress, 1.0); // notify done
959    
960            // update chunk's position pointers
961            ullStartPos = ullOriginalPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
962            ullPos      = 0;
963    
964            // add pad byte if needed
965            if ((ullStartPos + ullNewChunkSize) % 2 != 0) {
966                const char cPadByte = 0;
967                #if POSIX
968                lseek(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
969                write(pFile->hFileWrite, &cPadByte, 1);
970                #elif defined(WIN32)
971                SetFilePointerEx(pFile->hFileWrite, ullStartPos + ullNewChunkSize, NULL/*new pos pointer*/, FILE_BEGIN);
972                DWORD dwBytesWritten;
973                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
974                #else
975                fseeko(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
976                fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
977                #endif
978                return ullStartPos + ullNewChunkSize + 1;
979            }
980    
981            return ullStartPos + ullNewChunkSize;
982        }
983    
984        void Chunk::__resetPos() {
985            ullPos = 0;
986        }
987    
988    
989    
990  // *************** List ***************  // *************** List ***************
991  // *  // *
992    
993      List::List() : Chunk() {      List::List(File* pFile) : Chunk(pFile) {
994        #if DEBUG          #if DEBUG
995        std::cout << "List::List()" << std::endl;          std::cout << "List::List(File* pFile)" << std::endl;
996        #endif // DEBUG          #endif // DEBUG
997          pSubChunks    = NULL;          pSubChunks    = NULL;
998          pSubChunksMap = NULL;          pSubChunksMap = NULL;
999      }      }
1000    
1001      #if POSIX      List::List(File* pFile, file_offset_t StartPos, List* Parent)
1002      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) {  
1003          #if DEBUG          #if DEBUG
1004          std::cout << "List::List(FILE*,ulong,bool,List*)" << std::endl;          std::cout << "List::List(File*,file_offset_t,List*)" << std::endl;
1005          #endif // DEBUG          #endif // DEBUG
1006          pSubChunks    = NULL;          pSubChunks    = NULL;
1007          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1008          ReadHeader(StartPos);          ReadHeader(StartPos);
1009          ulStartPos    = StartPos + LIST_HEADER_SIZE;          ullStartPos = StartPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1010        }
1011    
1012        List::List(File* pFile, List* pParent, uint32_t uiListID)
1013          : Chunk(pFile, pParent, CHUNK_ID_LIST, 0) {
1014            pSubChunks    = NULL;
1015            pSubChunksMap = NULL;
1016            ListType      = uiListID;
1017      }      }
1018    
1019      List::~List() {      List::~List() {
1020        #if DEBUG          #if DEBUG
1021        std::cout << "List::~List()" << std::endl;          std::cout << "List::~List()" << std::endl;
1022        #endif // DEBUG          #endif // DEBUG
1023            DeleteChunkList();
1024        }
1025    
1026        void List::DeleteChunkList() {
1027          if (pSubChunks) {          if (pSubChunks) {
1028              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
1029              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 511  namespace RIFF { Line 1032  namespace RIFF {
1032                  iter++;                  iter++;
1033              }              }
1034              delete pSubChunks;              delete pSubChunks;
1035                pSubChunks = NULL;
1036            }
1037            if (pSubChunksMap) {
1038                delete pSubChunksMap;
1039                pSubChunksMap = NULL;
1040          }          }
         if (pSubChunksMap) delete pSubChunksMap;  
1041      }      }
1042    
1043      /**      /**
# Line 527  namespace RIFF { Line 1052  namespace RIFF {
1052       *                   that ID       *                   that ID
1053       */       */
1054      Chunk* List::GetSubChunk(uint32_t ChunkID) {      Chunk* List::GetSubChunk(uint32_t ChunkID) {
1055        #if DEBUG          #if DEBUG
1056        std::cout << "List::GetSubChunk(uint32_t)" << std::endl;          std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
1057        #endif // DEBUG          #endif // DEBUG
1058          if (!pSubChunksMap) LoadSubChunks();          if (!pSubChunksMap) LoadSubChunks();
1059          return (*pSubChunksMap)[ChunkID];          return (*pSubChunksMap)[ChunkID];
1060      }      }
# Line 693  namespace RIFF { Line 1218  namespace RIFF {
1218          return result;          return result;
1219      }      }
1220    
1221      void List::ReadHeader(unsigned long fPos) {      /** @brief Creates a new sub chunk.
1222        #if DEBUG       *
1223        std::cout << "List::Readheader(ulong) ";       * Creates and adds a new sub chunk to this list chunk. Note that the
1224        #endif // DEBUG       * chunk's body size given by \a ullBodySize must be greater than zero.
1225          Chunk::ReadHeader(fPos);       * You have to call File::Save() to make this change persistent to the
1226          ChunkSize -= 4;       * actual file and <b>before</b> performing any data write operations
1227         * on the new chunk!
1228         *
1229         * @param uiChunkID  - chunk ID of the new chunk
1230         * @param ullBodySize - size of the new chunk's body, that is its actual
1231         *                      data size (without header)
1232         * @throws RIFF::Exception if \a ullBodySize equals zero
1233         */
1234        Chunk* List::AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize) {
1235            if (ullBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1236            if (!pSubChunks) LoadSubChunks();
1237            Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1238            pSubChunks->push_back(pNewChunk);
1239            (*pSubChunksMap)[uiChunkID] = pNewChunk;
1240            pNewChunk->Resize(ullBodySize);
1241            ullNewChunkSize += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1242            return pNewChunk;
1243        }
1244    
1245        /** @brief Moves a sub chunk witin this list.
1246         *
1247         * Moves a sub chunk from one position in this list to another
1248         * position in the same list. The pSrc chunk is placed before the
1249         * pDst chunk.
1250         *
1251         * @param pSrc - sub chunk to be moved
1252         * @param pDst - the position to move to. pSrc will be placed
1253         *               before pDst. If pDst is 0, pSrc will be placed
1254         *               last in list.
1255         */
1256        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1257            if (!pSubChunks) LoadSubChunks();
1258            pSubChunks->remove(pSrc);
1259            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1260            pSubChunks->insert(iter, pSrc);
1261        }
1262    
1263        /** @brief Moves a sub chunk from this list to another list.
1264         *
1265         * Moves a sub chunk from this list list to the end of another
1266         * list.
1267         *
1268         * @param pSrc - sub chunk to be moved
1269         * @param pDst - destination list where the chunk shall be moved to
1270         */
1271        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1272            if (pNewParent == this || !pNewParent) return;
1273            if (!pSubChunks) LoadSubChunks();
1274            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1275            pSubChunks->remove(pSrc);
1276            pNewParent->pSubChunks->push_back(pSrc);
1277            // update chunk id map of this List
1278            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1279                pSubChunksMap->erase(pSrc->GetChunkID());
1280                // try to find another chunk of the same chunk ID
1281                ChunkList::iterator iter = pSubChunks->begin();
1282                ChunkList::iterator end  = pSubChunks->end();
1283                for (; iter != end; ++iter) {
1284                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1285                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1286                        break; // we're done, stop search
1287                    }
1288                }
1289            }
1290            // update chunk id map of other list
1291            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1292                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1293        }
1294    
1295        /** @brief Creates a new list sub chunk.
1296         *
1297         * Creates and adds a new list sub chunk to this list chunk. Note that
1298         * you have to add sub chunks / sub list chunks to the new created chunk
1299         * <b>before</b> trying to make this change persisten to the actual
1300         * file with File::Save()!
1301         *
1302         * @param uiListType - list ID of the new list chunk
1303         */
1304        List* List::AddSubList(uint32_t uiListType) {
1305            if (!pSubChunks) LoadSubChunks();
1306            List* pNewListChunk = new List(pFile, this, uiListType);
1307            pSubChunks->push_back(pNewListChunk);
1308            (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1309            ullNewChunkSize += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1310            return pNewListChunk;
1311        }
1312    
1313        /** @brief Removes a sub chunk.
1314         *
1315         * Removes the sub chunk given by \a pSubChunk from this list and frees
1316         * it completely from RAM. The given chunk can either be a normal sub
1317         * chunk or a list sub chunk. In case the given chunk is a list chunk,
1318         * all its subchunks (if any) will be removed recursively as well. You
1319         * should call File::Save() to make this change persistent at any time.
1320         *
1321         * @param pSubChunk - sub chunk or sub list chunk to be removed
1322         */
1323        void List::DeleteSubChunk(Chunk* pSubChunk) {
1324            if (!pSubChunks) LoadSubChunks();
1325            pSubChunks->remove(pSubChunk);
1326            if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1327                pSubChunksMap->erase(pSubChunk->GetChunkID());
1328                // try to find another chunk of the same chunk ID
1329                ChunkList::iterator iter = pSubChunks->begin();
1330                ChunkList::iterator end  = pSubChunks->end();
1331                for (; iter != end; ++iter) {
1332                    if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1333                        (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1334                        break; // we're done, stop search
1335                    }
1336                }
1337            }
1338            delete pSubChunk;
1339        }
1340    
1341        /**
1342         *  Returns the actual total size in bytes (including List chunk header and
1343         *  all subchunks) of this List Chunk if being stored to a file.
1344         *
1345         *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
1346         *                          being saved to a file
1347         */
1348        file_offset_t List::RequiredPhysicalSize(int fileOffsetSize) {
1349            if (!pSubChunks) LoadSubChunks();
1350            file_offset_t size = LIST_HEADER_SIZE(fileOffsetSize);
1351            ChunkList::iterator iter = pSubChunks->begin();
1352            ChunkList::iterator end  = pSubChunks->end();
1353            for (; iter != end; ++iter)
1354                size += (*iter)->RequiredPhysicalSize(fileOffsetSize);
1355            return size;
1356        }
1357    
1358        void List::ReadHeader(file_offset_t filePos) {
1359            #if DEBUG
1360            std::cout << "List::Readheader(file_offset_t) ";
1361            #endif // DEBUG
1362            Chunk::ReadHeader(filePos);
1363            if (ullCurrentChunkSize < 4) return;
1364            ullNewChunkSize = ullCurrentChunkSize -= 4;
1365          #if POSIX          #if POSIX
1366          lseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1367          read(hFile, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1368            #elif defined(WIN32)
1369            SetFilePointerEx(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), NULL/*new pos pointer*/, FILE_BEGIN);
1370            DWORD dwBytesRead;
1371            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1372          #else          #else
1373          fseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1374          fread(&ListType, 4, 1, hFile);          fread(&ListType, 4, 1, pFile->hFileRead);
1375          #endif // POSIX          #endif // POSIX
1376        #if DEBUG          #if DEBUG
1377        std::cout << "listType=" << convertToString(ListType) << std::endl;          std::cout << "listType=" << convertToString(ListType) << std::endl;
1378        #endif // DEBUG          #endif // DEBUG
1379          if (!bEndianNative) {          if (!pFile->bEndianNative) {
1380              //swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1381          }          }
1382      }      }
1383    
1384      void List::LoadSubChunks() {      void List::WriteHeader(file_offset_t filePos) {
1385         #if DEBUG          // the four list type bytes officially belong the chunk's body in the RIFF format
1386         std::cout << "List::LoadSubChunks()";          ullNewChunkSize += 4;
1387         #endif // DEBUG          Chunk::WriteHeader(filePos);
1388            ullNewChunkSize -= 4; // just revert the +4 incrementation
1389            #if POSIX
1390            lseek(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1391            write(pFile->hFileWrite, &ListType, 4);
1392            #elif defined(WIN32)
1393            SetFilePointerEx(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), NULL/*new pos pointer*/, FILE_BEGIN);
1394            DWORD dwBytesWritten;
1395            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1396            #else
1397            fseeko(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1398            fwrite(&ListType, 4, 1, pFile->hFileWrite);
1399            #endif // POSIX
1400        }
1401    
1402        void List::LoadSubChunks(progress_t* pProgress) {
1403            #if DEBUG
1404            std::cout << "List::LoadSubChunks()";
1405            #endif // DEBUG
1406          if (!pSubChunks) {          if (!pSubChunks) {
1407              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1408              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1409              unsigned long uiOriginalPos = GetPos();              #if defined(WIN32)
1410                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1411                #else
1412                if (!pFile->hFileRead) return;
1413                #endif
1414                file_offset_t ullOriginalPos = GetPos();
1415              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1416              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE(pFile->FileOffsetSize)) {
1417                  Chunk* ck;                  Chunk* ck;
1418                  uint32_t ckid;                  uint32_t ckid;
1419                  Read(&ckid, 4, 1);                  Read(&ckid, 4, 1);
1420         #if DEBUG                  #if DEBUG
1421         std::cout << " ckid=" << convertToString(ckid) << std::endl;                  std::cout << " ckid=" << convertToString(ckid) << std::endl;
1422         #endif // DEBUG                  #endif // DEBUG
1423                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1424                      ck = new RIFF::List(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::List(pFile, ullStartPos + ullPos - 4, this);
1425                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1426                  }                  }
1427                  else { // simple chunk                  else { // simple chunk
1428                      ck = new RIFF::Chunk(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::Chunk(pFile, ullStartPos + ullPos - 4, this);
1429                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1430                  }                  }
1431                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1432                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1433                  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
1434              }              }
1435              SetPos(uiOriginalPos); // restore position before this call              SetPos(ullOriginalPos); // restore position before this call
1436            }
1437            __notify_progress(pProgress, 1.0); // notify done
1438        }
1439    
1440        void List::LoadSubChunksRecursively(progress_t* pProgress) {
1441            const int n = CountSubLists();
1442            int i = 0;
1443            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList(), ++i) {
1444                // divide local progress into subprogress
1445                progress_t subprogress;
1446                __divide_progress(pProgress, &subprogress, n, i);
1447                // do the actual work
1448                pList->LoadSubChunksRecursively(&subprogress);
1449            }
1450            __notify_progress(pProgress, 1.0); // notify done
1451        }
1452    
1453        /** @brief Write list chunk persistently e.g. to disk.
1454         *
1455         * Stores the list chunk persistently to its actual "physical" file. All
1456         * subchunks (including sub list chunks) will be stored recursively as
1457         * well.
1458         *
1459         * @param ullWritePos - position within the "physical" file where this
1460         *                     list chunk should be written to
1461         * @param ullCurrentDataOffset - offset of current (old) data within
1462         *                              the file
1463         * @param pProgress - optional: callback function for progress notification
1464         * @returns new write position in the "physical" file, that is
1465         *          \a ullWritePos incremented by this list chunk's new size
1466         *          (including its header size of course)
1467         */
1468        file_offset_t List::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
1469            const file_offset_t ullOriginalPos = ullWritePos;
1470            ullWritePos += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1471    
1472            if (pFile->Mode != stream_mode_read_write)
1473                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1474    
1475            // write all subchunks (including sub list chunks) recursively
1476            if (pSubChunks) {
1477                int i = 0;
1478                const int n = pSubChunks->size();
1479                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1480                    // divide local progress into subprogress for loading current Instrument
1481                    progress_t subprogress;
1482                    __divide_progress(pProgress, &subprogress, n, i);
1483                    // do the actual work
1484                    ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, &subprogress);
1485                }
1486            }
1487    
1488            // update this list chunk's header
1489            ullCurrentChunkSize = ullNewChunkSize = ullWritePos - ullOriginalPos - LIST_HEADER_SIZE(pFile->FileOffsetSize);
1490            WriteHeader(ullOriginalPos);
1491    
1492            // offset of this list chunk in new written file may have changed
1493            ullStartPos = ullOriginalPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1494    
1495             __notify_progress(pProgress, 1.0); // notify done
1496    
1497            return ullWritePos;
1498        }
1499    
1500        void List::__resetPos() {
1501            Chunk::__resetPos();
1502            if (pSubChunks) {
1503                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1504                    (*iter)->__resetPos();
1505                }
1506          }          }
1507      }      }
1508    
1509      /**      /**
1510       *  Returns string representation of the lists's id       *  Returns string representation of the lists's id
1511       */       */
1512      String List::GetListTypeString() {      String List::GetListTypeString() const {
1513          return convertToString(ListType);          return convertToString(ListType);
1514      }      }
1515    
# Line 758  namespace RIFF { Line 1518  namespace RIFF {
1518  // *************** File ***************  // *************** File ***************
1519  // *  // *
1520    
1521      File::File(const String& path) : List(), Filename(path) {      /** @brief Create new RIFF file.
1522        #if DEBUG       *
1523        std::cout << "File::File("<<path<<")" << std::endl;       * Use this constructor if you want to create a new RIFF file completely
1524        #endif // DEBUG       * "from scratch". Note: there must be no empty chunks or empty list
1525         * chunks when trying to make the new RIFF file persistent with Save()!
1526         *
1527         * Note: by default, the RIFF file will be saved in native endian
1528         * format; that is, as a RIFF file on little-endian machines and
1529         * as a RIFX file on big-endian. To change this behaviour, call
1530         * SetByteOrder() before calling Save().
1531         *
1532         * @param FileType - four-byte identifier of the RIFF file type
1533         * @see AddSubChunk(), AddSubList(), SetByteOrder()
1534         */
1535        File::File(uint32_t FileType)
1536            : List(this), bIsNewFile(true), Layout(layout_standard),
1537              FileOffsetPreference(offset_size_auto)
1538        {
1539            #if defined(WIN32)
1540            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1541            #else
1542            hFileRead = hFileWrite = 0;
1543            #endif
1544            Mode = stream_mode_closed;
1545          bEndianNative = true;          bEndianNative = true;
1546            ListType = FileType;
1547            FileOffsetSize = 4;
1548            ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1549        }
1550    
1551        /** @brief Load existing RIFF file.
1552         *
1553         * Loads an existing RIFF file with all its chunks.
1554         *
1555         * @param path - path and file name of the RIFF file to open
1556         * @throws RIFF::Exception if error occured while trying to load the
1557         *                         given RIFF file
1558         */
1559        File::File(const String& path)
1560            : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard),
1561              FileOffsetPreference(offset_size_auto)
1562        {
1563            #if DEBUG
1564            std::cout << "File::File("<<path<<")" << std::endl;
1565            #endif // DEBUG
1566            bEndianNative = true;
1567            FileOffsetSize = 4;
1568            try {
1569                __openExistingFile(path);
1570                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1571                    throw RIFF::Exception("Not a RIFF file");
1572                }
1573            }
1574            catch (...) {
1575                Cleanup();
1576                throw;
1577            }
1578        }
1579    
1580        /** @brief Load existing RIFF-like file.
1581         *
1582         * Loads an existing file, which is not a "real" RIFF file, but similar to
1583         * an ordinary RIFF file.
1584         *
1585         * A "real" RIFF file contains at top level a List chunk either with chunk
1586         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1587         * case, and if it finds the toplevel List chunk to have another chunk ID
1588         * than one of those two expected ones, it would throw an Exception and
1589         * would refuse to load the file accordingly.
1590         *
1591         * Since there are however a lot of file formats which use the same simple
1592         * principles of the RIFF format, with another toplevel List chunk ID
1593         * though, you can use this alternative constructor here to be able to load
1594         * and handle those files in the same way as you would do with "real" RIFF
1595         * files.
1596         *
1597         * @param path - path and file name of the RIFF-alike file to be opened
1598         * @param FileType - expected toplevel List chunk ID (this is the very
1599         *                   first chunk found in the file)
1600         * @param Endian - whether the file uses little endian or big endian layout
1601         * @param layout - general file structure type
1602         * @param fileOffsetSize - (optional) preference how to deal with large files
1603         * @throws RIFF::Exception if error occured while trying to load the
1604         *                         given RIFF-alike file
1605         */
1606        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout, offset_size_t fileOffsetSize)
1607            : List(this), Filename(path), bIsNewFile(false), Layout(layout),
1608              FileOffsetPreference(fileOffsetSize)
1609        {
1610            SetByteOrder(Endian);
1611            if (fileOffsetSize < offset_size_auto || fileOffsetSize > offset_size_64bit)
1612                throw Exception("Invalid RIFF::offset_size_t");
1613            FileOffsetSize = 4;
1614            try {
1615                __openExistingFile(path, &FileType);
1616            }
1617            catch (...) {
1618                Cleanup();
1619                throw;
1620            }
1621        }
1622    
1623        /**
1624         * Opens an already existing RIFF file or RIFF-alike file. This method
1625         * shall only be called once (in a File class constructor).
1626         *
1627         * @param path - path and file name of the RIFF file or RIFF-alike file to
1628         *               be opened
1629         * @param FileType - (optional) expected chunk ID of first chunk in file
1630         * @throws RIFF::Exception if error occured while trying to load the
1631         *                         given RIFF file or RIFF-alike file
1632         */
1633        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1634          #if POSIX          #if POSIX
1635          hFile = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1636          if (hFile <= 0) {          if (hFileRead == -1) {
1637              hFile = 0;              hFileRead = hFileWrite = 0;
1638                String sError = strerror(errno);
1639                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1640            }
1641            #elif defined(WIN32)
1642            hFileRead = hFileWrite = CreateFile(
1643                                         path.c_str(), GENERIC_READ,
1644                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1645                                         NULL, OPEN_EXISTING,
1646                                         FILE_ATTRIBUTE_NORMAL |
1647                                         FILE_FLAG_RANDOM_ACCESS, NULL
1648                                     );
1649            if (hFileRead == INVALID_HANDLE_VALUE) {
1650                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1651              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1652          }          }
1653          #else          #else
1654          hFile = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1655          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1656          #endif // POSIX          #endif // POSIX
1657          ulStartPos = RIFF_HEADER_SIZE;          Mode = stream_mode_read;
1658          ReadHeader(0);  
1659          if (ChunkID != CHUNK_ID_RIFF) {          // determine RIFF file offset size to be used (in RIFF chunk headers)
1660              throw RIFF::Exception("Not a RIFF file");          // according to the current file offset preference
1661            FileOffsetSize = FileOffsetSizeFor(GetCurrentFileSize());
1662    
1663            switch (Layout) {
1664                case layout_standard: // this is a normal RIFF file
1665                    ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1666                    ReadHeader(0);
1667                    if (FileType && ChunkID != *FileType)
1668                        throw RIFF::Exception("Invalid file container ID");
1669                    break;
1670                case layout_flat: // non-standard RIFF-alike file
1671                    ullStartPos = 0;
1672                    ullNewChunkSize = ullCurrentChunkSize = GetCurrentFileSize();
1673                    if (FileType) {
1674                        uint32_t ckid;
1675                        if (Read(&ckid, 4, 1) != 4) {
1676                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1677                        } else if (ckid != *FileType) {
1678                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1679                            throw RIFF::Exception("Invalid file header ID" + s);
1680                        }
1681                        SetPos(0); // reset to first byte of file
1682                    }
1683                    LoadSubChunks();
1684                    break;
1685          }          }
1686      }      }
1687    
1688      File::~File() {      String File::GetFileName() const {
1689         #if DEBUG          return Filename;
1690         std::cout << "File::~File()" << std::endl;      }
1691         #endif // DEBUG      
1692        void File::SetFileName(const String& path) {
1693            Filename = path;
1694        }
1695    
1696        stream_mode_t File::GetMode() const {
1697            return Mode;
1698        }
1699    
1700        layout_t File::GetLayout() const {
1701            return Layout;
1702        }
1703    
1704        /** @brief Change file access mode.
1705         *
1706         * Changes files access mode either to read-only mode or to read/write
1707         * mode.
1708         *
1709         * @param NewMode - new file access mode
1710         * @returns true if mode was changed, false if current mode already
1711         *          equals new mode
1712         * @throws RIFF::Exception if new file access mode is unknown
1713         */
1714        bool File::SetMode(stream_mode_t NewMode) {
1715            if (NewMode != Mode) {
1716                switch (NewMode) {
1717                    case stream_mode_read:
1718                        #if POSIX
1719                        if (hFileRead) close(hFileRead);
1720                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1721                        if (hFileRead == -1) {
1722                            hFileRead = hFileWrite = 0;
1723                            String sError = strerror(errno);
1724                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1725                        }
1726                        #elif defined(WIN32)
1727                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1728                        hFileRead = hFileWrite = CreateFile(
1729                                                     Filename.c_str(), GENERIC_READ,
1730                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1731                                                     NULL, OPEN_EXISTING,
1732                                                     FILE_ATTRIBUTE_NORMAL |
1733                                                     FILE_FLAG_RANDOM_ACCESS,
1734                                                     NULL
1735                                                 );
1736                        if (hFileRead == INVALID_HANDLE_VALUE) {
1737                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1738                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1739                        }
1740                        #else
1741                        if (hFileRead) fclose(hFileRead);
1742                        hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1743                        if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1744                        #endif
1745                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1746                        break;
1747                    case stream_mode_read_write:
1748                        #if POSIX
1749                        if (hFileRead) close(hFileRead);
1750                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1751                        if (hFileRead == -1) {
1752                            hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1753                            String sError = strerror(errno);
1754                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1755                        }
1756                        #elif defined(WIN32)
1757                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1758                        hFileRead = hFileWrite = CreateFile(
1759                                                     Filename.c_str(),
1760                                                     GENERIC_READ | GENERIC_WRITE,
1761                                                     FILE_SHARE_READ,
1762                                                     NULL, OPEN_ALWAYS,
1763                                                     FILE_ATTRIBUTE_NORMAL |
1764                                                     FILE_FLAG_RANDOM_ACCESS,
1765                                                     NULL
1766                                                 );
1767                        if (hFileRead == INVALID_HANDLE_VALUE) {
1768                            hFileRead = hFileWrite = CreateFile(
1769                                                         Filename.c_str(), GENERIC_READ,
1770                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1771                                                         NULL, OPEN_EXISTING,
1772                                                         FILE_ATTRIBUTE_NORMAL |
1773                                                         FILE_FLAG_RANDOM_ACCESS,
1774                                                         NULL
1775                                                     );
1776                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1777                        }
1778                        #else
1779                        if (hFileRead) fclose(hFileRead);
1780                        hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1781                        if (!hFileRead) {
1782                            hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1783                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1784                        }
1785                        #endif
1786                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1787                        break;
1788                    case stream_mode_closed:
1789                        #if POSIX
1790                        if (hFileRead)  close(hFileRead);
1791                        if (hFileWrite) close(hFileWrite);
1792                        #elif defined(WIN32)
1793                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1794                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1795                        #else
1796                        if (hFileRead)  fclose(hFileRead);
1797                        if (hFileWrite) fclose(hFileWrite);
1798                        #endif
1799                        hFileRead = hFileWrite = 0;
1800                        break;
1801                    default:
1802                        throw Exception("Unknown file access mode");
1803                }
1804                Mode = NewMode;
1805                return true;
1806            }
1807            return false;
1808        }
1809    
1810        /** @brief Set the byte order to be used when saving.
1811         *
1812         * Set the byte order to be used in the file. A value of
1813         * endian_little will create a RIFF file, endian_big a RIFX file
1814         * and endian_native will create a RIFF file on little-endian
1815         * machines and RIFX on big-endian machines.
1816         *
1817         * @param Endian - endianess to use when file is saved.
1818         */
1819        void File::SetByteOrder(endian_t Endian) {
1820            #if WORDS_BIGENDIAN
1821            bEndianNative = Endian != endian_little;
1822            #else
1823            bEndianNative = Endian != endian_big;
1824            #endif
1825        }
1826    
1827        /** @brief Save changes to same file.
1828         *
1829         * Make all changes of all chunks persistent by writing them to the
1830         * actual (same) file.
1831         *
1832         * @param pProgress - optional: callback function for progress notification
1833         * @throws RIFF::Exception if there is an empty chunk or empty list
1834         *                         chunk or any kind of IO error occured
1835         */
1836        void File::Save(progress_t* pProgress) {
1837            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1838            if (Layout == layout_flat)
1839                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1840    
1841            // make sure the RIFF tree is built (from the original file)
1842            {
1843                // divide progress into subprogress
1844                progress_t subprogress;
1845                __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
1846                // do the actual work
1847                LoadSubChunksRecursively(&subprogress);
1848                // notify subprogress done
1849                __notify_progress(&subprogress, 1.f);
1850            }
1851    
1852            // reopen file in write mode
1853            SetMode(stream_mode_read_write);
1854    
1855            // get the current file size as it is now still physically stored on disk
1856            const file_offset_t workingFileSize = GetCurrentFileSize();
1857    
1858            // get the overall file size required to save this file
1859            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1860    
1861            // determine whether this file will yield in a large file (>=4GB) and
1862            // the RIFF file offset size to be used accordingly for all chunks
1863            FileOffsetSize = FileOffsetSizeFor(newFileSize);
1864    
1865            // to be able to save the whole file without loading everything into
1866            // RAM and without having to store the data in a temporary file, we
1867            // enlarge the file with the overall positive file size change,
1868            // then move current data towards the end of the file by the calculated
1869            // positive file size difference and finally update / rewrite the file
1870            // by copying the old data back to the right position at the beginning
1871            // of the file
1872    
1873            // if there are positive size changes...
1874            file_offset_t positiveSizeDiff = 0;
1875            if (newFileSize > workingFileSize) {
1876                positiveSizeDiff = newFileSize - workingFileSize;
1877    
1878                // divide progress into subprogress
1879                progress_t subprogress;
1880                __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1881    
1882                // ... we enlarge this file first ...
1883                ResizeFile(newFileSize);
1884    
1885                // ... and move current data by the same amount towards end of file.
1886                int8_t* pCopyBuffer = new int8_t[4096];
1887                #if defined(WIN32)
1888                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1889                #else
1890                int iBytesMoved = 1;
1891                #endif
1892                for (file_offset_t ullPos = workingFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1893                    iBytesMoved = (ullPos < 4096) ? ullPos : 4096;
1894                    ullPos -= iBytesMoved;
1895                    #if POSIX
1896                    lseek(hFileRead, ullPos, SEEK_SET);
1897                    iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1898                    lseek(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1899                    iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1900                    #elif defined(WIN32)
1901                    SetFilePointerEx(hFileRead, ullPos, NULL/*new pos pointer*/, FILE_BEGIN);
1902                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1903                    SetFilePointerEx(hFileWrite, ullPos + positiveSizeDiff, NULL/*new pos pointer*/, FILE_BEGIN);
1904                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1905                    #else
1906                    fseeko(hFileRead, ullPos, SEEK_SET);
1907                    iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1908                    fseeko(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1909                    iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1910                    #endif
1911                    if (!(iNotif % 8) && iBytesMoved > 0)
1912                        __notify_progress(&subprogress, float(workingFileSize - ullPos) / float(workingFileSize));
1913                }
1914                delete[] pCopyBuffer;
1915                if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1916    
1917                __notify_progress(&subprogress, 1.f); // notify subprogress done
1918            }
1919    
1920            // rebuild / rewrite complete RIFF tree ...
1921    
1922            // divide progress into subprogress
1923            progress_t subprogress;
1924            __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
1925            // do the actual work
1926            const file_offset_t finalSize = WriteChunk(0, positiveSizeDiff, &subprogress);
1927            const file_offset_t finalActualSize = __GetFileSize(hFileWrite);
1928            // notify subprogress done
1929            __notify_progress(&subprogress, 1.f);
1930    
1931            // resize file to the final size
1932            if (finalSize < finalActualSize) ResizeFile(finalSize);
1933    
1934            __notify_progress(pProgress, 1.0); // notify done
1935        }
1936    
1937        /** @brief Save changes to another file.
1938         *
1939         * Make all changes of all chunks persistent by writing them to another
1940         * file. <b>Caution:</b> this method is optimized for writing to
1941         * <b>another</b> file, do not use it to save the changes to the same
1942         * file! Use File::Save() in that case instead! Ignoring this might
1943         * result in a corrupted file, especially in case chunks were resized!
1944         *
1945         * After calling this method, this File object will be associated with
1946         * the new file (given by \a path) afterwards.
1947         *
1948         * @param path - path and file name where everything should be written to
1949         * @param pProgress - optional: callback function for progress notification
1950         */
1951        void File::Save(const String& path, progress_t* pProgress) {
1952            //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
1953    
1954            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1955            if (Layout == layout_flat)
1956                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1957    
1958            // make sure the RIFF tree is built (from the original file)
1959            {
1960                // divide progress into subprogress
1961                progress_t subprogress;
1962                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
1963                // do the actual work
1964                LoadSubChunksRecursively(&subprogress);
1965                // notify subprogress done
1966                __notify_progress(&subprogress, 1.f);
1967            }
1968    
1969            if (!bIsNewFile) SetMode(stream_mode_read);
1970            // open the other (new) file for writing and truncate it to zero size
1971          #if POSIX          #if POSIX
1972          if (hFile) close(hFile);          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1973            if (hFileWrite == -1) {
1974                hFileWrite = hFileRead;
1975                String sError = strerror(errno);
1976                throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
1977            }
1978            #elif defined(WIN32)
1979            hFileWrite = CreateFile(
1980                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1981                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1982                             FILE_FLAG_RANDOM_ACCESS, NULL
1983                         );
1984            if (hFileWrite == INVALID_HANDLE_VALUE) {
1985                hFileWrite = hFileRead;
1986                throw Exception("Could not open file \"" + path + "\" for writing");
1987            }
1988          #else          #else
1989          if (hFile) fclose(hFile);          hFileWrite = fopen(path.c_str(), "w+b");
1990            if (!hFileWrite) {
1991                hFileWrite = hFileRead;
1992                throw Exception("Could not open file \"" + path + "\" for writing");
1993            }
1994          #endif // POSIX          #endif // POSIX
1995            Mode = stream_mode_read_write;
1996    
1997            // get the overall file size required to save this file
1998            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1999    
2000            // determine whether this file will yield in a large file (>=4GB) and
2001            // the RIFF file offset size to be used accordingly for all chunks
2002            FileOffsetSize = FileOffsetSizeFor(newFileSize);
2003    
2004            // write complete RIFF tree to the other (new) file
2005            file_offset_t ullTotalSize;
2006            {
2007                // divide progress into subprogress
2008                progress_t subprogress;
2009                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
2010                // do the actual work
2011                ullTotalSize = WriteChunk(0, 0, &subprogress);
2012                // notify subprogress done
2013                __notify_progress(&subprogress, 1.f);
2014            }
2015            file_offset_t ullActualSize = __GetFileSize(hFileWrite);
2016    
2017            // resize file to the final size (if the file was originally larger)
2018            if (ullActualSize > ullTotalSize) ResizeFile(ullTotalSize);
2019    
2020            #if POSIX
2021            if (hFileWrite) close(hFileWrite);
2022            #elif defined(WIN32)
2023            if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
2024            #else
2025            if (hFileWrite) fclose(hFileWrite);
2026            #endif
2027            hFileWrite = hFileRead;
2028    
2029            // associate new file with this File object from now on
2030            Filename = path;
2031            bIsNewFile = false;
2032            Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
2033            SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
2034    
2035            __notify_progress(pProgress, 1.0); // notify done
2036      }      }
2037    
2038      unsigned long File::GetFileSize() {      void File::ResizeFile(file_offset_t ullNewSize) {
2039          #if POSIX          #if POSIX
2040          struct stat filestat;          if (ftruncate(hFileWrite, ullNewSize) < 0)
2041          fstat(hFile, &filestat);              throw Exception("Could not resize file \"" + Filename + "\"");
2042          long size = filestat.st_size;          #elif defined(WIN32)
2043          #else // standard C functions          if (
2044          long curpos = ftell(hFile);              !SetFilePointerEx(hFileWrite, ullNewSize, NULL/*new pos pointer*/, FILE_BEGIN) ||
2045          fseek(hFile, 0, SEEK_END);              !SetEndOfFile(hFileWrite)
2046          long size = ftell(hFile);          ) throw Exception("Could not resize file \"" + Filename + "\"");
2047          fseek(hFile, curpos, SEEK_SET);          #else
2048            # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
2049            # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
2050            #endif
2051        }
2052    
2053        File::~File() {
2054            #if DEBUG
2055            std::cout << "File::~File()" << std::endl;
2056            #endif // DEBUG
2057            Cleanup();
2058        }
2059    
2060        /**
2061         * Returns @c true if this file has been created new from scratch and
2062         * has not been stored to disk yet.
2063         */
2064        bool File::IsNew() const {
2065            return bIsNewFile;
2066        }
2067    
2068        void File::Cleanup() {
2069            #if POSIX
2070            if (hFileRead) close(hFileRead);
2071            #elif defined(WIN32)
2072            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
2073            #else
2074            if (hFileRead) fclose(hFileRead);
2075          #endif // POSIX          #endif // POSIX
2076            DeleteChunkList();
2077            pFile = NULL;
2078        }
2079    
2080        /**
2081         * Returns the current size of this file (in bytes) as it is currently
2082         * yet stored on disk. If this file does not yet exist on disk (i.e. when
2083         * this RIFF File has just been created from scratch and Save() has not
2084         * been called yet) then this method returns 0.
2085         */
2086        file_offset_t File::GetCurrentFileSize() const {
2087            file_offset_t size = 0;
2088            try {
2089                size = __GetFileSize(hFileRead);
2090            } catch (...) {
2091                size = 0;
2092            }
2093          return size;          return size;
2094      }      }
2095    
2096        /**
2097         * Returns the required size (in bytes) for this RIFF File to be saved to
2098         * disk. The precise size of the final file on disk depends on the RIFF
2099         * file offset size actually used internally in all headers of the RIFF
2100         * chunks. By default libgig handles the required file offset size
2101         * automatically for you; that means it is using 32 bit offsets for files
2102         * smaller than 4 GB and 64 bit offsets for files equal or larger than
2103         * 4 GB. You may however also override this default behavior by passing the
2104         * respective option to the RIFF File constructor to force one particular
2105         * offset size. In the latter case this method will return the file size
2106         * for the requested forced file offset size that will be used when calling
2107         * Save() later on.
2108         *
2109         * You may also use the overridden method below to get the file size for
2110         * an arbitrary other file offset size instead.
2111         *
2112         * @see offset_size_t
2113         * @see GetFileOffsetSize()
2114         */
2115        file_offset_t File::GetRequiredFileSize() {
2116            return GetRequiredFileSize(FileOffsetPreference);
2117        }
2118    
2119        /**
2120         * Returns the rquired size (in bytes) for this RIFF file to be saved to
2121         * disk, assuming the passed @a fileOffsestSize would be used for the
2122         * Save() operation.
2123         *
2124         * This overridden method essentialy behaves like the above method, with
2125         * the difference that you must provide a specific RIFF @a fileOffsetSize
2126         * for calculating the theoretical final file size.
2127         *
2128         * @see GetFileOffsetSize()
2129         */
2130        file_offset_t File::GetRequiredFileSize(offset_size_t fileOffsetSize) {
2131            switch (fileOffsetSize) {
2132                case offset_size_auto: {
2133                    file_offset_t fileSize = GetRequiredFileSize(offset_size_32bit);
2134                    if (fileSize >> 32)
2135                        return GetRequiredFileSize(offset_size_64bit);
2136                    else
2137                        return fileSize;
2138                }
2139                case offset_size_32bit: break;
2140                case offset_size_64bit: break;
2141                default: throw Exception("Internal error: Invalid RIFF::offset_size_t");
2142            }
2143            return RequiredPhysicalSize(FileOffsetSize);
2144        }
2145    
2146        int File::FileOffsetSizeFor(file_offset_t fileSize) const {
2147            switch (FileOffsetPreference) {
2148                case offset_size_auto:
2149                    return (fileSize >> 32) ? 8 : 4;
2150                case offset_size_32bit:
2151                    return 4;
2152                case offset_size_64bit:
2153                    return 8;
2154                default:
2155                    throw Exception("Internal error: Invalid RIFF::offset_size_t");
2156            }
2157        }
2158    
2159        /**
2160         * Returns the current size (in bytes) of file offsets stored in the
2161         * headers of all chunks of this file.
2162         *
2163         * Most RIFF files are using 32 bit file offsets internally, which limits
2164         * them to a maximum file size of less than 4 GB though. In contrast to the
2165         * common standard, this RIFF File class implementation supports handling of
2166         * RIFF files equal or larger than 4 GB. In such cases 64 bit file offsets
2167         * have to be used in all headers of all RIFF Chunks when being stored to a
2168         * physical file. libgig by default automatically selects the correct file
2169         * offset size for you. You may however also force one particular file
2170         * offset size by supplying the respective option to the RIFF::File
2171         * constructor.
2172         *
2173         * This method can be used to check which RIFF file offset size is currently
2174         * being used for this RIFF File.
2175         *
2176         * @returns current RIFF file offset size used (in bytes)
2177         * @see offset_size_t
2178         */
2179        int File::GetFileOffsetSize() const {
2180            return FileOffsetSize;
2181        }
2182    
2183        /**
2184         * Returns the required size (in bytes) of file offsets stored in the
2185         * headers of all chunks of this file if the current RIFF tree would be
2186         * saved to disk by calling Save().
2187         *
2188         * See GetFileOffsetSize() for mor details about RIFF file offsets.
2189         *
2190         * @returns RIFF file offset size required (in bytes) if being saved
2191         * @see offset_size_t
2192         */
2193        int File::GetRequiredFileOffsetSize() {
2194            return FileOffsetSizeFor(GetCurrentFileSize());
2195        }
2196    
2197        #if POSIX
2198        file_offset_t File::__GetFileSize(int hFile) const {
2199            struct stat filestat;
2200            if (fstat(hFile, &filestat) == -1)
2201                throw Exception("POSIX FS error: could not determine file size");
2202            return filestat.st_size;
2203        }
2204        #elif defined(WIN32)
2205        file_offset_t File::__GetFileSize(HANDLE hFile) const {
2206            PLARGE_INTEGER size;
2207            if (!GetFileSizeEx(hFile, &size))
2208                throw Exception("Windows FS error: could not determine file size");
2209            return size;
2210        }
2211        #else // standard C functions
2212        file_offset_t File::__GetFileSize(FILE* hFile) const {
2213            off_t curpos = ftello(hFile);
2214            if (fseeko(hFile, 0, SEEK_END) == -1)
2215                throw Exception("FS error: could not determine file size");
2216            off_t size = ftello(hFile);
2217            fseeko(hFile, curpos, SEEK_SET);
2218            return size;
2219        }
2220        #endif
2221    
2222    
2223  // *************** Exception ***************  // *************** Exception ***************
# Line 836  namespace RIFF { Line 2249  namespace RIFF {
2249      }      }
2250    
2251  } // namespace RIFF  } // namespace RIFF
 #endif  

Legend:
Removed from v.666  
changed lines
  Added in v.2912

  ViewVC Help
Powered by ViewVC