/[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 2155 by persson, Thu Jan 6 11:33:40 2011 UTC revision 3478 by schoenebeck, Thu Feb 21 20:10:08 2019 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2011 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2019 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 29  Line 29 
29    
30  #include "helper.h"  #include "helper.h"
31    
32    #if POSIX
33    # include <errno.h>
34    #endif
35    
36  namespace RIFF {  namespace RIFF {
37    
38  // *************** Internal functions **************  // *************** Internal functions **************
# Line 50  namespace RIFF { Line 54  namespace RIFF {
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         * Divides this progress task into the requested amount of sub-progress
69         * tasks and returns a vector with those subprogress tasks.
70         *
71         * @param iSubtasks - total amount sub tasks this task should be subdivided
72         * @returns subtasks
73         */
74        std::vector<progress_t> progress_t::subdivide(int iSubtasks) {
75            std::vector<progress_t> v;
76            for (int i = 0; i < iSubtasks; ++i) {
77                progress_t p;
78                __divide_progress(this, &p, iSubtasks, i);
79                v.push_back(p);
80            }
81            return v;
82        }
83    
84    
85    
86  // *************** Chunk **************  // *************** Chunk **************
87  // *  // *
88    
89      Chunk::Chunk(File* pFile) {      Chunk::Chunk(File* pFile) {
90          #if DEBUG          #if DEBUG_RIFF
91          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
92          #endif // DEBUG          #endif // DEBUG_RIFF
93          ulPos      = 0;          ullPos     = 0;
94          pParent    = NULL;          pParent    = NULL;
95          pChunkData = NULL;          pChunkData = NULL;
96          CurrentChunkSize = 0;          ullCurrentChunkSize = 0;
97          NewChunkSize = 0;          ullNewChunkSize = 0;
98          ulChunkDataSize = 0;          ullChunkDataSize = 0;
99          ChunkID    = CHUNK_ID_RIFF;          ChunkID    = CHUNK_ID_RIFF;
100          this->pFile = pFile;          this->pFile = pFile;
101      }      }
102    
103      Chunk::Chunk(File* pFile, unsigned long StartPos, List* Parent) {      Chunk::Chunk(File* pFile, file_offset_t StartPos, List* Parent) {
104          #if DEBUG          #if DEBUG_RIFF
105          std::cout << "Chunk::Chunk(File*,ulong,bool,List*),StartPos=" << StartPos << std::endl;          std::cout << "Chunk::Chunk(File*,file_offset_t,List*),StartPos=" << StartPos << std::endl;
106          #endif // DEBUG          #endif // DEBUG_RIFF
107          this->pFile   = pFile;          this->pFile   = pFile;
108          ulStartPos    = StartPos + CHUNK_HEADER_SIZE;          ullStartPos   = StartPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
109          pParent       = Parent;          pParent       = Parent;
110          ulPos         = 0;          ullPos        = 0;
111          pChunkData    = NULL;          pChunkData    = NULL;
112          CurrentChunkSize = 0;          ullCurrentChunkSize = 0;
113          NewChunkSize = 0;          ullNewChunkSize = 0;
114          ulChunkDataSize = 0;          ullChunkDataSize = 0;
115          ReadHeader(StartPos);          ReadHeader(StartPos);
116      }      }
117    
118      Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, uint uiBodySize) {      Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, file_offset_t ullBodySize) {
119          this->pFile      = pFile;          this->pFile      = pFile;
120          ulStartPos       = 0; // arbitrary usually, since it will be updated when we write the chunk          ullStartPos      = 0; // arbitrary usually, since it will be updated when we write the chunk
121          this->pParent    = pParent;          this->pParent    = pParent;
122          ulPos            = 0;          ullPos           = 0;
123          pChunkData       = NULL;          pChunkData       = NULL;
124          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
125          ulChunkDataSize  = 0;          ullChunkDataSize = 0;
126          CurrentChunkSize = 0;          ullCurrentChunkSize = 0;
127          NewChunkSize     = uiBodySize;          ullNewChunkSize  = ullBodySize;
128      }      }
129    
130      Chunk::~Chunk() {      Chunk::~Chunk() {
         if (pFile) pFile->UnlogResized(this);  
131          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
132      }      }
133    
134      void Chunk::ReadHeader(unsigned long fPos) {      void Chunk::ReadHeader(file_offset_t filePos) {
135          #if DEBUG          #if DEBUG_RIFF
136          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << filePos << ") ";
137          #endif // DEBUG          #endif // DEBUG_RIFF
138          ChunkID = 0;          ChunkID = 0;
139          NewChunkSize = CurrentChunkSize = 0;          ullNewChunkSize = ullCurrentChunkSize = 0;
140          #if POSIX          #if POSIX
141          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, filePos, SEEK_SET) != -1) {
142              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
143              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize);
144          #elif defined(WIN32)          #elif defined(WIN32)
145          if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {          LARGE_INTEGER liFilePos;
146            liFilePos.QuadPart = filePos;
147            if (SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
148              DWORD dwBytesRead;              DWORD dwBytesRead;
149              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
150              ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);              ReadFile(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize, &dwBytesRead, NULL);
151          #else          #else
152          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseeko(pFile->hFileRead, filePos, SEEK_SET)) {
153              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
154              fread(&CurrentChunkSize, 4, 1, pFile->hFileRead);              fread(&ullCurrentChunkSize, pFile->FileOffsetSize, 1, pFile->hFileRead);
155          #endif // POSIX          #endif // POSIX
156              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
157              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
# Line 131  namespace RIFF { Line 165  namespace RIFF {
165              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
166              if (!pFile->bEndianNative) {              if (!pFile->bEndianNative) {
167                  //swapBytes_32(&ChunkID);                  //swapBytes_32(&ChunkID);
168                  swapBytes_32(&CurrentChunkSize);                  if (pFile->FileOffsetSize == 4)
169                        swapBytes_32(&ullCurrentChunkSize);
170                    else
171                        swapBytes_64(&ullCurrentChunkSize);
172              }              }
173              #if DEBUG              #if DEBUG_RIFF
174              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
175              std::cout << "ckSize=" << CurrentChunkSize << " ";              std::cout << "ckSize=" << ullCurrentChunkSize << " ";
176              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
177              #endif // DEBUG              #endif // DEBUG_RIFF
178              NewChunkSize = CurrentChunkSize;              ullNewChunkSize = ullCurrentChunkSize;
179          }          }
180      }      }
181    
182      void Chunk::WriteHeader(unsigned long fPos) {      void Chunk::WriteHeader(file_offset_t filePos) {
183          uint32_t uiNewChunkID = ChunkID;          uint32_t uiNewChunkID = ChunkID;
184          if (ChunkID == CHUNK_ID_RIFF) {          if (ChunkID == CHUNK_ID_RIFF) {
185              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
# Line 152  namespace RIFF { Line 189  namespace RIFF {
189              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
190          }          }
191    
192          uint32_t uiNewChunkSize = NewChunkSize;          uint64_t ullNewChunkSize = this->ullNewChunkSize;
193          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
194              swapBytes_32(&uiNewChunkSize);              if (pFile->FileOffsetSize == 4)
195                    swapBytes_32(&ullNewChunkSize);
196                else
197                    swapBytes_64(&ullNewChunkSize);
198          }          }
199    
200          #if POSIX          #if POSIX
201          if (lseek(pFile->hFileWrite, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileWrite, filePos, SEEK_SET) != -1) {
202              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
203              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize);
204          }          }
205          #elif defined(WIN32)          #elif defined(WIN32)
206          if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {          LARGE_INTEGER liFilePos;
207            liFilePos.QuadPart = filePos;
208            if (SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
209              DWORD dwBytesWritten;              DWORD dwBytesWritten;
210              WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
211              WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize, &dwBytesWritten, NULL);
212          }          }
213          #else          #else
214          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseeko(pFile->hFileWrite, filePos, SEEK_SET)) {
215              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
216              fwrite(&uiNewChunkSize, 4, 1, pFile->hFileWrite);              fwrite(&ullNewChunkSize, pFile->FileOffsetSize, 1, pFile->hFileWrite);
217          }          }
218          #endif // POSIX          #endif // POSIX
219      }      }
# Line 180  namespace RIFF { Line 222  namespace RIFF {
222       *  Returns the String representation of the chunk's ID (e.g. "RIFF",       *  Returns the String representation of the chunk's ID (e.g. "RIFF",
223       *  "LIST").       *  "LIST").
224       */       */
225      String Chunk::GetChunkIDString() {      String Chunk::GetChunkIDString() const {
226          return convertToString(ChunkID);          return convertToString(ChunkID);
227      }      }
228    
# Line 196  namespace RIFF { Line 238  namespace RIFF {
238       *                  if omitted \a Where relates to beginning of the chunk       *                  if omitted \a Where relates to beginning of the chunk
239       *                  data       *                  data
240       */       */
241      unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {      file_offset_t Chunk::SetPos(file_offset_t Where, stream_whence_t Whence) {
242       #if DEBUG          #if DEBUG_RIFF
243       std::cout << "Chunk::SetPos(ulong)" << std::endl;          std::cout << "Chunk::SetPos(file_offset_t,stream_whence_t)" << std::endl;
244       #endif // DEBUG          #endif // DEBUG_RIFF
245          switch (Whence) {          switch (Whence) {
246              case stream_curpos:              case stream_curpos:
247                  ulPos += Where;                  ullPos += Where;
248                  break;                  break;
249              case stream_end:              case stream_end:
250                  ulPos = CurrentChunkSize - 1 - Where;                  ullPos = ullCurrentChunkSize - 1 - Where;
251                  break;                  break;
252              case stream_backward:              case stream_backward:
253                  ulPos -= Where;                  ullPos -= Where;
254                  break;                  break;
255              case stream_start: default:              case stream_start: default:
256                  ulPos = Where;                  ullPos = Where;
257                  break;                  break;
258          }          }
259          if (ulPos > CurrentChunkSize) ulPos = CurrentChunkSize;          if (ullPos > ullCurrentChunkSize) ullPos = ullCurrentChunkSize;
260          return ulPos;          return ullPos;
261      }      }
262    
263      /**      /**
# Line 228  namespace RIFF { Line 270  namespace RIFF {
270       *       *
271       *  @returns  number of bytes left to read       *  @returns  number of bytes left to read
272       */       */
273      unsigned long Chunk::RemainingBytes() {      file_offset_t Chunk::RemainingBytes() const {
274         #if DEBUG          #if DEBUG_RIFF
275         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;          std::cout << "Chunk::Remainingbytes()=" << ullCurrentChunkSize - ullPos << std::endl;
276         #endif // DEBUG          #endif // DEBUG_RIFF
277          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;          return (ullCurrentChunkSize > ullPos) ? ullCurrentChunkSize - ullPos : 0;
278        }
279    
280        /**
281         *  Returns the actual total size in bytes (including header) of this Chunk
282         *  if being stored to a file.
283         *
284         *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
285         *                          being saved to a file
286         */
287        file_offset_t Chunk::RequiredPhysicalSize(int fileOffsetSize) {
288            return CHUNK_HEADER_SIZE(fileOffsetSize) + // RIFF chunk header
289                   ullNewChunkSize + // chunks's actual data body
290                   ullNewChunkSize % 2; // optional pad byte
291      }      }
292    
293      /**      /**
# Line 246  namespace RIFF { Line 301  namespace RIFF {
301       *    already reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
302       *    possible without SetPos()       *    possible without SetPos()
303       */       */
304      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() const {
305        #if DEBUG          #if DEBUG_RIFF
306        std::cout << "Chunk::GetState()" << std::endl;          std::cout << "Chunk::GetState()" << std::endl;
307        #endif // DEBUG          #endif // DEBUG_RIFF
308          #if POSIX          #if POSIX
309          if (pFile->hFileRead == 0) return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
310          #elif defined (WIN32)          #elif defined (WIN32)
# Line 258  namespace RIFF { Line 313  namespace RIFF {
313          #else          #else
314          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
315          #endif // POSIX          #endif // POSIX
316          if (ulPos < CurrentChunkSize) return stream_ready;          if (ullPos < ullCurrentChunkSize) return stream_ready;
317          else                          return stream_end_reached;          else                              return stream_end_reached;
318      }      }
319    
320      /**      /**
# Line 275  namespace RIFF { Line 330  namespace RIFF {
330       *  @param WordCount  number of data words to read       *  @param WordCount  number of data words to read
331       *  @param WordSize   size of each data word to read       *  @param WordSize   size of each data word to read
332       *  @returns          number of successfully read data words or 0 if end       *  @returns          number of successfully read data words or 0 if end
333       *                    of file reached or error occured       *                    of file reached or error occurred
334       */       */
335      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) {
336         #if DEBUG          #if DEBUG_RIFF
337         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;          std::cout << "Chunk::Read(void*,file_offset_t,file_offset_t)" << std::endl;
338         #endif // DEBUG          #endif // DEBUG_RIFF
339          if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)          //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
340          if (ulPos >= CurrentChunkSize) return 0;          if (ullPos >= ullCurrentChunkSize) return 0;
341          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ullPos + WordCount * WordSize >= ullCurrentChunkSize) WordCount = (ullCurrentChunkSize - ullPos) / WordSize;
342          #if POSIX          #if POSIX
343          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET) < 0) return 0;
344          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          ssize_t readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
345          if (readWords < 1) return 0;          if (readWords < 1) {
346                #if DEBUG_RIFF
347                std::cerr << "POSIX read() failed: " << strerror(errno) << std::endl << std::flush;
348                #endif // DEBUG_RIFF
349                return 0;
350            }
351          readWords /= WordSize;          readWords /= WordSize;
352          #elif defined(WIN32)          #elif defined(WIN32)
353          if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;          LARGE_INTEGER liFilePos;
354            liFilePos.QuadPart = ullStartPos + ullPos;
355            if (!SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN))
356                return 0;
357          DWORD readWords;          DWORD readWords;
358          ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);          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)
359          if (readWords < 1) return 0;          if (readWords < 1) return 0;
360          readWords /= WordSize;          readWords /= WordSize;
361          #else // standard C functions          #else // standard C functions
362          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseeko(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET)) return 0;
363          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          file_offset_t readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
364          #endif // POSIX          #endif // POSIX
365          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
366              switch (WordSize) {              switch (WordSize) {
367                  case 2:                  case 2:
368                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
369                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
370                      break;                      break;
371                  case 4:                  case 4:
372                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
373                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
374                      break;                      break;
375                    case 8:
376                        for (file_offset_t iWord = 0; iWord < readWords; iWord++)
377                            swapBytes_64((uint64_t*) pData + iWord);
378                        break;
379                  default:                  default:
380                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
381                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
382                      break;                      break;
383              }              }
# Line 332  namespace RIFF { Line 399  namespace RIFF {
399       *  @param WordSize   size of each data word to write       *  @param WordSize   size of each data word to write
400       *  @returns          number of successfully written data words       *  @returns          number of successfully written data words
401       *  @throws RIFF::Exception  if write operation would exceed current       *  @throws RIFF::Exception  if write operation would exceed current
402       *                           chunk size or any IO error occured       *                           chunk size or any IO error occurred
403       *  @see Resize()       *  @see Resize()
404       */       */
405      unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {      file_offset_t Chunk::Write(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
406          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
407              throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");              throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
408          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)          if (ullPos >= ullCurrentChunkSize || ullPos + WordCount * WordSize > ullCurrentChunkSize)
409              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
410          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
411              switch (WordSize) {              switch (WordSize) {
412                  case 2:                  case 2:
413                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
414                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
415                      break;                      break;
416                  case 4:                  case 4:
417                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
418                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
419                      break;                      break;
420                    case 8:
421                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
422                            swapBytes_64((uint64_t*) pData + iWord);
423                        break;
424                  default:                  default:
425                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
426                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
427                      break;                      break;
428              }              }
429          }          }
430          #if POSIX          #if POSIX
431          if (lseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET) < 0) {          if (lseek(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET) < 0) {
432              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ullPos) +
433                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
434          }          }
435          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          ssize_t writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
436          if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");          if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
437          writtenWords /= WordSize;          writtenWords /= WordSize;
438          #elif defined(WIN32)          #elif defined(WIN32)
439          if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {          LARGE_INTEGER liFilePos;
440              throw Exception("Could not seek to position " + ToString(ulPos) +          liFilePos.QuadPart = ullStartPos + ullPos;
441                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");          if (!SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
442                throw Exception("Could not seek to position " + ToString(ullPos) +
443                                " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
444          }          }
445          DWORD writtenWords;          DWORD writtenWords;
446          WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);          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)
447          if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");          if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
448          writtenWords /= WordSize;          writtenWords /= WordSize;
449          #else // standard C functions          #else // standard C functions
450          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseeko(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET)) {
451              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ullPos) +
452                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
453          }          }
454          unsigned long writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);          file_offset_t writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
455          #endif // POSIX          #endif // POSIX
456          SetPos(writtenWords * WordSize, stream_curpos);          SetPos(writtenWords * WordSize, stream_curpos);
457          return writtenWords;          return writtenWords;
458      }      }
459    
460      /** 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. */
461      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) {
462          unsigned long readWords = Read(pData, WordCount, WordSize);          file_offset_t readWords = Read(pData, WordCount, WordSize);
463          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");
464          return readWords;          return readWords;
465      }      }
# Line 399  namespace RIFF { Line 472  namespace RIFF {
472       * @param pData             destination buffer       * @param pData             destination buffer
473       * @param WordCount         number of 8 Bit signed integers to read       * @param WordCount         number of 8 Bit signed integers to read
474       * @returns                 number of read integers       * @returns                 number of read integers
475       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
476       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
477       */       */
478      unsigned long Chunk::ReadInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt8(int8_t* pData, file_offset_t WordCount) {
479         #if DEBUG          #if DEBUG_RIFF
480         std::cout << "Chunk::ReadInt8(int8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt8(int8_t*,file_offset_t)" << std::endl;
481         #endif // DEBUG          #endif // DEBUG_RIFF
482          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
483      }      }
484    
# Line 420  namespace RIFF { Line 493  namespace RIFF {
493       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
494       * @param WordCount         number of 8 Bit signed integers to write       * @param WordCount         number of 8 Bit signed integers to write
495       * @returns                 number of written integers       * @returns                 number of written integers
496       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
497       * @see Resize()       * @see Resize()
498       */       */
499      unsigned long Chunk::WriteInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt8(int8_t* pData, file_offset_t WordCount) {
500          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
501      }      }
502    
# Line 436  namespace RIFF { Line 509  namespace RIFF {
509       * @param pData             destination buffer       * @param pData             destination buffer
510       * @param WordCount         number of 8 Bit unsigned integers to read       * @param WordCount         number of 8 Bit unsigned integers to read
511       * @returns                 number of read integers       * @returns                 number of read integers
512       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
513       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
514       */       */
515      unsigned long Chunk::ReadUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint8(uint8_t* pData, file_offset_t WordCount) {
516         #if DEBUG          #if DEBUG_RIFF
517         std::cout << "Chunk::ReadUint8(uint8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint8(uint8_t*,file_offset_t)" << std::endl;
518         #endif // DEBUG          #endif // DEBUG_RIFF
519          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
520      }      }
521    
# Line 457  namespace RIFF { Line 530  namespace RIFF {
530       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
531       * @param WordCount         number of 8 Bit unsigned integers to write       * @param WordCount         number of 8 Bit unsigned integers to write
532       * @returns                 number of written integers       * @returns                 number of written integers
533       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
534       * @see Resize()       * @see Resize()
535       */       */
536      unsigned long Chunk::WriteUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint8(uint8_t* pData, file_offset_t WordCount) {
537          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
538      }      }
539    
# Line 473  namespace RIFF { Line 546  namespace RIFF {
546       * @param pData             destination buffer       * @param pData             destination buffer
547       * @param WordCount         number of 16 Bit signed integers to read       * @param WordCount         number of 16 Bit signed integers to read
548       * @returns                 number of read integers       * @returns                 number of read integers
549       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
550       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
551       */       */
552      unsigned long Chunk::ReadInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt16(int16_t* pData, file_offset_t WordCount) {
553        #if DEBUG          #if DEBUG_RIFF
554        std::cout << "Chunk::ReadInt16(int16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt16(int16_t*,file_offset_t)" << std::endl;
555        #endif // DEBUG          #endif // DEBUG_RIFF
556          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
557      }      }
558    
# Line 494  namespace RIFF { Line 567  namespace RIFF {
567       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
568       * @param WordCount         number of 16 Bit signed integers to write       * @param WordCount         number of 16 Bit signed integers to write
569       * @returns                 number of written integers       * @returns                 number of written integers
570       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
571       * @see Resize()       * @see Resize()
572       */       */
573      unsigned long Chunk::WriteInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt16(int16_t* pData, file_offset_t WordCount) {
574          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
575      }      }
576    
# Line 510  namespace RIFF { Line 583  namespace RIFF {
583       * @param pData             destination buffer       * @param pData             destination buffer
584       * @param WordCount         number of 8 Bit unsigned integers to read       * @param WordCount         number of 8 Bit unsigned integers to read
585       * @returns                 number of read integers       * @returns                 number of read integers
586       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
587       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
588       */       */
589      unsigned long Chunk::ReadUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint16(uint16_t* pData, file_offset_t WordCount) {
590        #if DEBUG          #if DEBUG_RIFF
591        std::cout << "Chunk::ReadUint16(uint16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint16(uint16_t*,file_offset_t)" << std::endl;
592        #endif // DEBUG          #endif // DEBUG_RIFF
593          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
594      }      }
595    
# Line 531  namespace RIFF { Line 604  namespace RIFF {
604       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
605       * @param WordCount         number of 16 Bit unsigned integers to write       * @param WordCount         number of 16 Bit unsigned integers to write
606       * @returns                 number of written integers       * @returns                 number of written integers
607       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
608       * @see Resize()       * @see Resize()
609       */       */
610      unsigned long Chunk::WriteUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint16(uint16_t* pData, file_offset_t WordCount) {
611          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
612      }      }
613    
# Line 547  namespace RIFF { Line 620  namespace RIFF {
620       * @param pData             destination buffer       * @param pData             destination buffer
621       * @param WordCount         number of 32 Bit signed integers to read       * @param WordCount         number of 32 Bit signed integers to read
622       * @returns                 number of read integers       * @returns                 number of read integers
623       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
624       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
625       */       */
626      unsigned long Chunk::ReadInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt32(int32_t* pData, file_offset_t WordCount) {
627         #if DEBUG          #if DEBUG_RIFF
628         std::cout << "Chunk::ReadInt32(int32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt32(int32_t*,file_offset_t)" << std::endl;
629         #endif // DEBUG          #endif // DEBUG_RIFF
630          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
631      }      }
632    
# Line 568  namespace RIFF { Line 641  namespace RIFF {
641       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
642       * @param WordCount         number of 32 Bit signed integers to write       * @param WordCount         number of 32 Bit signed integers to write
643       * @returns                 number of written integers       * @returns                 number of written integers
644       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
645       * @see Resize()       * @see Resize()
646       */       */
647      unsigned long Chunk::WriteInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt32(int32_t* pData, file_offset_t WordCount) {
648          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
649      }      }
650    
# Line 584  namespace RIFF { Line 657  namespace RIFF {
657       * @param pData             destination buffer       * @param pData             destination buffer
658       * @param WordCount         number of 32 Bit unsigned integers to read       * @param WordCount         number of 32 Bit unsigned integers to read
659       * @returns                 number of read integers       * @returns                 number of read integers
660       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
661       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
662       */       */
663      unsigned long Chunk::ReadUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint32(uint32_t* pData, file_offset_t WordCount) {
664         #if DEBUG          #if DEBUG_RIFF
665         std::cout << "Chunk::ReadUint32(uint32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint32(uint32_t*,file_offset_t)" << std::endl;
666         #endif // DEBUG          #endif // DEBUG_RIFF
667          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
668      }      }
669    
670      /**      /**
671         * Reads a null-padded string of size characters and copies it
672         * into the string \a s. The position within the chunk will
673         * automatically be incremented.
674         *
675         * @param s                 destination string
676         * @param size              number of characters to read
677         * @throws RIFF::Exception  if an error occurred or less than
678         *                          \a size characters could be read!
679         */
680        void Chunk::ReadString(String& s, int size) {
681            char* buf = new char[size];
682            ReadSceptical(buf, 1, size);
683            s.assign(buf, std::find(buf, buf + size, '\0'));
684            delete[] buf;
685        }
686    
687        /**
688       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
689       * buffer pointed by \a pData to the chunk's body, directly to the       * buffer pointed by \a pData to the chunk's body, directly to the
690       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 605  namespace RIFF { Line 695  namespace RIFF {
695       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
696       * @param WordCount         number of 32 Bit unsigned integers to write       * @param WordCount         number of 32 Bit unsigned integers to write
697       * @returns                 number of written integers       * @returns                 number of written integers
698       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
699       * @see Resize()       * @see Resize()
700       */       */
701      unsigned long Chunk::WriteUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint32(uint32_t* pData, file_offset_t WordCount) {
702          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
703      }      }
704    
# Line 617  namespace RIFF { Line 707  namespace RIFF {
707       * the chunk.       * the chunk.
708       *       *
709       * @returns                 read integer word       * @returns                 read integer word
710       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
711       */       */
712      int8_t Chunk::ReadInt8() {      int8_t Chunk::ReadInt8() {
713        #if DEBUG          #if DEBUG_RIFF
714        std::cout << "Chunk::ReadInt8()" << std::endl;          std::cout << "Chunk::ReadInt8()" << std::endl;
715        #endif // DEBUG          #endif // DEBUG_RIFF
716          int8_t word;          int8_t word;
717          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
718          return word;          return word;
# Line 633  namespace RIFF { Line 723  namespace RIFF {
723       * within the chunk.       * within the chunk.
724       *       *
725       * @returns                 read integer word       * @returns                 read integer word
726       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
727       */       */
728      uint8_t Chunk::ReadUint8() {      uint8_t Chunk::ReadUint8() {
729        #if DEBUG          #if DEBUG_RIFF
730        std::cout << "Chunk::ReadUint8()" << std::endl;          std::cout << "Chunk::ReadUint8()" << std::endl;
731        #endif // DEBUG          #endif // DEBUG_RIFF
732          uint8_t word;          uint8_t word;
733          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
734          return word;          return word;
# Line 650  namespace RIFF { Line 740  namespace RIFF {
740       * needed.       * needed.
741       *       *
742       * @returns                 read integer word       * @returns                 read integer word
743       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
744       */       */
745      int16_t Chunk::ReadInt16() {      int16_t Chunk::ReadInt16() {
746        #if DEBUG          #if DEBUG_RIFF
747        std::cout << "Chunk::ReadInt16()" << std::endl;          std::cout << "Chunk::ReadInt16()" << std::endl;
748        #endif // DEBUG          #endif // DEBUG_RIFF
749          int16_t word;          int16_t word;
750          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
751          return word;          return word;
# Line 667  namespace RIFF { Line 757  namespace RIFF {
757       * needed.       * needed.
758       *       *
759       * @returns                 read integer word       * @returns                 read integer word
760       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
761       */       */
762      uint16_t Chunk::ReadUint16() {      uint16_t Chunk::ReadUint16() {
763        #if DEBUG          #if DEBUG_RIFF
764        std::cout << "Chunk::ReadUint16()" << std::endl;          std::cout << "Chunk::ReadUint16()" << std::endl;
765        #endif // DEBUG          #endif // DEBUG_RIFF
766          uint16_t word;          uint16_t word;
767          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
768          return word;          return word;
# Line 684  namespace RIFF { Line 774  namespace RIFF {
774       * needed.       * needed.
775       *       *
776       * @returns                 read integer word       * @returns                 read integer word
777       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
778       */       */
779      int32_t Chunk::ReadInt32() {      int32_t Chunk::ReadInt32() {
780        #if DEBUG          #if DEBUG_RIFF
781        std::cout << "Chunk::ReadInt32()" << std::endl;          std::cout << "Chunk::ReadInt32()" << std::endl;
782        #endif // DEBUG          #endif // DEBUG_RIFF
783          int32_t word;          int32_t word;
784          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
785          return word;          return word;
# Line 701  namespace RIFF { Line 791  namespace RIFF {
791       * needed.       * needed.
792       *       *
793       * @returns                 read integer word       * @returns                 read integer word
794       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
795       */       */
796      uint32_t Chunk::ReadUint32() {      uint32_t Chunk::ReadUint32() {
797        #if DEBUG          #if DEBUG_RIFF
798        std::cout << "Chunk::ReadUint32()" << std::endl;          std::cout << "Chunk::ReadUint32()" << std::endl;
799        #endif // DEBUG          #endif // DEBUG_RIFF
800          uint32_t word;          uint32_t word;
801          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
802          return word;          return word;
# Line 734  namespace RIFF { Line 824  namespace RIFF {
824       * @see ReleaseChunkData()       * @see ReleaseChunkData()
825       */       */
826      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
827          if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
828              #if POSIX              #if POSIX
829              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ullStartPos, SEEK_SET) == -1) return NULL;
830              #elif defined(WIN32)              #elif defined(WIN32)
831              if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;              LARGE_INTEGER liFilePos;
832                liFilePos.QuadPart = ullStartPos;
833                if (!SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) return NULL;
834              #else              #else
835              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseeko(pFile->hFileRead, ullStartPos, SEEK_SET)) return NULL;
836              #endif // POSIX              #endif // POSIX
837              unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;              file_offset_t ullBufferSize = (ullCurrentChunkSize > ullNewChunkSize) ? ullCurrentChunkSize : ullNewChunkSize;
838              pChunkData = new uint8_t[ulBufferSize];              pChunkData = new uint8_t[ullBufferSize];
839              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
840              memset(pChunkData, 0, ulBufferSize);              memset(pChunkData, 0, ullBufferSize);
841              #if POSIX              #if POSIX
842              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());              file_offset_t readWords = read(pFile->hFileRead, pChunkData, GetSize());
843              #elif defined(WIN32)              #elif defined(WIN32)
844              DWORD readWords;              DWORD readWords;
845              ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);              ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL); //FIXME: won't load chunks larger than 2GB !
846              #else              #else
847              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              file_offset_t readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
848              #endif // POSIX              #endif // POSIX
849              if (readWords != GetSize()) {              if (readWords != GetSize()) {
850                  delete[] pChunkData;                  delete[] pChunkData;
851                  return (pChunkData = NULL);                  return (pChunkData = NULL);
852              }              }
853              ulChunkDataSize = ulBufferSize;              ullChunkDataSize = ullBufferSize;
854          } else if (NewChunkSize > ulChunkDataSize) {          } else if (ullNewChunkSize > ullChunkDataSize) {
855              uint8_t* pNewBuffer = new uint8_t[NewChunkSize];              uint8_t* pNewBuffer = new uint8_t[ullNewChunkSize];
856              if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");              if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(ullNewChunkSize) + " bytes");
857              memset(pNewBuffer, 0 , NewChunkSize);              memset(pNewBuffer, 0 , ullNewChunkSize);
858              memcpy(pNewBuffer, pChunkData, ulChunkDataSize);              memcpy(pNewBuffer, pChunkData, ullChunkDataSize);
859              delete[] pChunkData;              delete[] pChunkData;
860              pChunkData      = pNewBuffer;              pChunkData       = pNewBuffer;
861              ulChunkDataSize = NewChunkSize;              ullChunkDataSize = ullNewChunkSize;
862          }          }
863          return pChunkData;          return pChunkData;
864      }      }
# Line 798  namespace RIFF { Line 890  namespace RIFF {
890       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
891       * boundary!       * boundary!
892       *       *
893       * @param iNewSize - new chunk body size in bytes (must be greater than zero)       * @param NewSize - new chunk body size in bytes (must be greater than zero)
894       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a NewSize is less than 1 or unrealistic large
895       * @see File::Save()       * @see File::Save()
896       */       */
897      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(file_offset_t NewSize) {
898          if (iNewSize <= 0)          if (NewSize == 0)
899              throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));              throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
900          if (NewChunkSize == iNewSize) return;          if ((NewSize >> 48) != 0)
901          NewChunkSize = iNewSize;              throw Exception("Unrealistic high chunk size detected: " + __resolveChunkPath(this));
902          pFile->LogAsResized(this);          if (ullNewChunkSize == NewSize) return;
903            ullNewChunkSize = NewSize;
904      }      }
905    
906      /** @brief Write chunk persistently e.g. to disk.      /** @brief Write chunk persistently e.g. to disk.
907       *       *
908       * Stores the chunk persistently to its actual "physical" file.       * Stores the chunk persistently to its actual "physical" file.
909       *       *
910       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
911       *                     chunk should be written to       *                     chunk should be written to
912       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
913       *                              the file       *                              the file
914         * @param pProgress - optional: callback function for progress notification
915       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
916       *          \a ulWritePos incremented by this chunk's new size       *          \a ullWritePos incremented by this chunk's new size
917       *          (including its header size of course)       *          (including its header size of course)
918       */       */
919      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      file_offset_t Chunk::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
920          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
921          ulWritePos += CHUNK_HEADER_SIZE;          ullWritePos += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
922    
923          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
924              throw Exception("Cannot write list chunk, file has to be opened in read+write mode");              throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
# Line 835  namespace RIFF { Line 929  namespace RIFF {
929              LoadChunkData();              LoadChunkData();
930              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
931              #if POSIX              #if POSIX
932              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ullWritePos, SEEK_SET);
933              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, ullNewChunkSize) != ullNewChunkSize) {
934                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
935              }              }
936              #elif defined(WIN32)              #elif defined(WIN32)
937              SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);              LARGE_INTEGER liFilePos;
938                liFilePos.QuadPart = ullWritePos;
939                SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
940              DWORD dwBytesWritten;              DWORD dwBytesWritten;
941              WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, pChunkData, ullNewChunkSize, &dwBytesWritten, NULL); //FIXME: won't save chunks larger than 2GB !
942              if (dwBytesWritten != NewChunkSize) {              if (dwBytesWritten != ullNewChunkSize) {
943                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
944              }              }
945              #else              #else
946              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseeko(pFile->hFileWrite, ullWritePos, SEEK_SET);
947              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, ullNewChunkSize, pFile->hFileWrite) != ullNewChunkSize) {
948                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
949              }              }
950              #endif // POSIX              #endif // POSIX
951          } else {          } else {
952              // move chunk data from the end of the file to the appropriate position              // move chunk data from the end of the file to the appropriate position
953              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
954              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              file_offset_t ullToMove = (ullNewChunkSize < ullCurrentChunkSize) ? ullNewChunkSize : ullCurrentChunkSize;
955              #if defined(WIN32)              #if defined(WIN32)
956              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
957              #else              #else
958              int iBytesMoved = 1;              int iBytesMoved = 1;
959              #endif              #endif
960              for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (file_offset_t ullOffset = 0; ullToMove > 0 && iBytesMoved > 0; ullOffset += iBytesMoved, ullToMove -= iBytesMoved) {
961                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ullToMove < 4096) ? int(ullToMove) : 4096;
962                  #if POSIX                  #if POSIX
963                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
964                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = (int) read(pFile->hFileRead, pCopyBuffer, (size_t) iBytesMoved);
965                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
966                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = (int) write(pFile->hFileWrite, pCopyBuffer, (size_t) iBytesMoved);
967                  #elif defined(WIN32)                  #elif defined(WIN32)
968                  SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  LARGE_INTEGER liFilePos;
969                    liFilePos.QuadPart = ullStartPos + ullCurrentDataOffset + ullOffset;
970                    SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
971                  ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
972                  SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  liFilePos.QuadPart = ullWritePos + ullOffset;
973                    SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
974                  WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
975                  #else                  #else
976                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseeko(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
977                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
978                  fseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  fseeko(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
979                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
980                  #endif                  #endif
981              }              }
# Line 885  namespace RIFF { Line 984  namespace RIFF {
984          }          }
985    
986          // update this chunk's header          // update this chunk's header
987          CurrentChunkSize = NewChunkSize;          ullCurrentChunkSize = ullNewChunkSize;
988          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
989    
990            __notify_progress(pProgress, 1.0); // notify done
991    
992          // update chunk's position pointers          // update chunk's position pointers
993          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;          ullStartPos = ullOriginalPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
994          ulPos      = 0;          ullPos      = 0;
995    
996          // add pad byte if needed          // add pad byte if needed
997          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ullStartPos + ullNewChunkSize) % 2 != 0) {
998              const char cPadByte = 0;              const char cPadByte = 0;
999              #if POSIX              #if POSIX
1000              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
1001              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
1002              #elif defined(WIN32)              #elif defined(WIN32)
1003              SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);              LARGE_INTEGER liFilePos;
1004                liFilePos.QuadPart = ullStartPos + ullNewChunkSize;
1005                SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1006              DWORD dwBytesWritten;              DWORD dwBytesWritten;
1007              WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
1008              #else              #else
1009              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseeko(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
1010              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
1011              #endif              #endif
1012              return ulStartPos + NewChunkSize + 1;              return ullStartPos + ullNewChunkSize + 1;
1013          }          }
1014    
1015          return ulStartPos + NewChunkSize;          return ullStartPos + ullNewChunkSize;
1016      }      }
1017    
1018      void Chunk::__resetPos() {      void Chunk::__resetPos() {
1019          ulPos = 0;          ullPos = 0;
1020      }      }
1021    
1022    
# Line 922  namespace RIFF { Line 1025  namespace RIFF {
1025  // *  // *
1026    
1027      List::List(File* pFile) : Chunk(pFile) {      List::List(File* pFile) : Chunk(pFile) {
1028        #if DEBUG          #if DEBUG_RIFF
1029        std::cout << "List::List(File* pFile)" << std::endl;          std::cout << "List::List(File* pFile)" << std::endl;
1030        #endif // DEBUG          #endif // DEBUG_RIFF
1031          pSubChunks    = NULL;          pSubChunks    = NULL;
1032          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1033      }      }
1034    
1035      List::List(File* pFile, unsigned long StartPos, List* Parent)      List::List(File* pFile, file_offset_t StartPos, List* Parent)
1036        : Chunk(pFile, StartPos, Parent) {        : Chunk(pFile, StartPos, Parent) {
1037          #if DEBUG          #if DEBUG_RIFF
1038          std::cout << "List::List(File*,ulong,bool,List*)" << std::endl;          std::cout << "List::List(File*,file_offset_t,List*)" << std::endl;
1039          #endif // DEBUG          #endif // DEBUG_RIFF
1040          pSubChunks    = NULL;          pSubChunks    = NULL;
1041          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1042          ReadHeader(StartPos);          ReadHeader(StartPos);
1043          ulStartPos    = StartPos + LIST_HEADER_SIZE;          ullStartPos = StartPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1044      }      }
1045    
1046      List::List(File* pFile, List* pParent, uint32_t uiListID)      List::List(File* pFile, List* pParent, uint32_t uiListID)
# Line 948  namespace RIFF { Line 1051  namespace RIFF {
1051      }      }
1052    
1053      List::~List() {      List::~List() {
1054        #if DEBUG          #if DEBUG_RIFF
1055        std::cout << "List::~List()" << std::endl;          std::cout << "List::~List()" << std::endl;
1056        #endif // DEBUG          #endif // DEBUG_RIFF
1057          DeleteChunkList();          DeleteChunkList();
1058      }      }
1059    
# Line 983  namespace RIFF { Line 1086  namespace RIFF {
1086       *                   that ID       *                   that ID
1087       */       */
1088      Chunk* List::GetSubChunk(uint32_t ChunkID) {      Chunk* List::GetSubChunk(uint32_t ChunkID) {
1089        #if DEBUG          #if DEBUG_RIFF
1090        std::cout << "List::GetSubChunk(uint32_t)" << std::endl;          std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
1091        #endif // DEBUG          #endif // DEBUG_RIFF
1092          if (!pSubChunksMap) LoadSubChunks();          if (!pSubChunksMap) LoadSubChunks();
1093          return (*pSubChunksMap)[ChunkID];          return (*pSubChunksMap)[ChunkID];
1094      }      }
# Line 993  namespace RIFF { Line 1096  namespace RIFF {
1096      /**      /**
1097       *  Returns sublist chunk with list type <i>\a ListType</i> within this       *  Returns sublist chunk with list type <i>\a ListType</i> within this
1098       *  chunk list. Use this method if you expect only one sublist chunk of       *  chunk list. Use this method if you expect only one sublist chunk of
1099       *  that type in the list. It there are more than one, it's undetermined       *  that type in the list. If there are more than one, it's undetermined
1100       *  which one of them will be returned! If there are no sublists with       *  which one of them will be returned! If there are no sublists with
1101       *  that desired list type, NULL will be returned.       *  that desired list type, NULL will be returned.
1102       *       *
# Line 1002  namespace RIFF { Line 1105  namespace RIFF {
1105       *                    that type       *                    that type
1106       */       */
1107      List* List::GetSubList(uint32_t ListType) {      List* List::GetSubList(uint32_t ListType) {
1108          #if DEBUG          #if DEBUG_RIFF
1109          std::cout << "List::GetSubList(uint32_t)" << std::endl;          std::cout << "List::GetSubList(uint32_t)" << std::endl;
1110          #endif // DEBUG          #endif // DEBUG_RIFF
1111          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1112          ChunkList::iterator iter = pSubChunks->begin();          ChunkList::iterator iter = pSubChunks->begin();
1113          ChunkList::iterator end  = pSubChunks->end();          ChunkList::iterator end  = pSubChunks->end();
# Line 1019  namespace RIFF { Line 1122  namespace RIFF {
1122      }      }
1123    
1124      /**      /**
1125       *  Returns the first subchunk within the list. You have to call this       *  Returns the first subchunk within the list (which may be an ordinary
1126         *  chunk as well as a list chunk). You have to call this
1127       *  method before you can call GetNextSubChunk(). Recall it when you want       *  method before you can call GetNextSubChunk(). Recall it when you want
1128       *  to start from the beginning of the list again.       *  to start from the beginning of the list again.
1129       *       *
# Line 1027  namespace RIFF { Line 1131  namespace RIFF {
1131       *            otherwise       *            otherwise
1132       */       */
1133      Chunk* List::GetFirstSubChunk() {      Chunk* List::GetFirstSubChunk() {
1134          #if DEBUG          #if DEBUG_RIFF
1135          std::cout << "List::GetFirstSubChunk()" << std::endl;          std::cout << "List::GetFirstSubChunk()" << std::endl;
1136          #endif // DEBUG          #endif // DEBUG_RIFF
1137          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1138          ChunksIterator = pSubChunks->begin();          ChunksIterator = pSubChunks->begin();
1139          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1140      }      }
1141    
1142      /**      /**
1143       *  Returns the next subchunk within the list. You have to call       *  Returns the next subchunk within the list (which may be an ordinary
1144         *  chunk as well as a list chunk). You have to call
1145       *  GetFirstSubChunk() before you can use this method!       *  GetFirstSubChunk() before you can use this method!
1146       *       *
1147       *  @returns  pointer to the next subchunk within the list or NULL if       *  @returns  pointer to the next subchunk within the list or NULL if
1148       *            end of list is reached       *            end of list is reached
1149       */       */
1150      Chunk* List::GetNextSubChunk() {      Chunk* List::GetNextSubChunk() {
1151          #if DEBUG          #if DEBUG_RIFF
1152          std::cout << "List::GetNextSubChunk()" << std::endl;          std::cout << "List::GetNextSubChunk()" << std::endl;
1153          #endif // DEBUG          #endif // DEBUG_RIFF
1154          if (!pSubChunks) return NULL;          if (!pSubChunks) return NULL;
1155          ChunksIterator++;          ChunksIterator++;
1156          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
# Line 1061  namespace RIFF { Line 1166  namespace RIFF {
1166       *            otherwise       *            otherwise
1167       */       */
1168      List* List::GetFirstSubList() {      List* List::GetFirstSubList() {
1169          #if DEBUG          #if DEBUG_RIFF
1170          std::cout << "List::GetFirstSubList()" << std::endl;          std::cout << "List::GetFirstSubList()" << std::endl;
1171          #endif // DEBUG          #endif // DEBUG_RIFF
1172          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1173          ListIterator            = pSubChunks->begin();          ListIterator            = pSubChunks->begin();
1174          ChunkList::iterator end = pSubChunks->end();          ChunkList::iterator end = pSubChunks->end();
# Line 1083  namespace RIFF { Line 1188  namespace RIFF {
1188       *            end of list is reached       *            end of list is reached
1189       */       */
1190      List* List::GetNextSubList() {      List* List::GetNextSubList() {
1191          #if DEBUG          #if DEBUG_RIFF
1192          std::cout << "List::GetNextSubList()" << std::endl;          std::cout << "List::GetNextSubList()" << std::endl;
1193          #endif // DEBUG          #endif // DEBUG_RIFF
1194          if (!pSubChunks) return NULL;          if (!pSubChunks) return NULL;
1195          if (ListIterator == pSubChunks->end()) return NULL;          if (ListIterator == pSubChunks->end()) return NULL;
1196          ListIterator++;          ListIterator++;
# Line 1098  namespace RIFF { Line 1203  namespace RIFF {
1203      }      }
1204    
1205      /**      /**
1206       *  Returns number of subchunks within the list.       *  Returns number of subchunks within the list (including list chunks).
1207       */       */
1208      unsigned int List::CountSubChunks() {      size_t List::CountSubChunks() {
1209          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1210          return pSubChunks->size();          return pSubChunks->size();
1211      }      }
# Line 1109  namespace RIFF { Line 1214  namespace RIFF {
1214       *  Returns number of subchunks within the list with chunk ID       *  Returns number of subchunks within the list with chunk ID
1215       *  <i>\a ChunkId</i>.       *  <i>\a ChunkId</i>.
1216       */       */
1217      unsigned int List::CountSubChunks(uint32_t ChunkID) {      size_t List::CountSubChunks(uint32_t ChunkID) {
1218          unsigned int result = 0;          size_t result = 0;
1219          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1220          ChunkList::iterator iter = pSubChunks->begin();          ChunkList::iterator iter = pSubChunks->begin();
1221          ChunkList::iterator end  = pSubChunks->end();          ChunkList::iterator end  = pSubChunks->end();
# Line 1126  namespace RIFF { Line 1231  namespace RIFF {
1231      /**      /**
1232       *  Returns number of sublists within the list.       *  Returns number of sublists within the list.
1233       */       */
1234      unsigned int List::CountSubLists() {      size_t List::CountSubLists() {
1235          return CountSubChunks(CHUNK_ID_LIST);          return CountSubChunks(CHUNK_ID_LIST);
1236      }      }
1237    
# Line 1134  namespace RIFF { Line 1239  namespace RIFF {
1239       *  Returns number of sublists within the list with list type       *  Returns number of sublists within the list with list type
1240       *  <i>\a ListType</i>       *  <i>\a ListType</i>
1241       */       */
1242      unsigned int List::CountSubLists(uint32_t ListType) {      size_t List::CountSubLists(uint32_t ListType) {
1243          unsigned int result = 0;          size_t result = 0;
1244          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1245          ChunkList::iterator iter = pSubChunks->begin();          ChunkList::iterator iter = pSubChunks->begin();
1246          ChunkList::iterator end  = pSubChunks->end();          ChunkList::iterator end  = pSubChunks->end();
# Line 1152  namespace RIFF { Line 1257  namespace RIFF {
1257      /** @brief Creates a new sub chunk.      /** @brief Creates a new sub chunk.
1258       *       *
1259       * Creates and adds a new sub chunk to this list chunk. Note that the       * Creates and adds a new sub chunk to this list chunk. Note that the
1260       * chunk's body size given by \a uiBodySize must be greater than zero.       * chunk's body size given by \a ullBodySize must be greater than zero.
1261       * You have to call File::Save() to make this change persistent to the       * You have to call File::Save() to make this change persistent to the
1262       * actual file and <b>before</b> performing any data write operations       * actual file and <b>before</b> performing any data write operations
1263       * on the new chunk!       * on the new chunk!
1264       *       *
1265       * @param uiChunkID  - chunk ID of the new chunk       * @param uiChunkID  - chunk ID of the new chunk
1266       * @param uiBodySize - size of the new chunk's body, that is its actual       * @param ullBodySize - size of the new chunk's body, that is its actual
1267       *                     data size (without header)       *                      data size (without header)
1268       * @throws RIFF::Exception if \a uiBodySize equals zero       * @throws RIFF::Exception if \a ullBodySize equals zero
1269       */       */
1270      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize) {
1271          if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");          if (ullBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1272          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1273          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1274          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1275          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1276          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(ullBodySize);
1277          NewChunkSize += CHUNK_HEADER_SIZE;          ullNewChunkSize += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1278          return pNewChunk;          return pNewChunk;
1279      }      }
1280    
1281      /** @brief Moves a sub chunk.      /** @brief Moves a sub chunk witin this list.
1282       *       *
1283       * Moves a sub chunk from one position in a list to another       * Moves a sub chunk from one position in this list to another
1284       * position in the same list. The pSrc chunk is placed before the       * position in the same list. The pSrc chunk is placed before the
1285       * pDst chunk.       * pDst chunk.
1286       *       *
# Line 1192  namespace RIFF { Line 1296  namespace RIFF {
1296          pSubChunks->insert(iter, pSrc);          pSubChunks->insert(iter, pSrc);
1297      }      }
1298    
1299        /** @brief Moves a sub chunk from this list to another list.
1300         *
1301         * Moves a sub chunk from this list list to the end of another
1302         * list.
1303         *
1304         * @param pSrc - sub chunk to be moved
1305         * @param pDst - destination list where the chunk shall be moved to
1306         */
1307        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1308            if (pNewParent == this || !pNewParent) return;
1309            if (!pSubChunks) LoadSubChunks();
1310            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1311            pSubChunks->remove(pSrc);
1312            pNewParent->pSubChunks->push_back(pSrc);
1313            // update chunk id map of this List
1314            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1315                pSubChunksMap->erase(pSrc->GetChunkID());
1316                // try to find another chunk of the same chunk ID
1317                ChunkList::iterator iter = pSubChunks->begin();
1318                ChunkList::iterator end  = pSubChunks->end();
1319                for (; iter != end; ++iter) {
1320                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1321                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1322                        break; // we're done, stop search
1323                    }
1324                }
1325            }
1326            // update chunk id map of other list
1327            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1328                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1329        }
1330    
1331      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1332       *       *
1333       * Creates and adds a new list sub chunk to this list chunk. Note that       * Creates and adds a new list sub chunk to this list chunk. Note that
# Line 1206  namespace RIFF { Line 1342  namespace RIFF {
1342          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1343          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1344          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1345          NewChunkSize += LIST_HEADER_SIZE;          ullNewChunkSize += LIST_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1346          return pNewListChunk;          return pNewListChunk;
1347      }      }
1348    
# Line 1239  namespace RIFF { Line 1374  namespace RIFF {
1374          delete pSubChunk;          delete pSubChunk;
1375      }      }
1376    
1377      void List::ReadHeader(unsigned long fPos) {      /**
1378        #if DEBUG       *  Returns the actual total size in bytes (including List chunk header and
1379        std::cout << "List::Readheader(ulong) ";       *  all subchunks) of this List Chunk if being stored to a file.
1380        #endif // DEBUG       *
1381          Chunk::ReadHeader(fPos);       *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
1382          if (CurrentChunkSize < 4) return;       *                          being saved to a file
1383          NewChunkSize = CurrentChunkSize -= 4;       */
1384        file_offset_t List::RequiredPhysicalSize(int fileOffsetSize) {
1385            if (!pSubChunks) LoadSubChunks();
1386            file_offset_t size = LIST_HEADER_SIZE(fileOffsetSize);
1387            ChunkList::iterator iter = pSubChunks->begin();
1388            ChunkList::iterator end  = pSubChunks->end();
1389            for (; iter != end; ++iter)
1390                size += (*iter)->RequiredPhysicalSize(fileOffsetSize);
1391            return size;
1392        }
1393    
1394        void List::ReadHeader(file_offset_t filePos) {
1395            #if DEBUG_RIFF
1396            std::cout << "List::Readheader(file_offset_t) ";
1397            #endif // DEBUG_RIFF
1398            Chunk::ReadHeader(filePos);
1399            if (ullCurrentChunkSize < 4) return;
1400            ullNewChunkSize = ullCurrentChunkSize -= 4;
1401          #if POSIX          #if POSIX
1402          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1403          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1404          #elif defined(WIN32)          #elif defined(WIN32)
1405          SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          LARGE_INTEGER liFilePos;
1406            liFilePos.QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1407            SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1408          DWORD dwBytesRead;          DWORD dwBytesRead;
1409          ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);          ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1410          #else          #else
1411          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1412          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
1413          #endif // POSIX          #endif // POSIX
1414        #if DEBUG          #if DEBUG_RIFF
1415        std::cout << "listType=" << convertToString(ListType) << std::endl;          std::cout << "listType=" << convertToString(ListType) << std::endl;
1416        #endif // DEBUG          #endif // DEBUG_RIFF
1417          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
1418              //swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1419          }          }
1420      }      }
1421    
1422      void List::WriteHeader(unsigned long fPos) {      void List::WriteHeader(file_offset_t filePos) {
1423          // the four list type bytes officially belong the chunk's body in the RIFF format          // the four list type bytes officially belong the chunk's body in the RIFF format
1424          NewChunkSize += 4;          ullNewChunkSize += 4;
1425          Chunk::WriteHeader(fPos);          Chunk::WriteHeader(filePos);
1426          NewChunkSize -= 4; // just revert the +4 incrementation          ullNewChunkSize -= 4; // just revert the +4 incrementation
1427          #if POSIX          #if POSIX
1428          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1429          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1430          #elif defined(WIN32)          #elif defined(WIN32)
1431          SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          LARGE_INTEGER liFilePos;
1432            liFilePos.QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1433            SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1434          DWORD dwBytesWritten;          DWORD dwBytesWritten;
1435          WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);          WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1436          #else          #else
1437          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1438          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
1439          #endif // POSIX          #endif // POSIX
1440      }      }
1441    
1442      void List::LoadSubChunks() {      void List::LoadSubChunks(progress_t* pProgress) {
1443         #if DEBUG          #if DEBUG_RIFF
1444         std::cout << "List::LoadSubChunks()";          std::cout << "List::LoadSubChunks()";
1445         #endif // DEBUG          #endif // DEBUG_RIFF
1446          if (!pSubChunks) {          if (!pSubChunks) {
1447              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1448              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
# Line 1295  namespace RIFF { Line 1451  namespace RIFF {
1451              #else              #else
1452              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1453              #endif              #endif
1454              unsigned long uiOriginalPos = GetPos();              file_offset_t ullOriginalPos = GetPos();
1455              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1456              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE(pFile->FileOffsetSize)) {
1457                  Chunk* ck;                  Chunk* ck;
1458                  uint32_t ckid;                  uint32_t ckid;
1459                  Read(&ckid, 4, 1);                  Read(&ckid, 4, 1);
1460         #if DEBUG                  #if DEBUG_RIFF
1461         std::cout << " ckid=" << convertToString(ckid) << std::endl;                  std::cout << " ckid=" << convertToString(ckid) << std::endl;
1462         #endif // DEBUG                  #endif // DEBUG_RIFF
1463                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1464                      ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::List(pFile, ullStartPos + ullPos - 4, this);
1465                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1466                  }                  }
1467                  else { // simple chunk                  else { // simple chunk
1468                      ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::Chunk(pFile, ullStartPos + ullPos - 4, this);
1469                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1470                  }                  }
1471                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1472                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1473                  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
1474              }              }
1475              SetPos(uiOriginalPos); // restore position before this call              SetPos(ullOriginalPos); // restore position before this call
1476          }          }
1477            __notify_progress(pProgress, 1.0); // notify done
1478      }      }
1479    
1480      void List::LoadSubChunksRecursively() {      void List::LoadSubChunksRecursively(progress_t* pProgress) {
1481          for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())          const int n = (int) CountSubLists();
1482              pList->LoadSubChunksRecursively();          int i = 0;
1483            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList(), ++i) {
1484                // divide local progress into subprogress
1485                progress_t subprogress;
1486                __divide_progress(pProgress, &subprogress, n, i);
1487                // do the actual work
1488                pList->LoadSubChunksRecursively(&subprogress);
1489            }
1490            __notify_progress(pProgress, 1.0); // notify done
1491      }      }
1492    
1493      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
# Line 1331  namespace RIFF { Line 1496  namespace RIFF {
1496       * subchunks (including sub list chunks) will be stored recursively as       * subchunks (including sub list chunks) will be stored recursively as
1497       * well.       * well.
1498       *       *
1499       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
1500       *                     list chunk should be written to       *                     list chunk should be written to
1501       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
1502       *                              the file       *                              the file
1503         * @param pProgress - optional: callback function for progress notification
1504       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
1505       *          \a ulWritePos incremented by this list chunk's new size       *          \a ullWritePos incremented by this list chunk's new size
1506       *          (including its header size of course)       *          (including its header size of course)
1507       */       */
1508      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      file_offset_t List::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
1509          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
1510          ulWritePos += LIST_HEADER_SIZE;          ullWritePos += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1511    
1512          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
1513              throw Exception("Cannot write list chunk, file has to be opened in read+write mode");              throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1514    
1515          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1516          if (pSubChunks) {          if (pSubChunks) {
1517              for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {              size_t i = 0;
1518                  ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);              const size_t n = pSubChunks->size();
1519                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1520                    // divide local progress into subprogress for loading current Instrument
1521                    progress_t subprogress;
1522                    __divide_progress(pProgress, &subprogress, n, i);
1523                    // do the actual work
1524                    ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, &subprogress);
1525              }              }
1526          }          }
1527    
1528          // update this list chunk's header          // update this list chunk's header
1529          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          ullCurrentChunkSize = ullNewChunkSize = ullWritePos - ullOriginalPos - LIST_HEADER_SIZE(pFile->FileOffsetSize);
1530          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
1531    
1532          // offset of this list chunk in new written file may have changed          // offset of this list chunk in new written file may have changed
1533          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;          ullStartPos = ullOriginalPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1534    
1535             __notify_progress(pProgress, 1.0); // notify done
1536    
1537          return ulWritePos;          return ullWritePos;
1538      }      }
1539    
1540      void List::__resetPos() {      void List::__resetPos() {
# Line 1375  namespace RIFF { Line 1549  namespace RIFF {
1549      /**      /**
1550       *  Returns string representation of the lists's id       *  Returns string representation of the lists's id
1551       */       */
1552      String List::GetListTypeString() {      String List::GetListTypeString() const {
1553          return convertToString(ListType);          return convertToString(ListType);
1554      }      }
1555    
# Line 1384  namespace RIFF { Line 1558  namespace RIFF {
1558  // *************** File ***************  // *************** File ***************
1559  // *  // *
1560    
 //HACK: to avoid breaking DLL compatibility to older versions of libgig we roll the new std::set<Chunk*> into the old std::list<Chunk*> container, should be replaced on member variable level soon though  
 #define _GET_RESIZED_CHUNKS() \  
         (reinterpret_cast<std::set<Chunk*>*>(ResizedChunks.front()))  
   
1561      /** @brief Create new RIFF file.      /** @brief Create new RIFF file.
1562       *       *
1563       * Use this constructor if you want to create a new RIFF file completely       * Use this constructor if you want to create a new RIFF file completely
# Line 1402  namespace RIFF { Line 1572  namespace RIFF {
1572       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1573       * @see AddSubChunk(), AddSubList(), SetByteOrder()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1574       */       */
1575      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType)
1576          //HACK: see _GET_RESIZED_CHUNKS() comment          : List(this), bIsNewFile(true), Layout(layout_standard),
1577          ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));            FileOffsetPreference(offset_size_auto)
1578        {
1579          #if defined(WIN32)          #if defined(WIN32)
1580          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1581          #else          #else
# Line 1412  namespace RIFF { Line 1583  namespace RIFF {
1583          #endif          #endif
1584          Mode = stream_mode_closed;          Mode = stream_mode_closed;
1585          bEndianNative = true;          bEndianNative = true;
         ulStartPos = RIFF_HEADER_SIZE;  
1586          ListType = FileType;          ListType = FileType;
1587            FileOffsetSize = 4;
1588            ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1589      }      }
1590    
1591      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1421  namespace RIFF { Line 1593  namespace RIFF {
1593       * Loads an existing RIFF file with all its chunks.       * Loads an existing RIFF file with all its chunks.
1594       *       *
1595       * @param path - path and file name of the RIFF file to open       * @param path - path and file name of the RIFF file to open
1596       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occurred while trying to load the
1597       *                         given RIFF file       *                         given RIFF file
1598       */       */
1599      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path)
1600         #if DEBUG          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard),
1601         std::cout << "File::File("<<path<<")" << std::endl;            FileOffsetPreference(offset_size_auto)
1602         #endif // DEBUG      {
1603            #if DEBUG_RIFF
1604            std::cout << "File::File("<<path<<")" << std::endl;
1605            #endif // DEBUG_RIFF
1606            bEndianNative = true;
1607            FileOffsetSize = 4;
1608          try {          try {
1609              bEndianNative = true;              __openExistingFile(path);
             //HACK: see _GET_RESIZED_CHUNKS() comment  
             ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));  
             #if POSIX  
             hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);  
             if (hFileRead <= 0) {  
                 hFileRead = hFileWrite = 0;  
                 throw RIFF::Exception("Can't open \"" + path + "\"");  
             }  
             #elif defined(WIN32)  
             hFileRead = hFileWrite = CreateFile(  
                                          path.c_str(), GENERIC_READ,  
                                          FILE_SHARE_READ | FILE_SHARE_WRITE,  
                                          NULL, OPEN_EXISTING,  
                                          FILE_ATTRIBUTE_NORMAL |  
                                          FILE_FLAG_RANDOM_ACCESS, NULL  
                                      );  
             if (hFileRead == INVALID_HANDLE_VALUE) {  
                 hFileRead = hFileWrite = INVALID_HANDLE_VALUE;  
                 throw RIFF::Exception("Can't open \"" + path + "\"");  
             }  
             #else  
             hFileRead = hFileWrite = fopen(path.c_str(), "rb");  
             if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");  
             #endif // POSIX  
             Mode = stream_mode_read;  
             ulStartPos = RIFF_HEADER_SIZE;  
             ReadHeader(0);  
1610              if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {              if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1611                  throw RIFF::Exception("Not a RIFF file");                  throw RIFF::Exception("Not a RIFF file");
1612              }              }
# Line 1467  namespace RIFF { Line 1617  namespace RIFF {
1617          }          }
1618      }      }
1619    
1620      String File::GetFileName() {      /** @brief Load existing RIFF-like file.
1621         *
1622         * Loads an existing file, which is not a "real" RIFF file, but similar to
1623         * an ordinary RIFF file.
1624         *
1625         * A "real" RIFF file contains at top level a List chunk either with chunk
1626         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1627         * case, and if it finds the toplevel List chunk to have another chunk ID
1628         * than one of those two expected ones, it would throw an Exception and
1629         * would refuse to load the file accordingly.
1630         *
1631         * Since there are however a lot of file formats which use the same simple
1632         * principles of the RIFF format, with another toplevel List chunk ID
1633         * though, you can use this alternative constructor here to be able to load
1634         * and handle those files in the same way as you would do with "real" RIFF
1635         * files.
1636         *
1637         * @param path - path and file name of the RIFF-alike file to be opened
1638         * @param FileType - expected toplevel List chunk ID (this is the very
1639         *                   first chunk found in the file)
1640         * @param Endian - whether the file uses little endian or big endian layout
1641         * @param layout - general file structure type
1642         * @param fileOffsetSize - (optional) preference how to deal with large files
1643         * @throws RIFF::Exception if error occurred while trying to load the
1644         *                         given RIFF-alike file
1645         */
1646        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout, offset_size_t fileOffsetSize)
1647            : List(this), Filename(path), bIsNewFile(false), Layout(layout),
1648              FileOffsetPreference(fileOffsetSize)
1649        {
1650            SetByteOrder(Endian);
1651            if (fileOffsetSize < offset_size_auto || fileOffsetSize > offset_size_64bit)
1652                throw Exception("Invalid RIFF::offset_size_t");
1653            FileOffsetSize = 4;
1654            try {
1655                __openExistingFile(path, &FileType);
1656            }
1657            catch (...) {
1658                Cleanup();
1659                throw;
1660            }
1661        }
1662    
1663        /**
1664         * Opens an already existing RIFF file or RIFF-alike file. This method
1665         * shall only be called once (in a File class constructor).
1666         *
1667         * @param path - path and file name of the RIFF file or RIFF-alike file to
1668         *               be opened
1669         * @param FileType - (optional) expected chunk ID of first chunk in file
1670         * @throws RIFF::Exception if error occurred while trying to load the
1671         *                         given RIFF file or RIFF-alike file
1672         */
1673        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1674            #if POSIX
1675            hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1676            if (hFileRead == -1) {
1677                hFileRead = hFileWrite = 0;
1678                String sError = strerror(errno);
1679                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1680            }
1681            #elif defined(WIN32)
1682            hFileRead = hFileWrite = CreateFile(
1683                                         path.c_str(), GENERIC_READ,
1684                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1685                                         NULL, OPEN_EXISTING,
1686                                         FILE_ATTRIBUTE_NORMAL |
1687                                         FILE_FLAG_RANDOM_ACCESS, NULL
1688                                     );
1689            if (hFileRead == INVALID_HANDLE_VALUE) {
1690                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1691                throw RIFF::Exception("Can't open \"" + path + "\"");
1692            }
1693            #else
1694            hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1695            if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1696            #endif // POSIX
1697            Mode = stream_mode_read;
1698    
1699            // determine RIFF file offset size to be used (in RIFF chunk headers)
1700            // according to the current file offset preference
1701            FileOffsetSize = FileOffsetSizeFor(GetCurrentFileSize());
1702    
1703            switch (Layout) {
1704                case layout_standard: // this is a normal RIFF file
1705                    ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1706                    ReadHeader(0);
1707                    if (FileType && ChunkID != *FileType)
1708                        throw RIFF::Exception("Invalid file container ID");
1709                    break;
1710                case layout_flat: // non-standard RIFF-alike file
1711                    ullStartPos = 0;
1712                    ullNewChunkSize = ullCurrentChunkSize = GetCurrentFileSize();
1713                    if (FileType) {
1714                        uint32_t ckid;
1715                        if (Read(&ckid, 4, 1) != 4) {
1716                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1717                        } else if (ckid != *FileType) {
1718                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1719                            throw RIFF::Exception("Invalid file header ID" + s);
1720                        }
1721                        SetPos(0); // reset to first byte of file
1722                    }
1723                    LoadSubChunks();
1724                    break;
1725            }
1726        }
1727    
1728        String File::GetFileName() const {
1729          return Filename;          return Filename;
1730      }      }
1731        
1732        void File::SetFileName(const String& path) {
1733            Filename = path;
1734        }
1735    
1736      stream_mode_t File::GetMode() {      stream_mode_t File::GetMode() const {
1737          return Mode;          return Mode;
1738      }      }
1739    
1740        layout_t File::GetLayout() const {
1741            return Layout;
1742        }
1743    
1744      /** @brief Change file access mode.      /** @brief Change file access mode.
1745       *       *
1746       * Changes files access mode either to read-only mode or to read/write       * Changes files access mode either to read-only mode or to read/write
# Line 1492  namespace RIFF { Line 1758  namespace RIFF {
1758                      #if POSIX                      #if POSIX
1759                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1760                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1761                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1762                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1763                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          String sError = strerror(errno);
1764                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1765                      }                      }
1766                      #elif defined(WIN32)                      #elif defined(WIN32)
1767                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1521  namespace RIFF { Line 1788  namespace RIFF {
1788                      #if POSIX                      #if POSIX
1789                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1790                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1791                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1792                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1793                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          String sError = strerror(errno);
1794                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1795                      }                      }
1796                      #elif defined(WIN32)                      #elif defined(WIN32)
1797                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1561  namespace RIFF { Line 1829  namespace RIFF {
1829                      #if POSIX                      #if POSIX
1830                      if (hFileRead)  close(hFileRead);                      if (hFileRead)  close(hFileRead);
1831                      if (hFileWrite) close(hFileWrite);                      if (hFileWrite) close(hFileWrite);
1832                        hFileRead = hFileWrite = 0;
1833                      #elif defined(WIN32)                      #elif defined(WIN32)
1834                      if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1835                      if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);                      if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1836                        hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1837                      #else                      #else
1838                      if (hFileRead)  fclose(hFileRead);                      if (hFileRead)  fclose(hFileRead);
1839                      if (hFileWrite) fclose(hFileWrite);                      if (hFileWrite) fclose(hFileWrite);
1840                        hFileRead = hFileWrite = NULL;
1841                      #endif                      #endif
                     hFileRead = hFileWrite = 0;  
1842                      break;                      break;
1843                  default:                  default:
1844                      throw Exception("Unknown file access mode");                      throw Exception("Unknown file access mode");
# Line 1599  namespace RIFF { Line 1869  namespace RIFF {
1869      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1870       *       *
1871       * Make all changes of all chunks persistent by writing them to the       * Make all changes of all chunks persistent by writing them to the
1872       * actual (same) file. The file might temporarily grow to a higher size       * actual (same) file.
      * than it will have at the end of the saving process, in case chunks  
      * were grown.  
1873       *       *
1874         * @param pProgress - optional: callback function for progress notification
1875       * @throws RIFF::Exception if there is an empty chunk or empty list       * @throws RIFF::Exception if there is an empty chunk or empty list
1876       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occurred
1877       */       */
1878      void File::Save() {      void File::Save(progress_t* pProgress) {
1879            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1880            if (Layout == layout_flat)
1881                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1882    
1883          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1884          LoadSubChunksRecursively();          {
1885                // divide progress into subprogress
1886                progress_t subprogress;
1887                __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
1888                // do the actual work
1889                LoadSubChunksRecursively(&subprogress);
1890                // notify subprogress done
1891                __notify_progress(&subprogress, 1.f);
1892            }
1893    
1894          // reopen file in write mode          // reopen file in write mode
1895          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1896    
1897            // get the current file size as it is now still physically stored on disk
1898            const file_offset_t workingFileSize = GetCurrentFileSize();
1899    
1900            // get the overall file size required to save this file
1901            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1902    
1903            // determine whether this file will yield in a large file (>=4GB) and
1904            // the RIFF file offset size to be used accordingly for all chunks
1905            FileOffsetSize = FileOffsetSizeFor(newFileSize);
1906    
1907          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
1908          // RAM and without having to store the data in a temporary file, we          // RAM and without having to store the data in a temporary file, we
1909          // enlarge the file with the sum of all _positive_ chunk size          // enlarge the file with the overall positive file size change,
1910          // changes, move current data towards the end of the file with the          // then move current data towards the end of the file by the calculated
1911          // calculated sum and finally update / rewrite the file by copying          // positive file size difference and finally update / rewrite the file
1912          // the old data back to the right position at the beginning of the file          // by copying the old data back to the right position at the beginning
1913            // of the file
         // first we sum up all positive chunk size changes (and skip all negative ones)  
         unsigned long ulPositiveSizeDiff = 0;  
         std::set<Chunk*>* resizedChunks = _GET_RESIZED_CHUNKS();  
         for (std::set<Chunk*>::const_iterator iter = resizedChunks->begin(), end = resizedChunks->end(); iter != end; ++iter) {  
             if ((*iter)->GetNewSize() == 0) {  
                 throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));  
             }  
             unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;  
             unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;  
             if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;  
         }  
   
         unsigned long ulWorkingFileSize = GetFileSize();  
1914    
1915          // if there are positive size changes...          // if there are positive size changes...
1916          if (ulPositiveSizeDiff > 0) {          file_offset_t positiveSizeDiff = 0;
1917            if (newFileSize > workingFileSize) {
1918                positiveSizeDiff = newFileSize - workingFileSize;
1919    
1920                // divide progress into subprogress
1921                progress_t subprogress;
1922                __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1923    
1924              // ... we enlarge this file first ...              // ... we enlarge this file first ...
1925              ulWorkingFileSize += ulPositiveSizeDiff;              ResizeFile(newFileSize);
1926              ResizeFile(ulWorkingFileSize);  
1927              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1928              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
             const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;  
1929              #if defined(WIN32)              #if defined(WIN32)
1930              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1931              #else              #else
1932              int iBytesMoved = 1;              ssize_t iBytesMoved = 1;
1933              #endif              #endif
1934              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {              for (file_offset_t ullPos = workingFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1935                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;                  iBytesMoved = (ullPos < 4096) ? ullPos : 4096;
1936                  ulPos -= iBytesMoved;                  ullPos -= iBytesMoved;
1937                  #if POSIX                  #if POSIX
1938                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ullPos, SEEK_SET);
1939                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1940                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1941                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1942                  #elif defined(WIN32)                  #elif defined(WIN32)
1943                  SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);                  LARGE_INTEGER liFilePos;
1944                    liFilePos.QuadPart = ullPos;
1945                    SetFilePointerEx(hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1946                  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1947                  SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);                  liFilePos.QuadPart = ullPos + positiveSizeDiff;
1948                    SetFilePointerEx(hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1949                  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1950                  #else                  #else
1951                  fseek(hFileRead, ulPos, SEEK_SET);                  fseeko(hFileRead, ullPos, SEEK_SET);
1952                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1953                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  fseeko(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1954                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1955                  #endif                  #endif
1956                    if (!(iNotif % 8) && iBytesMoved > 0)
1957                        __notify_progress(&subprogress, float(workingFileSize - ullPos) / float(workingFileSize));
1958              }              }
1959              delete[] pCopyBuffer;              delete[] pCopyBuffer;
1960              if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");              if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1961    
1962                __notify_progress(&subprogress, 1.f); // notify subprogress done
1963          }          }
1964    
1965          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree ...
1966          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);  
1967          unsigned long ulActualSize = __GetFileSize(hFileWrite);          // divide progress into subprogress
1968            progress_t subprogress;
1969            __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
1970            // do the actual work
1971            const file_offset_t finalSize = WriteChunk(0, positiveSizeDiff, &subprogress);
1972            const file_offset_t finalActualSize = __GetFileSize(hFileWrite);
1973            // notify subprogress done
1974            __notify_progress(&subprogress, 1.f);
1975    
1976          // resize file to the final size          // resize file to the final size
1977          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (finalSize < finalActualSize) ResizeFile(finalSize);
1978    
1979          // forget all resized chunks          __notify_progress(pProgress, 1.0); // notify done
         resizedChunks->clear();  
1980      }      }
1981    
1982      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1694  namespace RIFF { Line 1991  namespace RIFF {
1991       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
1992       *       *
1993       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1994         * @param pProgress - optional: callback function for progress notification
1995       */       */
1996      void File::Save(const String& path) {      void File::Save(const String& path, progress_t* pProgress) {
1997          //TODO: we should make a check here if somebody tries to write to the same file and automatically call the other Save() method in that case          //TODO: we should make a check here if somebody tries to write to the same file and automatically call the other Save() method in that case
1998    
1999            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
2000            if (Layout == layout_flat)
2001                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
2002    
2003          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
2004          LoadSubChunksRecursively();          {
2005                // divide progress into subprogress
2006                progress_t subprogress;
2007                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
2008                // do the actual work
2009                LoadSubChunksRecursively(&subprogress);
2010                // notify subprogress done
2011                __notify_progress(&subprogress, 1.f);
2012            }
2013    
2014          if (Filename.length() > 0) SetMode(stream_mode_read);          if (!bIsNewFile) SetMode(stream_mode_read);
2015          // open the other (new) file for writing and truncate it to zero size          // open the other (new) file for writing and truncate it to zero size
2016          #if POSIX          #if POSIX
2017          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
2018          if (hFileWrite < 0) {          if (hFileWrite == -1) {
2019              hFileWrite = hFileRead;              hFileWrite = hFileRead;
2020              throw Exception("Could not open file \"" + path + "\" for writing");              String sError = strerror(errno);
2021                throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
2022          }          }
2023          #elif defined(WIN32)          #elif defined(WIN32)
2024          hFileWrite = CreateFile(          hFileWrite = CreateFile(
# Line 1728  namespace RIFF { Line 2039  namespace RIFF {
2039          #endif // POSIX          #endif // POSIX
2040          Mode = stream_mode_read_write;          Mode = stream_mode_read_write;
2041    
2042            // get the overall file size required to save this file
2043            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
2044    
2045            // determine whether this file will yield in a large file (>=4GB) and
2046            // the RIFF file offset size to be used accordingly for all chunks
2047            FileOffsetSize = FileOffsetSizeFor(newFileSize);
2048    
2049          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
2050          unsigned long ulTotalSize  = WriteChunk(0, 0);          file_offset_t ullTotalSize;
2051          unsigned long ulActualSize = __GetFileSize(hFileWrite);          {
2052                // divide progress into subprogress
2053                progress_t subprogress;
2054                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
2055                // do the actual work
2056                ullTotalSize = WriteChunk(0, 0, &subprogress);
2057                // notify subprogress done
2058                __notify_progress(&subprogress, 1.f);
2059            }
2060            file_offset_t ullActualSize = __GetFileSize(hFileWrite);
2061    
2062          // resize file to the final size (if the file was originally larger)          // resize file to the final size (if the file was originally larger)
2063          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ullActualSize > ullTotalSize) ResizeFile(ullTotalSize);
   
         // forget all resized chunks  
         _GET_RESIZED_CHUNKS()->clear();  
2064    
2065          #if POSIX          #if POSIX
2066          if (hFileWrite) close(hFileWrite);          if (hFileWrite) close(hFileWrite);
# Line 1749  namespace RIFF { Line 2073  namespace RIFF {
2073    
2074          // associate new file with this File object from now on          // associate new file with this File object from now on
2075          Filename = path;          Filename = path;
2076            bIsNewFile = false;
2077          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
2078          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
2079    
2080            __notify_progress(pProgress, 1.0); // notify done
2081      }      }
2082    
2083      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(file_offset_t ullNewSize) {
2084          #if POSIX          #if POSIX
2085          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ullNewSize) < 0)
2086              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
2087          #elif defined(WIN32)          #elif defined(WIN32)
2088            LARGE_INTEGER liFilePos;
2089            liFilePos.QuadPart = ullNewSize;
2090          if (          if (
2091              SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||              !SetFilePointerEx(hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN) ||
2092              !SetEndOfFile(hFileWrite)              !SetEndOfFile(hFileWrite)
2093          ) throw Exception("Could not resize file \"" + Filename + "\"");          ) throw Exception("Could not resize file \"" + Filename + "\"");
2094          #else          #else
# Line 1769  namespace RIFF { Line 2098  namespace RIFF {
2098      }      }
2099    
2100      File::~File() {      File::~File() {
2101         #if DEBUG          #if DEBUG_RIFF
2102         std::cout << "File::~File()" << std::endl;          std::cout << "File::~File()" << std::endl;
2103         #endif // DEBUG          #endif // DEBUG_RIFF
2104          Cleanup();          Cleanup();
2105      }      }
2106    
2107        /**
2108         * Returns @c true if this file has been created new from scratch and
2109         * has not been stored to disk yet.
2110         */
2111        bool File::IsNew() const {
2112            return bIsNewFile;
2113        }
2114    
2115      void File::Cleanup() {      void File::Cleanup() {
2116          #if POSIX          #if POSIX
2117          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
# Line 1785  namespace RIFF { Line 2122  namespace RIFF {
2122          #endif // POSIX          #endif // POSIX
2123          DeleteChunkList();          DeleteChunkList();
2124          pFile = NULL;          pFile = NULL;
         //HACK: see _GET_RESIZED_CHUNKS() comment  
         delete _GET_RESIZED_CHUNKS();  
2125      }      }
2126    
2127      void File::LogAsResized(Chunk* pResizedChunk) {      /**
2128          _GET_RESIZED_CHUNKS()->insert(pResizedChunk);       * Returns the current size of this file (in bytes) as it is currently
2129         * yet stored on disk. If this file does not yet exist on disk (i.e. when
2130         * this RIFF File has just been created from scratch and Save() has not
2131         * been called yet) then this method returns 0.
2132         */
2133        file_offset_t File::GetCurrentFileSize() const {
2134            file_offset_t size = 0;
2135            try {
2136                size = __GetFileSize(hFileRead);
2137            } catch (...) {
2138                size = 0;
2139            }
2140            return size;
2141        }
2142    
2143        /**
2144         * Returns the required size (in bytes) for this RIFF File to be saved to
2145         * disk. The precise size of the final file on disk depends on the RIFF
2146         * file offset size actually used internally in all headers of the RIFF
2147         * chunks. By default libgig handles the required file offset size
2148         * automatically for you; that means it is using 32 bit offsets for files
2149         * smaller than 4 GB and 64 bit offsets for files equal or larger than
2150         * 4 GB. You may however also override this default behavior by passing the
2151         * respective option to the RIFF File constructor to force one particular
2152         * offset size. In the latter case this method will return the file size
2153         * for the requested forced file offset size that will be used when calling
2154         * Save() later on.
2155         *
2156         * You may also use the overridden method below to get the file size for
2157         * an arbitrary other file offset size instead.
2158         *
2159         * @see offset_size_t
2160         * @see GetFileOffsetSize()
2161         */
2162        file_offset_t File::GetRequiredFileSize() {
2163            return GetRequiredFileSize(FileOffsetPreference);
2164        }
2165    
2166        /**
2167         * Returns the rquired size (in bytes) for this RIFF file to be saved to
2168         * disk, assuming the passed @a fileOffsestSize would be used for the
2169         * Save() operation.
2170         *
2171         * This overridden method essentialy behaves like the above method, with
2172         * the difference that you must provide a specific RIFF @a fileOffsetSize
2173         * for calculating the theoretical final file size.
2174         *
2175         * @see GetFileOffsetSize()
2176         */
2177        file_offset_t File::GetRequiredFileSize(offset_size_t fileOffsetSize) {
2178            switch (fileOffsetSize) {
2179                case offset_size_auto: {
2180                    file_offset_t fileSize = GetRequiredFileSize(offset_size_32bit);
2181                    if (fileSize >> 32)
2182                        return GetRequiredFileSize(offset_size_64bit);
2183                    else
2184                        return fileSize;
2185                }
2186                case offset_size_32bit: break;
2187                case offset_size_64bit: break;
2188                default: throw Exception("Internal error: Invalid RIFF::offset_size_t");
2189            }
2190            return RequiredPhysicalSize(FileOffsetSize);
2191        }
2192    
2193        int File::FileOffsetSizeFor(file_offset_t fileSize) const {
2194            switch (FileOffsetPreference) {
2195                case offset_size_auto:
2196                    return (fileSize >> 32) ? 8 : 4;
2197                case offset_size_32bit:
2198                    return 4;
2199                case offset_size_64bit:
2200                    return 8;
2201                default:
2202                    throw Exception("Internal error: Invalid RIFF::offset_size_t");
2203            }
2204      }      }
2205    
2206      void File::UnlogResized(Chunk* pResizedChunk) {      /**
2207          _GET_RESIZED_CHUNKS()->erase(pResizedChunk);       * Returns the current size (in bytes) of file offsets stored in the
2208         * headers of all chunks of this file.
2209         *
2210         * Most RIFF files are using 32 bit file offsets internally, which limits
2211         * them to a maximum file size of less than 4 GB though. In contrast to the
2212         * common standard, this RIFF File class implementation supports handling of
2213         * RIFF files equal or larger than 4 GB. In such cases 64 bit file offsets
2214         * have to be used in all headers of all RIFF Chunks when being stored to a
2215         * physical file. libgig by default automatically selects the correct file
2216         * offset size for you. You may however also force one particular file
2217         * offset size by supplying the respective option to the RIFF::File
2218         * constructor.
2219         *
2220         * This method can be used to check which RIFF file offset size is currently
2221         * being used for this RIFF File.
2222         *
2223         * @returns current RIFF file offset size used (in bytes)
2224         * @see offset_size_t
2225         */
2226        int File::GetFileOffsetSize() const {
2227            return FileOffsetSize;
2228      }      }
2229    
2230      unsigned long File::GetFileSize() {      /**
2231          return __GetFileSize(hFileRead);       * Returns the required size (in bytes) of file offsets stored in the
2232         * headers of all chunks of this file if the current RIFF tree would be
2233         * saved to disk by calling Save().
2234         *
2235         * See GetFileOffsetSize() for mor details about RIFF file offsets.
2236         *
2237         * @returns RIFF file offset size required (in bytes) if being saved
2238         * @see offset_size_t
2239         */
2240        int File::GetRequiredFileOffsetSize() {
2241            return FileOffsetSizeFor(GetCurrentFileSize());
2242      }      }
2243    
2244      #if POSIX      #if POSIX
2245      unsigned long File::__GetFileSize(int hFile) {      file_offset_t File::__GetFileSize(int hFile) const {
2246          struct stat filestat;          struct stat filestat;
2247          fstat(hFile, &filestat);          if (fstat(hFile, &filestat) == -1)
2248          long size = filestat.st_size;              throw Exception("POSIX FS error: could not determine file size");
2249          return size;          return filestat.st_size;
2250      }      }
2251      #elif defined(WIN32)      #elif defined(WIN32)
2252      unsigned long File::__GetFileSize(HANDLE hFile) {      file_offset_t File::__GetFileSize(HANDLE hFile) const {
2253          DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);          LARGE_INTEGER size;
2254          if (dwSize == INVALID_FILE_SIZE)          if (!GetFileSizeEx(hFile, &size))
2255              throw Exception("Windows FS error: could not determine file size");              throw Exception("Windows FS error: could not determine file size");
2256          return dwSize;          return size.QuadPart;
2257      }      }
2258      #else // standard C functions      #else // standard C functions
2259      unsigned long File::__GetFileSize(FILE* hFile) {      file_offset_t File::__GetFileSize(FILE* hFile) const {
2260          long curpos = ftell(hFile);          off_t curpos = ftello(hFile);
2261          fseek(hFile, 0, SEEK_END);          if (fseeko(hFile, 0, SEEK_END) == -1)
2262          long size = ftell(hFile);              throw Exception("FS error: could not determine file size");
2263          fseek(hFile, curpos, SEEK_SET);          off_t size = ftello(hFile);
2264            fseeko(hFile, curpos, SEEK_SET);
2265          return size;          return size;
2266      }      }
2267      #endif      #endif
# Line 1829  namespace RIFF { Line 2270  namespace RIFF {
2270  // *************** Exception ***************  // *************** Exception ***************
2271  // *  // *
2272    
2273        Exception::Exception() {
2274        }
2275    
2276        Exception::Exception(String format, ...) {
2277            va_list arg;
2278            va_start(arg, format);
2279            Message = assemble(format, arg);
2280            va_end(arg);
2281        }
2282    
2283        Exception::Exception(String format, va_list arg) {
2284            Message = assemble(format, arg);
2285        }
2286    
2287      void Exception::PrintMessage() {      void Exception::PrintMessage() {
2288          std::cout << "RIFF::Exception: " << Message << std::endl;          std::cout << "RIFF::Exception: " << Message << std::endl;
2289      }      }
2290    
2291        String Exception::assemble(String format, va_list arg) {
2292            char* buf = NULL;
2293            vasprintf(&buf, format.c_str(), arg);
2294            String s = buf;
2295            free(buf);
2296            return s;
2297        }
2298    
2299    
2300  // *************** functions ***************  // *************** functions ***************
2301  // *  // *

Legend:
Removed from v.2155  
changed lines
  Added in v.3478

  ViewVC Help
Powered by ViewVC