/[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 1885 by persson, Thu Apr 16 18:25:31 2009 UTC revision 2914 by schoenebeck, Tue May 17 19:04:56 2016 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-2009 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2016 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 22  Line 22 
22   ***************************************************************************/   ***************************************************************************/
23    
24  #include <algorithm>  #include <algorithm>
25    #include <set>
26  #include <string.h>  #include <string.h>
27    
28  #include "RIFF.h"  #include "RIFF.h"
29    
30  #include "helper.h"  #include "helper.h"
31    
32    #if POSIX
33    # include <errno.h>
34    #endif
35    
36  namespace RIFF {  namespace RIFF {
37    
38  // *************** Internal functions **************  // *************** Internal functions **************
# Line 49  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    
69  // *************** Chunk **************  // *************** Chunk **************
70  // *  // *
71    
# Line 56  namespace RIFF { Line 73  namespace RIFF {
73          #if DEBUG          #if DEBUG
74          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
75          #endif // DEBUG          #endif // DEBUG
76          ulPos      = 0;          ullPos     = 0;
77          pParent    = NULL;          pParent    = NULL;
78          pChunkData = NULL;          pChunkData = NULL;
79          CurrentChunkSize = 0;          ullCurrentChunkSize = 0;
80          NewChunkSize = 0;          ullNewChunkSize = 0;
81          ulChunkDataSize = 0;          ullChunkDataSize = 0;
82          ChunkID    = CHUNK_ID_RIFF;          ChunkID    = CHUNK_ID_RIFF;
83          this->pFile = pFile;          this->pFile = pFile;
84      }      }
85    
86      Chunk::Chunk(File* pFile, unsigned long StartPos, List* Parent) {      Chunk::Chunk(File* pFile, file_offset_t StartPos, List* Parent) {
87          #if DEBUG          #if DEBUG
88          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;
89          #endif // DEBUG          #endif // DEBUG
90          this->pFile   = pFile;          this->pFile   = pFile;
91          ulStartPos    = StartPos + CHUNK_HEADER_SIZE;          ullStartPos   = StartPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
92          pParent       = Parent;          pParent       = Parent;
93          ulPos         = 0;          ullPos        = 0;
94          pChunkData    = NULL;          pChunkData    = NULL;
95          CurrentChunkSize = 0;          ullCurrentChunkSize = 0;
96          NewChunkSize = 0;          ullNewChunkSize = 0;
97          ulChunkDataSize = 0;          ullChunkDataSize = 0;
98          ReadHeader(StartPos);          ReadHeader(StartPos);
99      }      }
100    
101      Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, uint uiBodySize) {      Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, file_offset_t ullBodySize) {
102          this->pFile      = pFile;          this->pFile      = pFile;
103          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
104          this->pParent    = pParent;          this->pParent    = pParent;
105          ulPos            = 0;          ullPos           = 0;
106          pChunkData       = NULL;          pChunkData       = NULL;
107          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
108          ulChunkDataSize  = 0;          ullChunkDataSize = 0;
109          CurrentChunkSize = 0;          ullCurrentChunkSize = 0;
110          NewChunkSize     = uiBodySize;          ullNewChunkSize  = ullBodySize;
111      }      }
112    
113      Chunk::~Chunk() {      Chunk::~Chunk() {
         if (pFile) pFile->UnlogResized(this);  
114          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
115      }      }
116    
117      void Chunk::ReadHeader(unsigned long fPos) {      void Chunk::ReadHeader(file_offset_t filePos) {
118          #if DEBUG          #if DEBUG
119          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << filePos << ") ";
120          #endif // DEBUG          #endif // DEBUG
121          ChunkID = 0;          ChunkID = 0;
122          NewChunkSize = CurrentChunkSize = 0;          ullNewChunkSize = ullCurrentChunkSize = 0;
123          #if POSIX          #if POSIX
124          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, filePos, SEEK_SET) != -1) {
125              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
126              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize);
127          #elif defined(WIN32)          #elif defined(WIN32)
128          if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {          const LARGE_INTEGER liFilePos = { .QuadPart = filePos };
129            if (SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
130              DWORD dwBytesRead;              DWORD dwBytesRead;
131              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
132              ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);              ReadFile(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize, &dwBytesRead, NULL);
133          #else          #else
134          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseeko(pFile->hFileRead, filePos, SEEK_SET)) {
135              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
136              fread(&CurrentChunkSize, 4, 1, pFile->hFileRead);              fread(&ullCurrentChunkSize, pFile->FileOffsetSize, 1, pFile->hFileRead);
137          #endif // POSIX          #endif // POSIX
138              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
139              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
# Line 130  namespace RIFF { Line 147  namespace RIFF {
147              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
148              if (!pFile->bEndianNative) {              if (!pFile->bEndianNative) {
149                  //swapBytes_32(&ChunkID);                  //swapBytes_32(&ChunkID);
150                  swapBytes_32(&CurrentChunkSize);                  if (pFile->FileOffsetSize == 4)
151                        swapBytes_32(&ullCurrentChunkSize);
152                    else
153                        swapBytes_64(&ullCurrentChunkSize);
154              }              }
155              #if DEBUG              #if DEBUG
156              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
157              std::cout << "ckSize=" << CurrentChunkSize << " ";              std::cout << "ckSize=" << ullCurrentChunkSize << " ";
158              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
159              #endif // DEBUG              #endif // DEBUG
160              NewChunkSize = CurrentChunkSize;              ullNewChunkSize = ullCurrentChunkSize;
161          }          }
162      }      }
163    
164      void Chunk::WriteHeader(unsigned long fPos) {      void Chunk::WriteHeader(file_offset_t filePos) {
165          uint32_t uiNewChunkID = ChunkID;          uint32_t uiNewChunkID = ChunkID;
166          if (ChunkID == CHUNK_ID_RIFF) {          if (ChunkID == CHUNK_ID_RIFF) {
167              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
# Line 151  namespace RIFF { Line 171  namespace RIFF {
171              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
172          }          }
173    
174          uint32_t uiNewChunkSize = NewChunkSize;          uint64_t ullNewChunkSize = this->ullNewChunkSize;
175          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
176              swapBytes_32(&uiNewChunkSize);              if (pFile->FileOffsetSize == 4)
177                    swapBytes_32(&ullNewChunkSize);
178                else
179                    swapBytes_64(&ullNewChunkSize);
180          }          }
181    
182          #if POSIX          #if POSIX
183          if (lseek(pFile->hFileWrite, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileWrite, filePos, SEEK_SET) != -1) {
184              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
185              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize);
186          }          }
187          #elif defined(WIN32)          #elif defined(WIN32)
188          if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {          const LARGE_INTEGER liFilePos = { .QuadPart = filePos };
189            if (SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
190              DWORD dwBytesWritten;              DWORD dwBytesWritten;
191              WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
192              WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize, &dwBytesWritten, NULL);
193          }          }
194          #else          #else
195          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseeko(pFile->hFileWrite, filePos, SEEK_SET)) {
196              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
197              fwrite(&uiNewChunkSize, 4, 1, pFile->hFileWrite);              fwrite(&ullNewChunkSize, pFile->FileOffsetSize, 1, pFile->hFileWrite);
198          }          }
199          #endif // POSIX          #endif // POSIX
200      }      }
# Line 179  namespace RIFF { Line 203  namespace RIFF {
203       *  Returns the String representation of the chunk's ID (e.g. "RIFF",       *  Returns the String representation of the chunk's ID (e.g. "RIFF",
204       *  "LIST").       *  "LIST").
205       */       */
206      String Chunk::GetChunkIDString() {      String Chunk::GetChunkIDString() const {
207          return convertToString(ChunkID);          return convertToString(ChunkID);
208      }      }
209    
# Line 195  namespace RIFF { Line 219  namespace RIFF {
219       *                  if omitted \a Where relates to beginning of the chunk       *                  if omitted \a Where relates to beginning of the chunk
220       *                  data       *                  data
221       */       */
222      unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {      file_offset_t Chunk::SetPos(file_offset_t Where, stream_whence_t Whence) {
223       #if DEBUG          #if DEBUG
224       std::cout << "Chunk::SetPos(ulong)" << std::endl;          std::cout << "Chunk::SetPos(file_offset_t,stream_whence_t)" << std::endl;
225       #endif // DEBUG          #endif // DEBUG
226          switch (Whence) {          switch (Whence) {
227              case stream_curpos:              case stream_curpos:
228                  ulPos += Where;                  ullPos += Where;
229                  break;                  break;
230              case stream_end:              case stream_end:
231                  ulPos = CurrentChunkSize - 1 - Where;                  ullPos = ullCurrentChunkSize - 1 - Where;
232                  break;                  break;
233              case stream_backward:              case stream_backward:
234                  ulPos -= Where;                  ullPos -= Where;
235                  break;                  break;
236              case stream_start: default:              case stream_start: default:
237                  ulPos = Where;                  ullPos = Where;
238                  break;                  break;
239          }          }
240          if (ulPos > CurrentChunkSize) ulPos = CurrentChunkSize;          if (ullPos > ullCurrentChunkSize) ullPos = ullCurrentChunkSize;
241          return ulPos;          return ullPos;
242      }      }
243    
244      /**      /**
# Line 227  namespace RIFF { Line 251  namespace RIFF {
251       *       *
252       *  @returns  number of bytes left to read       *  @returns  number of bytes left to read
253       */       */
254      unsigned long Chunk::RemainingBytes() {      file_offset_t Chunk::RemainingBytes() const {
255         #if DEBUG          #if DEBUG
256         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;          std::cout << "Chunk::Remainingbytes()=" << ullCurrentChunkSize - ullPos << std::endl;
257         #endif // DEBUG          #endif // DEBUG
258          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;          return (ullCurrentChunkSize > ullPos) ? ullCurrentChunkSize - ullPos : 0;
259        }
260    
261        /**
262         *  Returns the actual total size in bytes (including header) of this Chunk
263         *  if being stored to a file.
264         *
265         *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
266         *                          being saved to a file
267         */
268        file_offset_t Chunk::RequiredPhysicalSize(int fileOffsetSize) {
269            return CHUNK_HEADER_SIZE(fileOffsetSize) + // RIFF chunk header
270                   ullNewChunkSize + // chunks's actual data body
271                   ullNewChunkSize % 2; // optional pad byte
272      }      }
273    
274      /**      /**
# Line 245  namespace RIFF { Line 282  namespace RIFF {
282       *    already reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
283       *    possible without SetPos()       *    possible without SetPos()
284       */       */
285      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() const {
286        #if DEBUG          #if DEBUG
287        std::cout << "Chunk::GetState()" << std::endl;          std::cout << "Chunk::GetState()" << std::endl;
288        #endif // DEBUG          #endif // DEBUG
289          #if POSIX          #if POSIX
290          if (pFile->hFileRead == 0) return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
291          #elif defined (WIN32)          #elif defined (WIN32)
# Line 257  namespace RIFF { Line 294  namespace RIFF {
294          #else          #else
295          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
296          #endif // POSIX          #endif // POSIX
297          if (ulPos < CurrentChunkSize) return stream_ready;          if (ullPos < ullCurrentChunkSize) return stream_ready;
298          else                          return stream_end_reached;          else                              return stream_end_reached;
299      }      }
300    
301      /**      /**
# Line 276  namespace RIFF { Line 313  namespace RIFF {
313       *  @returns          number of successfully read data words or 0 if end       *  @returns          number of successfully read data words or 0 if end
314       *                    of file reached or error occured       *                    of file reached or error occured
315       */       */
316      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) {
317         #if DEBUG          #if DEBUG
318         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;          std::cout << "Chunk::Read(void*,file_offset_t,file_offset_t)" << std::endl;
319         #endif // DEBUG          #endif // DEBUG
320          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)
321          if (ulPos >= CurrentChunkSize) return 0;          if (ullPos >= ullCurrentChunkSize) return 0;
322          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ullPos + WordCount * WordSize >= ullCurrentChunkSize) WordCount = (ullCurrentChunkSize - ullPos) / WordSize;
323          #if POSIX          #if POSIX
324          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET) < 0) return 0;
325          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          ssize_t readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
326          if (readWords < 1) return 0;          if (readWords < 1) {
327                #if DEBUG
328                std::cerr << "POSIX read() failed: " << strerror(errno) << std::endl << std::flush;
329                #endif // DEBUG
330                return 0;
331            }
332          readWords /= WordSize;          readWords /= WordSize;
333          #elif defined(WIN32)          #elif defined(WIN32)
334          if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;          const LARGE_INTEGER liFilePos = { .QuadPart = ullStartPos + ullPos };
335            if (!SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN))
336                return 0;
337          DWORD readWords;          DWORD readWords;
338          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)
339          if (readWords < 1) return 0;          if (readWords < 1) return 0;
340          readWords /= WordSize;          readWords /= WordSize;
341          #else // standard C functions          #else // standard C functions
342          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseeko(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET)) return 0;
343          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          file_offset_t readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
344          #endif // POSIX          #endif // POSIX
345          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
346              switch (WordSize) {              switch (WordSize) {
347                  case 2:                  case 2:
348                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
349                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
350                      break;                      break;
351                  case 4:                  case 4:
352                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
353                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
354                      break;                      break;
355                    case 8:
356                        for (file_offset_t iWord = 0; iWord < readWords; iWord++)
357                            swapBytes_64((uint64_t*) pData + iWord);
358                        break;
359                  default:                  default:
360                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
361                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
362                      break;                      break;
363              }              }
# Line 334  namespace RIFF { Line 382  namespace RIFF {
382       *                           chunk size or any IO error occured       *                           chunk size or any IO error occured
383       *  @see Resize()       *  @see Resize()
384       */       */
385      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) {
386          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
387              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");
388          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)          if (ullPos >= ullCurrentChunkSize || ullPos + WordCount * WordSize > ullCurrentChunkSize)
389              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
390          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
391              switch (WordSize) {              switch (WordSize) {
392                  case 2:                  case 2:
393                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
394                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
395                      break;                      break;
396                  case 4:                  case 4:
397                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
398                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
399                      break;                      break;
400                    case 8:
401                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
402                            swapBytes_64((uint64_t*) pData + iWord);
403                        break;
404                  default:                  default:
405                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
406                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
407                      break;                      break;
408              }              }
409          }          }
410          #if POSIX          #if POSIX
411          if (lseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET) < 0) {          if (lseek(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET) < 0) {
412              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ullPos) +
413                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
414          }          }
415          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          ssize_t writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
416          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");
417          writtenWords /= WordSize;          writtenWords /= WordSize;
418          #elif defined(WIN32)          #elif defined(WIN32)
419          if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {          const LARGE_INTEGER liFilePos = { .QuadPart = ullStartPos + ullPos };
420              throw Exception("Could not seek to position " + ToString(ulPos) +          if (!SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
421                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");              throw Exception("Could not seek to position " + ToString(ullPos) +
422                                " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
423          }          }
424          DWORD writtenWords;          DWORD writtenWords;
425          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)
426          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");
427          writtenWords /= WordSize;          writtenWords /= WordSize;
428          #else // standard C functions          #else // standard C functions
429          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseeko(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET)) {
430              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ullPos) +
431                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
432          }          }
433          unsigned long writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);          file_offset_t writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
434          #endif // POSIX          #endif // POSIX
435          SetPos(writtenWords * WordSize, stream_curpos);          SetPos(writtenWords * WordSize, stream_curpos);
436          return writtenWords;          return writtenWords;
437      }      }
438    
439      /** 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. */
440      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) {
441          unsigned long readWords = Read(pData, WordCount, WordSize);          file_offset_t readWords = Read(pData, WordCount, WordSize);
442          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");
443          return readWords;          return readWords;
444      }      }
# Line 401  namespace RIFF { Line 454  namespace RIFF {
454       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
455       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
456       */       */
457      unsigned long Chunk::ReadInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt8(int8_t* pData, file_offset_t WordCount) {
458         #if DEBUG          #if DEBUG
459         std::cout << "Chunk::ReadInt8(int8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt8(int8_t*,file_offset_t)" << std::endl;
460         #endif // DEBUG          #endif // DEBUG
461          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
462      }      }
463    
# Line 422  namespace RIFF { Line 475  namespace RIFF {
475       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
476       * @see Resize()       * @see Resize()
477       */       */
478      unsigned long Chunk::WriteInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt8(int8_t* pData, file_offset_t WordCount) {
479          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
480      }      }
481    
# Line 438  namespace RIFF { Line 491  namespace RIFF {
491       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
492       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
493       */       */
494      unsigned long Chunk::ReadUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint8(uint8_t* pData, file_offset_t WordCount) {
495         #if DEBUG          #if DEBUG
496         std::cout << "Chunk::ReadUint8(uint8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint8(uint8_t*,file_offset_t)" << std::endl;
497         #endif // DEBUG          #endif // DEBUG
498          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
499      }      }
500    
# Line 459  namespace RIFF { Line 512  namespace RIFF {
512       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
513       * @see Resize()       * @see Resize()
514       */       */
515      unsigned long Chunk::WriteUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint8(uint8_t* pData, file_offset_t WordCount) {
516          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
517      }      }
518    
# Line 475  namespace RIFF { Line 528  namespace RIFF {
528       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
529       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
530       */       */
531      unsigned long Chunk::ReadInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt16(int16_t* pData, file_offset_t WordCount) {
532        #if DEBUG          #if DEBUG
533        std::cout << "Chunk::ReadInt16(int16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt16(int16_t*,file_offset_t)" << std::endl;
534        #endif // DEBUG          #endif // DEBUG
535          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
536      }      }
537    
# Line 496  namespace RIFF { Line 549  namespace RIFF {
549       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
550       * @see Resize()       * @see Resize()
551       */       */
552      unsigned long Chunk::WriteInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt16(int16_t* pData, file_offset_t WordCount) {
553          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
554      }      }
555    
# Line 512  namespace RIFF { Line 565  namespace RIFF {
565       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
566       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
567       */       */
568      unsigned long Chunk::ReadUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint16(uint16_t* pData, file_offset_t WordCount) {
569        #if DEBUG          #if DEBUG
570        std::cout << "Chunk::ReadUint16(uint16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint16(uint16_t*,file_offset_t)" << std::endl;
571        #endif // DEBUG          #endif // DEBUG
572          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
573      }      }
574    
# Line 533  namespace RIFF { Line 586  namespace RIFF {
586       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
587       * @see Resize()       * @see Resize()
588       */       */
589      unsigned long Chunk::WriteUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint16(uint16_t* pData, file_offset_t WordCount) {
590          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
591      }      }
592    
# Line 549  namespace RIFF { Line 602  namespace RIFF {
602       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
603       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
604       */       */
605      unsigned long Chunk::ReadInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt32(int32_t* pData, file_offset_t WordCount) {
606         #if DEBUG          #if DEBUG
607         std::cout << "Chunk::ReadInt32(int32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt32(int32_t*,file_offset_t)" << std::endl;
608         #endif // DEBUG          #endif // DEBUG
609          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
610      }      }
611    
# Line 570  namespace RIFF { Line 623  namespace RIFF {
623       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
624       * @see Resize()       * @see Resize()
625       */       */
626      unsigned long Chunk::WriteInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt32(int32_t* pData, file_offset_t WordCount) {
627          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
628      }      }
629    
# Line 586  namespace RIFF { Line 639  namespace RIFF {
639       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
640       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
641       */       */
642      unsigned long Chunk::ReadUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint32(uint32_t* pData, file_offset_t WordCount) {
643         #if DEBUG          #if DEBUG
644         std::cout << "Chunk::ReadUint32(uint32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint32(uint32_t*,file_offset_t)" << std::endl;
645         #endif // DEBUG          #endif // DEBUG
646          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
647      }      }
648    
649      /**      /**
650         * Reads a null-padded string of size characters and copies it
651         * into the string \a s. The position within the chunk will
652         * automatically be incremented.
653         *
654         * @param s                 destination string
655         * @param size              number of characters to read
656         * @throws RIFF::Exception  if an error occured or less than
657         *                          \a size characters could be read!
658         */
659        void Chunk::ReadString(String& s, int size) {
660            char* buf = new char[size];
661            ReadSceptical(buf, 1, size);
662            s.assign(buf, std::find(buf, buf + size, '\0'));
663            delete[] buf;
664        }
665    
666        /**
667       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
668       * 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
669       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 607  namespace RIFF { Line 677  namespace RIFF {
677       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
678       * @see Resize()       * @see Resize()
679       */       */
680      unsigned long Chunk::WriteUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint32(uint32_t* pData, file_offset_t WordCount) {
681          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
682      }      }
683    
# Line 619  namespace RIFF { Line 689  namespace RIFF {
689       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
690       */       */
691      int8_t Chunk::ReadInt8() {      int8_t Chunk::ReadInt8() {
692        #if DEBUG          #if DEBUG
693        std::cout << "Chunk::ReadInt8()" << std::endl;          std::cout << "Chunk::ReadInt8()" << std::endl;
694        #endif // DEBUG          #endif // DEBUG
695          int8_t word;          int8_t word;
696          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
697          return word;          return word;
# Line 635  namespace RIFF { Line 705  namespace RIFF {
705       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
706       */       */
707      uint8_t Chunk::ReadUint8() {      uint8_t Chunk::ReadUint8() {
708        #if DEBUG          #if DEBUG
709        std::cout << "Chunk::ReadUint8()" << std::endl;          std::cout << "Chunk::ReadUint8()" << std::endl;
710        #endif // DEBUG          #endif // DEBUG
711          uint8_t word;          uint8_t word;
712          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
713          return word;          return word;
# Line 652  namespace RIFF { Line 722  namespace RIFF {
722       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
723       */       */
724      int16_t Chunk::ReadInt16() {      int16_t Chunk::ReadInt16() {
725        #if DEBUG          #if DEBUG
726        std::cout << "Chunk::ReadInt16()" << std::endl;          std::cout << "Chunk::ReadInt16()" << std::endl;
727        #endif // DEBUG          #endif // DEBUG
728          int16_t word;          int16_t word;
729          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
730          return word;          return word;
# Line 669  namespace RIFF { Line 739  namespace RIFF {
739       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
740       */       */
741      uint16_t Chunk::ReadUint16() {      uint16_t Chunk::ReadUint16() {
742        #if DEBUG          #if DEBUG
743        std::cout << "Chunk::ReadUint16()" << std::endl;          std::cout << "Chunk::ReadUint16()" << std::endl;
744        #endif // DEBUG          #endif // DEBUG
745          uint16_t word;          uint16_t word;
746          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
747          return word;          return word;
# Line 686  namespace RIFF { Line 756  namespace RIFF {
756       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
757       */       */
758      int32_t Chunk::ReadInt32() {      int32_t Chunk::ReadInt32() {
759        #if DEBUG          #if DEBUG
760        std::cout << "Chunk::ReadInt32()" << std::endl;          std::cout << "Chunk::ReadInt32()" << std::endl;
761        #endif // DEBUG          #endif // DEBUG
762          int32_t word;          int32_t word;
763          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
764          return word;          return word;
# Line 703  namespace RIFF { Line 773  namespace RIFF {
773       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
774       */       */
775      uint32_t Chunk::ReadUint32() {      uint32_t Chunk::ReadUint32() {
776        #if DEBUG          #if DEBUG
777        std::cout << "Chunk::ReadUint32()" << std::endl;          std::cout << "Chunk::ReadUint32()" << std::endl;
778        #endif // DEBUG          #endif // DEBUG
779          uint32_t word;          uint32_t word;
780          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
781          return word;          return word;
# Line 733  namespace RIFF { Line 803  namespace RIFF {
803       * @see ReleaseChunkData()       * @see ReleaseChunkData()
804       */       */
805      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
806          if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
807              #if POSIX              #if POSIX
808              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ullStartPos, SEEK_SET) == -1) return NULL;
809              #elif defined(WIN32)              #elif defined(WIN32)
810              if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;              const LARGE_INTEGER liFilePos = { .QuadPart = ullStartPos };
811                if (!SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) return NULL;
812              #else              #else
813              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseeko(pFile->hFileRead, ullStartPos, SEEK_SET)) return NULL;
814              #endif // POSIX              #endif // POSIX
815              unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;              file_offset_t ullBufferSize = (ullCurrentChunkSize > ullNewChunkSize) ? ullCurrentChunkSize : ullNewChunkSize;
816              pChunkData = new uint8_t[ulBufferSize];              pChunkData = new uint8_t[ullBufferSize];
817              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
818              memset(pChunkData, 0, ulBufferSize);              memset(pChunkData, 0, ullBufferSize);
819              #if POSIX              #if POSIX
820              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());              file_offset_t readWords = read(pFile->hFileRead, pChunkData, GetSize());
821              #elif defined(WIN32)              #elif defined(WIN32)
822              DWORD readWords;              DWORD readWords;
823              ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);              ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL); //FIXME: won't load chunks larger than 2GB !
824              #else              #else
825              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              file_offset_t readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
826              #endif // POSIX              #endif // POSIX
827              if (readWords != GetSize()) {              if (readWords != GetSize()) {
828                  delete[] pChunkData;                  delete[] pChunkData;
829                  return (pChunkData = NULL);                  return (pChunkData = NULL);
830              }              }
831              ulChunkDataSize = ulBufferSize;              ullChunkDataSize = ullBufferSize;
832          } else if (NewChunkSize > ulChunkDataSize) {          } else if (ullNewChunkSize > ullChunkDataSize) {
833              uint8_t* pNewBuffer = new uint8_t[NewChunkSize];              uint8_t* pNewBuffer = new uint8_t[ullNewChunkSize];
834              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");
835              memset(pNewBuffer, 0 , NewChunkSize);              memset(pNewBuffer, 0 , ullNewChunkSize);
836              memcpy(pNewBuffer, pChunkData, ulChunkDataSize);              memcpy(pNewBuffer, pChunkData, ullChunkDataSize);
837              delete[] pChunkData;              delete[] pChunkData;
838              pChunkData      = pNewBuffer;              pChunkData       = pNewBuffer;
839              ulChunkDataSize = NewChunkSize;              ullChunkDataSize = ullNewChunkSize;
840          }          }
841          return pChunkData;          return pChunkData;
842      }      }
# Line 797  namespace RIFF { Line 868  namespace RIFF {
868       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
869       * boundary!       * boundary!
870       *       *
871       * @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)
872       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a NewSize is less than 1 or Unrealistic large
873       * @see File::Save()       * @see File::Save()
874       */       */
875      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(file_offset_t NewSize) {
876          if (iNewSize <= 0)          if (NewSize == 0)
877              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));
878          if (NewChunkSize == iNewSize) return;          if ((NewSize >> 48) != 0)
879          NewChunkSize = iNewSize;              throw Exception("Unrealistic high chunk size detected: " + __resolveChunkPath(this));
880          pFile->LogAsResized(this);          if (ullNewChunkSize == NewSize) return;
881            ullNewChunkSize = NewSize;
882      }      }
883    
884      /** @brief Write chunk persistently e.g. to disk.      /** @brief Write chunk persistently e.g. to disk.
885       *       *
886       * Stores the chunk persistently to its actual "physical" file.       * Stores the chunk persistently to its actual "physical" file.
887       *       *
888       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
889       *                     chunk should be written to       *                     chunk should be written to
890       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
891       *                              the file       *                              the file
892         * @param pProgress - optional: callback function for progress notification
893       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
894       *          \a ulWritePos incremented by this chunk's new size       *          \a ullWritePos incremented by this chunk's new size
895       *          (including its header size of course)       *          (including its header size of course)
896       */       */
897      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) {
898          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
899          ulWritePos += CHUNK_HEADER_SIZE;          ullWritePos += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
900    
901          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
902              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 834  namespace RIFF { Line 907  namespace RIFF {
907              LoadChunkData();              LoadChunkData();
908              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
909              #if POSIX              #if POSIX
910              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ullWritePos, SEEK_SET);
911              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, ullNewChunkSize) != ullNewChunkSize) {
912                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
913              }              }
914              #elif defined(WIN32)              #elif defined(WIN32)
915              SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);              const LARGE_INTEGER liFilePos = { .QuadPart = ullWritePos };
916                SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
917              DWORD dwBytesWritten;              DWORD dwBytesWritten;
918              WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, pChunkData, ullNewChunkSize, &dwBytesWritten, NULL); //FIXME: won't save chunks larger than 2GB !
919              if (dwBytesWritten != NewChunkSize) {              if (dwBytesWritten != ullNewChunkSize) {
920                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
921              }              }
922              #else              #else
923              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseeko(pFile->hFileWrite, ullWritePos, SEEK_SET);
924              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, ullNewChunkSize, pFile->hFileWrite) != ullNewChunkSize) {
925                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
926              }              }
927              #endif // POSIX              #endif // POSIX
928          } else {          } else {
929              // 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
930              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
931              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              file_offset_t ullToMove = (ullNewChunkSize < ullCurrentChunkSize) ? ullNewChunkSize : ullCurrentChunkSize;
932              #if defined(WIN32)              #if defined(WIN32)
933              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
934              #else              #else
935              int iBytesMoved = 1;              int iBytesMoved = 1;
936              #endif              #endif
937              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (file_offset_t ullOffset = 0; ullToMove > 0 && iBytesMoved > 0; ullOffset += iBytesMoved, ullToMove -= iBytesMoved) {
938                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ullToMove < 4096) ? ullToMove : 4096;
939                  #if POSIX                  #if POSIX
940                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
941                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
942                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
943                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
944                  #elif defined(WIN32)                  #elif defined(WIN32)
945                  SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  LARGE_INTEGER liFilePos = { .QuadPart = ullStartPos + ullCurrentDataOffset + ullOffset };
946                    SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
947                  ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
948                  SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  liFilePos.QuadPart = ullWritePos + ullOffset;
949                    SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
950                  WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
951                  #else                  #else
952                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseeko(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
953                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
954                  fseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  fseeko(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
955                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
956                  #endif                  #endif
957              }              }
# Line 884  namespace RIFF { Line 960  namespace RIFF {
960          }          }
961    
962          // update this chunk's header          // update this chunk's header
963          CurrentChunkSize = NewChunkSize;          ullCurrentChunkSize = ullNewChunkSize;
964          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
965    
966            __notify_progress(pProgress, 1.0); // notify done
967    
968          // update chunk's position pointers          // update chunk's position pointers
969          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;          ullStartPos = ullOriginalPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
970          ulPos      = 0;          ullPos      = 0;
971    
972          // add pad byte if needed          // add pad byte if needed
973          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ullStartPos + ullNewChunkSize) % 2 != 0) {
974              const char cPadByte = 0;              const char cPadByte = 0;
975              #if POSIX              #if POSIX
976              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
977              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
978              #elif defined(WIN32)              #elif defined(WIN32)
979              SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);              const LARGE_INTEGER liFilePos = { .QuadPart = ullStartPos + ullNewChunkSize };
980                SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
981              DWORD dwBytesWritten;              DWORD dwBytesWritten;
982              WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
983              #else              #else
984              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseeko(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
985              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
986              #endif              #endif
987              return ulStartPos + NewChunkSize + 1;              return ullStartPos + ullNewChunkSize + 1;
988          }          }
989    
990          return ulStartPos + NewChunkSize;          return ullStartPos + ullNewChunkSize;
991      }      }
992    
993      void Chunk::__resetPos() {      void Chunk::__resetPos() {
994          ulPos = 0;          ullPos = 0;
995      }      }
996    
997    
# Line 921  namespace RIFF { Line 1000  namespace RIFF {
1000  // *  // *
1001    
1002      List::List(File* pFile) : Chunk(pFile) {      List::List(File* pFile) : Chunk(pFile) {
1003        #if DEBUG          #if DEBUG
1004        std::cout << "List::List(File* pFile)" << std::endl;          std::cout << "List::List(File* pFile)" << std::endl;
1005        #endif // DEBUG          #endif // DEBUG
1006          pSubChunks    = NULL;          pSubChunks    = NULL;
1007          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1008      }      }
1009    
1010      List::List(File* pFile, unsigned long StartPos, List* Parent)      List::List(File* pFile, file_offset_t StartPos, List* Parent)
1011        : Chunk(pFile, StartPos, Parent) {        : Chunk(pFile, StartPos, Parent) {
1012          #if DEBUG          #if DEBUG
1013          std::cout << "List::List(File*,ulong,bool,List*)" << std::endl;          std::cout << "List::List(File*,file_offset_t,List*)" << std::endl;
1014          #endif // DEBUG          #endif // DEBUG
1015          pSubChunks    = NULL;          pSubChunks    = NULL;
1016          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1017          ReadHeader(StartPos);          ReadHeader(StartPos);
1018          ulStartPos    = StartPos + LIST_HEADER_SIZE;          ullStartPos = StartPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1019      }      }
1020    
1021      List::List(File* pFile, List* pParent, uint32_t uiListID)      List::List(File* pFile, List* pParent, uint32_t uiListID)
# Line 947  namespace RIFF { Line 1026  namespace RIFF {
1026      }      }
1027    
1028      List::~List() {      List::~List() {
1029        #if DEBUG          #if DEBUG
1030        std::cout << "List::~List()" << std::endl;          std::cout << "List::~List()" << std::endl;
1031        #endif // DEBUG          #endif // DEBUG
1032          DeleteChunkList();          DeleteChunkList();
1033      }      }
1034    
# Line 982  namespace RIFF { Line 1061  namespace RIFF {
1061       *                   that ID       *                   that ID
1062       */       */
1063      Chunk* List::GetSubChunk(uint32_t ChunkID) {      Chunk* List::GetSubChunk(uint32_t ChunkID) {
1064        #if DEBUG          #if DEBUG
1065        std::cout << "List::GetSubChunk(uint32_t)" << std::endl;          std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
1066        #endif // DEBUG          #endif // DEBUG
1067          if (!pSubChunksMap) LoadSubChunks();          if (!pSubChunksMap) LoadSubChunks();
1068          return (*pSubChunksMap)[ChunkID];          return (*pSubChunksMap)[ChunkID];
1069      }      }
# Line 1151  namespace RIFF { Line 1230  namespace RIFF {
1230      /** @brief Creates a new sub chunk.      /** @brief Creates a new sub chunk.
1231       *       *
1232       * 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
1233       * 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.
1234       * 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
1235       * actual file and <b>before</b> performing any data write operations       * actual file and <b>before</b> performing any data write operations
1236       * on the new chunk!       * on the new chunk!
1237       *       *
1238       * @param uiChunkID  - chunk ID of the new chunk       * @param uiChunkID  - chunk ID of the new chunk
1239       * @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
1240       *                     data size (without header)       *                      data size (without header)
1241       * @throws RIFF::Exception if \a uiBodySize equals zero       * @throws RIFF::Exception if \a ullBodySize equals zero
1242       */       */
1243      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize) {
1244          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");
1245          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1246          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1247          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1248          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1249          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(ullBodySize);
1250          NewChunkSize += CHUNK_HEADER_SIZE;          ullNewChunkSize += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1251          return pNewChunk;          return pNewChunk;
1252      }      }
1253    
1254      /** @brief Moves a sub chunk.      /** @brief Moves a sub chunk witin this list.
1255       *       *
1256       * Moves a sub chunk from one position in a list to another       * Moves a sub chunk from one position in this list to another
1257       * position in the same list. The pSrc chunk is placed before the       * position in the same list. The pSrc chunk is placed before the
1258       * pDst chunk.       * pDst chunk.
1259       *       *
# Line 1191  namespace RIFF { Line 1269  namespace RIFF {
1269          pSubChunks->insert(iter, pSrc);          pSubChunks->insert(iter, pSrc);
1270      }      }
1271    
1272        /** @brief Moves a sub chunk from this list to another list.
1273         *
1274         * Moves a sub chunk from this list list to the end of another
1275         * list.
1276         *
1277         * @param pSrc - sub chunk to be moved
1278         * @param pDst - destination list where the chunk shall be moved to
1279         */
1280        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1281            if (pNewParent == this || !pNewParent) return;
1282            if (!pSubChunks) LoadSubChunks();
1283            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1284            pSubChunks->remove(pSrc);
1285            pNewParent->pSubChunks->push_back(pSrc);
1286            // update chunk id map of this List
1287            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1288                pSubChunksMap->erase(pSrc->GetChunkID());
1289                // try to find another chunk of the same chunk ID
1290                ChunkList::iterator iter = pSubChunks->begin();
1291                ChunkList::iterator end  = pSubChunks->end();
1292                for (; iter != end; ++iter) {
1293                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1294                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1295                        break; // we're done, stop search
1296                    }
1297                }
1298            }
1299            // update chunk id map of other list
1300            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1301                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1302        }
1303    
1304      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1305       *       *
1306       * 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 1205  namespace RIFF { Line 1315  namespace RIFF {
1315          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1316          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1317          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1318          NewChunkSize += LIST_HEADER_SIZE;          ullNewChunkSize += LIST_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1319          return pNewListChunk;          return pNewListChunk;
1320      }      }
1321    
# Line 1238  namespace RIFF { Line 1347  namespace RIFF {
1347          delete pSubChunk;          delete pSubChunk;
1348      }      }
1349    
1350      void List::ReadHeader(unsigned long fPos) {      /**
1351        #if DEBUG       *  Returns the actual total size in bytes (including List chunk header and
1352        std::cout << "List::Readheader(ulong) ";       *  all subchunks) of this List Chunk if being stored to a file.
1353        #endif // DEBUG       *
1354          Chunk::ReadHeader(fPos);       *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
1355          if (CurrentChunkSize < 4) return;       *                          being saved to a file
1356          NewChunkSize = CurrentChunkSize -= 4;       */
1357        file_offset_t List::RequiredPhysicalSize(int fileOffsetSize) {
1358            if (!pSubChunks) LoadSubChunks();
1359            file_offset_t size = LIST_HEADER_SIZE(fileOffsetSize);
1360            ChunkList::iterator iter = pSubChunks->begin();
1361            ChunkList::iterator end  = pSubChunks->end();
1362            for (; iter != end; ++iter)
1363                size += (*iter)->RequiredPhysicalSize(fileOffsetSize);
1364            return size;
1365        }
1366    
1367        void List::ReadHeader(file_offset_t filePos) {
1368            #if DEBUG
1369            std::cout << "List::Readheader(file_offset_t) ";
1370            #endif // DEBUG
1371            Chunk::ReadHeader(filePos);
1372            if (ullCurrentChunkSize < 4) return;
1373            ullNewChunkSize = ullCurrentChunkSize -= 4;
1374          #if POSIX          #if POSIX
1375          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1376          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1377          #elif defined(WIN32)          #elif defined(WIN32)
1378          SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          const LARGE_INTEGER liFilePos = { .QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) };
1379            SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1380          DWORD dwBytesRead;          DWORD dwBytesRead;
1381          ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);          ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1382          #else          #else
1383          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1384          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
1385          #endif // POSIX          #endif // POSIX
1386        #if DEBUG          #if DEBUG
1387        std::cout << "listType=" << convertToString(ListType) << std::endl;          std::cout << "listType=" << convertToString(ListType) << std::endl;
1388        #endif // DEBUG          #endif // DEBUG
1389          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
1390              //swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1391          }          }
1392      }      }
1393    
1394      void List::WriteHeader(unsigned long fPos) {      void List::WriteHeader(file_offset_t filePos) {
1395          // 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
1396          NewChunkSize += 4;          ullNewChunkSize += 4;
1397          Chunk::WriteHeader(fPos);          Chunk::WriteHeader(filePos);
1398          NewChunkSize -= 4; // just revert the +4 incrementation          ullNewChunkSize -= 4; // just revert the +4 incrementation
1399          #if POSIX          #if POSIX
1400          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1401          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1402          #elif defined(WIN32)          #elif defined(WIN32)
1403          SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          const LARGE_INTEGER liFilePos = { .QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) };
1404            SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1405          DWORD dwBytesWritten;          DWORD dwBytesWritten;
1406          WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);          WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1407          #else          #else
1408          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1409          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
1410          #endif // POSIX          #endif // POSIX
1411      }      }
1412    
1413      void List::LoadSubChunks() {      void List::LoadSubChunks(progress_t* pProgress) {
1414         #if DEBUG          #if DEBUG
1415         std::cout << "List::LoadSubChunks()";          std::cout << "List::LoadSubChunks()";
1416         #endif // DEBUG          #endif // DEBUG
1417          if (!pSubChunks) {          if (!pSubChunks) {
1418              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1419              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
# Line 1294  namespace RIFF { Line 1422  namespace RIFF {
1422              #else              #else
1423              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1424              #endif              #endif
1425              unsigned long uiOriginalPos = GetPos();              file_offset_t ullOriginalPos = GetPos();
1426              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1427              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE(pFile->FileOffsetSize)) {
1428                  Chunk* ck;                  Chunk* ck;
1429                  uint32_t ckid;                  uint32_t ckid;
1430                  Read(&ckid, 4, 1);                  Read(&ckid, 4, 1);
1431         #if DEBUG                  #if DEBUG
1432         std::cout << " ckid=" << convertToString(ckid) << std::endl;                  std::cout << " ckid=" << convertToString(ckid) << std::endl;
1433         #endif // DEBUG                  #endif // DEBUG
1434                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1435                      ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::List(pFile, ullStartPos + ullPos - 4, this);
1436                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1437                  }                  }
1438                  else { // simple chunk                  else { // simple chunk
1439                      ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::Chunk(pFile, ullStartPos + ullPos - 4, this);
1440                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1441                  }                  }
1442                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1443                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1444                  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
1445              }              }
1446              SetPos(uiOriginalPos); // restore position before this call              SetPos(ullOriginalPos); // restore position before this call
1447          }          }
1448            __notify_progress(pProgress, 1.0); // notify done
1449      }      }
1450    
1451      void List::LoadSubChunksRecursively() {      void List::LoadSubChunksRecursively(progress_t* pProgress) {
1452          for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())          const int n = CountSubLists();
1453              pList->LoadSubChunksRecursively();          int i = 0;
1454            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList(), ++i) {
1455                // divide local progress into subprogress
1456                progress_t subprogress;
1457                __divide_progress(pProgress, &subprogress, n, i);
1458                // do the actual work
1459                pList->LoadSubChunksRecursively(&subprogress);
1460            }
1461            __notify_progress(pProgress, 1.0); // notify done
1462      }      }
1463    
1464      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
# Line 1330  namespace RIFF { Line 1467  namespace RIFF {
1467       * subchunks (including sub list chunks) will be stored recursively as       * subchunks (including sub list chunks) will be stored recursively as
1468       * well.       * well.
1469       *       *
1470       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
1471       *                     list chunk should be written to       *                     list chunk should be written to
1472       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
1473       *                              the file       *                              the file
1474         * @param pProgress - optional: callback function for progress notification
1475       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
1476       *          \a ulWritePos incremented by this list chunk's new size       *          \a ullWritePos incremented by this list chunk's new size
1477       *          (including its header size of course)       *          (including its header size of course)
1478       */       */
1479      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) {
1480          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
1481          ulWritePos += LIST_HEADER_SIZE;          ullWritePos += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1482    
1483          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
1484              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");
1485    
1486          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1487          if (pSubChunks) {          if (pSubChunks) {
1488              for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {              int i = 0;
1489                  ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);              const int n = pSubChunks->size();
1490                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1491                    // divide local progress into subprogress for loading current Instrument
1492                    progress_t subprogress;
1493                    __divide_progress(pProgress, &subprogress, n, i);
1494                    // do the actual work
1495                    ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, &subprogress);
1496              }              }
1497          }          }
1498    
1499          // update this list chunk's header          // update this list chunk's header
1500          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          ullCurrentChunkSize = ullNewChunkSize = ullWritePos - ullOriginalPos - LIST_HEADER_SIZE(pFile->FileOffsetSize);
1501          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
1502    
1503          // offset of this list chunk in new written file may have changed          // offset of this list chunk in new written file may have changed
1504          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;          ullStartPos = ullOriginalPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1505    
1506             __notify_progress(pProgress, 1.0); // notify done
1507    
1508          return ulWritePos;          return ullWritePos;
1509      }      }
1510    
1511      void List::__resetPos() {      void List::__resetPos() {
# Line 1374  namespace RIFF { Line 1520  namespace RIFF {
1520      /**      /**
1521       *  Returns string representation of the lists's id       *  Returns string representation of the lists's id
1522       */       */
1523      String List::GetListTypeString() {      String List::GetListTypeString() const {
1524          return convertToString(ListType);          return convertToString(ListType);
1525      }      }
1526    
# Line 1397  namespace RIFF { Line 1543  namespace RIFF {
1543       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1544       * @see AddSubChunk(), AddSubList(), SetByteOrder()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1545       */       */
1546      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType)
1547            : List(this), bIsNewFile(true), Layout(layout_standard),
1548              FileOffsetPreference(offset_size_auto)
1549        {
1550          #if defined(WIN32)          #if defined(WIN32)
1551          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1552          #else          #else
# Line 1405  namespace RIFF { Line 1554  namespace RIFF {
1554          #endif          #endif
1555          Mode = stream_mode_closed;          Mode = stream_mode_closed;
1556          bEndianNative = true;          bEndianNative = true;
         ulStartPos = RIFF_HEADER_SIZE;  
1557          ListType = FileType;          ListType = FileType;
1558            FileOffsetSize = 4;
1559            ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1560      }      }
1561    
1562      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1417  namespace RIFF { Line 1567  namespace RIFF {
1567       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occured while trying to load the
1568       *                         given RIFF file       *                         given RIFF file
1569       */       */
1570      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path)
1571        #if DEBUG          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard),
1572        std::cout << "File::File("<<path<<")" << std::endl;            FileOffsetPreference(offset_size_auto)
1573        #endif // DEBUG      {
1574            #if DEBUG
1575            std::cout << "File::File("<<path<<")" << std::endl;
1576            #endif // DEBUG
1577          bEndianNative = true;          bEndianNative = true;
1578            FileOffsetSize = 4;
1579            try {
1580                __openExistingFile(path);
1581                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1582                    throw RIFF::Exception("Not a RIFF file");
1583                }
1584            }
1585            catch (...) {
1586                Cleanup();
1587                throw;
1588            }
1589        }
1590    
1591        /** @brief Load existing RIFF-like file.
1592         *
1593         * Loads an existing file, which is not a "real" RIFF file, but similar to
1594         * an ordinary RIFF file.
1595         *
1596         * A "real" RIFF file contains at top level a List chunk either with chunk
1597         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1598         * case, and if it finds the toplevel List chunk to have another chunk ID
1599         * than one of those two expected ones, it would throw an Exception and
1600         * would refuse to load the file accordingly.
1601         *
1602         * Since there are however a lot of file formats which use the same simple
1603         * principles of the RIFF format, with another toplevel List chunk ID
1604         * though, you can use this alternative constructor here to be able to load
1605         * and handle those files in the same way as you would do with "real" RIFF
1606         * files.
1607         *
1608         * @param path - path and file name of the RIFF-alike file to be opened
1609         * @param FileType - expected toplevel List chunk ID (this is the very
1610         *                   first chunk found in the file)
1611         * @param Endian - whether the file uses little endian or big endian layout
1612         * @param layout - general file structure type
1613         * @param fileOffsetSize - (optional) preference how to deal with large files
1614         * @throws RIFF::Exception if error occured while trying to load the
1615         *                         given RIFF-alike file
1616         */
1617        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout, offset_size_t fileOffsetSize)
1618            : List(this), Filename(path), bIsNewFile(false), Layout(layout),
1619              FileOffsetPreference(fileOffsetSize)
1620        {
1621            SetByteOrder(Endian);
1622            if (fileOffsetSize < offset_size_auto || fileOffsetSize > offset_size_64bit)
1623                throw Exception("Invalid RIFF::offset_size_t");
1624            FileOffsetSize = 4;
1625            try {
1626                __openExistingFile(path, &FileType);
1627            }
1628            catch (...) {
1629                Cleanup();
1630                throw;
1631            }
1632        }
1633    
1634        /**
1635         * Opens an already existing RIFF file or RIFF-alike file. This method
1636         * shall only be called once (in a File class constructor).
1637         *
1638         * @param path - path and file name of the RIFF file or RIFF-alike file to
1639         *               be opened
1640         * @param FileType - (optional) expected chunk ID of first chunk in file
1641         * @throws RIFF::Exception if error occured while trying to load the
1642         *                         given RIFF file or RIFF-alike file
1643         */
1644        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1645          #if POSIX          #if POSIX
1646          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1647          if (hFileRead <= 0) {          if (hFileRead == -1) {
1648              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1649              throw RIFF::Exception("Can't open \"" + path + "\"");              String sError = strerror(errno);
1650                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1651          }          }
1652          #elif defined(WIN32)          #elif defined(WIN32)
1653          hFileRead = hFileWrite = CreateFile(          hFileRead = hFileWrite = CreateFile(
# Line 1445  namespace RIFF { Line 1666  namespace RIFF {
1666          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1667          #endif // POSIX          #endif // POSIX
1668          Mode = stream_mode_read;          Mode = stream_mode_read;
1669          ulStartPos = RIFF_HEADER_SIZE;  
1670          ReadHeader(0);          // determine RIFF file offset size to be used (in RIFF chunk headers)
1671          if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {          // according to the current file offset preference
1672              throw RIFF::Exception("Not a RIFF file");          FileOffsetSize = FileOffsetSizeFor(GetCurrentFileSize());
1673    
1674            switch (Layout) {
1675                case layout_standard: // this is a normal RIFF file
1676                    ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1677                    ReadHeader(0);
1678                    if (FileType && ChunkID != *FileType)
1679                        throw RIFF::Exception("Invalid file container ID");
1680                    break;
1681                case layout_flat: // non-standard RIFF-alike file
1682                    ullStartPos = 0;
1683                    ullNewChunkSize = ullCurrentChunkSize = GetCurrentFileSize();
1684                    if (FileType) {
1685                        uint32_t ckid;
1686                        if (Read(&ckid, 4, 1) != 4) {
1687                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1688                        } else if (ckid != *FileType) {
1689                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1690                            throw RIFF::Exception("Invalid file header ID" + s);
1691                        }
1692                        SetPos(0); // reset to first byte of file
1693                    }
1694                    LoadSubChunks();
1695                    break;
1696          }          }
1697      }      }
1698    
1699      String File::GetFileName() {      String File::GetFileName() const {
1700          return Filename;          return Filename;
1701      }      }
1702        
1703        void File::SetFileName(const String& path) {
1704            Filename = path;
1705        }
1706    
1707      stream_mode_t File::GetMode() {      stream_mode_t File::GetMode() const {
1708          return Mode;          return Mode;
1709      }      }
1710    
1711        layout_t File::GetLayout() const {
1712            return Layout;
1713        }
1714    
1715      /** @brief Change file access mode.      /** @brief Change file access mode.
1716       *       *
1717       * 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 1477  namespace RIFF { Line 1729  namespace RIFF {
1729                      #if POSIX                      #if POSIX
1730                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1731                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1732                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1733                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1734                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          String sError = strerror(errno);
1735                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1736                      }                      }
1737                      #elif defined(WIN32)                      #elif defined(WIN32)
1738                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1506  namespace RIFF { Line 1759  namespace RIFF {
1759                      #if POSIX                      #if POSIX
1760                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1761                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1762                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1763                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1764                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          String sError = strerror(errno);
1765                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1766                      }                      }
1767                      #elif defined(WIN32)                      #elif defined(WIN32)
1768                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1584  namespace RIFF { Line 1838  namespace RIFF {
1838      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1839       *       *
1840       * Make all changes of all chunks persistent by writing them to the       * Make all changes of all chunks persistent by writing them to the
1841       * 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.  
1842       *       *
1843         * @param pProgress - optional: callback function for progress notification
1844       * @throws RIFF::Exception if there is an empty chunk or empty list       * @throws RIFF::Exception if there is an empty chunk or empty list
1845       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1846       */       */
1847      void File::Save() {      void File::Save(progress_t* pProgress) {
1848            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1849            if (Layout == layout_flat)
1850                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1851    
1852          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1853          LoadSubChunksRecursively();          {
1854                // divide progress into subprogress
1855                progress_t subprogress;
1856                __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
1857                // do the actual work
1858                LoadSubChunksRecursively(&subprogress);
1859                // notify subprogress done
1860                __notify_progress(&subprogress, 1.f);
1861            }
1862    
1863          // reopen file in write mode          // reopen file in write mode
1864          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1865    
1866            // get the current file size as it is now still physically stored on disk
1867            const file_offset_t workingFileSize = GetCurrentFileSize();
1868    
1869            // get the overall file size required to save this file
1870            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1871    
1872            // determine whether this file will yield in a large file (>=4GB) and
1873            // the RIFF file offset size to be used accordingly for all chunks
1874            FileOffsetSize = FileOffsetSizeFor(newFileSize);
1875    
1876          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
1877          // 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
1878          // enlarge the file with the sum of all _positive_ chunk size          // enlarge the file with the overall positive file size change,
1879          // 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
1880          // calculated sum and finally update / rewrite the file by copying          // positive file size difference and finally update / rewrite the file
1881          // 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
1882            // of the file
         // first we sum up all positive chunk size changes (and skip all negative ones)  
         unsigned long ulPositiveSizeDiff = 0;  
         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();  
1883    
1884          // if there are positive size changes...          // if there are positive size changes...
1885          if (ulPositiveSizeDiff > 0) {          file_offset_t positiveSizeDiff = 0;
1886            if (newFileSize > workingFileSize) {
1887                positiveSizeDiff = newFileSize - workingFileSize;
1888    
1889                // divide progress into subprogress
1890                progress_t subprogress;
1891                __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1892    
1893              // ... we enlarge this file first ...              // ... we enlarge this file first ...
1894              ulWorkingFileSize += ulPositiveSizeDiff;              ResizeFile(newFileSize);
1895              ResizeFile(ulWorkingFileSize);  
1896              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1897              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
             const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;  
1898              #if defined(WIN32)              #if defined(WIN32)
1899              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
1900              #else              #else
1901              int iBytesMoved = 1;              int iBytesMoved = 1;
1902              #endif              #endif
1903              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {              for (file_offset_t ullPos = workingFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1904                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;                  iBytesMoved = (ullPos < 4096) ? ullPos : 4096;
1905                  ulPos -= iBytesMoved;                  ullPos -= iBytesMoved;
1906                  #if POSIX                  #if POSIX
1907                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ullPos, SEEK_SET);
1908                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1909                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1910                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1911                  #elif defined(WIN32)                  #elif defined(WIN32)
1912                  SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);                  LARGE_INTEGER liFilePos = { .QuadPart = ullPos };
1913                    SetFilePointerEx(hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1914                  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1915                  SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);                  liFilePos.QuadPart = ullPos + positiveSizeDiff;
1916                    SetFilePointerEx(hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1917                  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1918                  #else                  #else
1919                  fseek(hFileRead, ulPos, SEEK_SET);                  fseeko(hFileRead, ullPos, SEEK_SET);
1920                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1921                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  fseeko(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1922                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1923                  #endif                  #endif
1924                    if (!(iNotif % 8) && iBytesMoved > 0)
1925                        __notify_progress(&subprogress, float(workingFileSize - ullPos) / float(workingFileSize));
1926              }              }
1927              delete[] pCopyBuffer;              delete[] pCopyBuffer;
1928              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");
1929    
1930                __notify_progress(&subprogress, 1.f); // notify subprogress done
1931          }          }
1932    
1933          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree ...
1934          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);  
1935          unsigned long ulActualSize = __GetFileSize(hFileWrite);          // divide progress into subprogress
1936            progress_t subprogress;
1937            __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
1938            // do the actual work
1939            const file_offset_t finalSize = WriteChunk(0, positiveSizeDiff, &subprogress);
1940            const file_offset_t finalActualSize = __GetFileSize(hFileWrite);
1941            // notify subprogress done
1942            __notify_progress(&subprogress, 1.f);
1943    
1944          // resize file to the final size          // resize file to the final size
1945          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (finalSize < finalActualSize) ResizeFile(finalSize);
1946    
1947          // forget all resized chunks          __notify_progress(pProgress, 1.0); // notify done
         ResizedChunks.clear();  
1948      }      }
1949    
1950      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1678  namespace RIFF { Line 1959  namespace RIFF {
1959       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
1960       *       *
1961       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1962         * @param pProgress - optional: callback function for progress notification
1963       */       */
1964      void File::Save(const String& path) {      void File::Save(const String& path, progress_t* pProgress) {
1965          //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
1966    
1967            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1968            if (Layout == layout_flat)
1969                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1970    
1971          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1972          LoadSubChunksRecursively();          {
1973                // divide progress into subprogress
1974                progress_t subprogress;
1975                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
1976                // do the actual work
1977                LoadSubChunksRecursively(&subprogress);
1978                // notify subprogress done
1979                __notify_progress(&subprogress, 1.f);
1980            }
1981    
1982          if (Filename.length() > 0) SetMode(stream_mode_read);          if (!bIsNewFile) SetMode(stream_mode_read);
1983          // 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
1984          #if POSIX          #if POSIX
1985          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);
1986          if (hFileWrite < 0) {          if (hFileWrite == -1) {
1987              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1988              throw Exception("Could not open file \"" + path + "\" for writing");              String sError = strerror(errno);
1989                throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
1990          }          }
1991          #elif defined(WIN32)          #elif defined(WIN32)
1992          hFileWrite = CreateFile(          hFileWrite = CreateFile(
# Line 1712  namespace RIFF { Line 2007  namespace RIFF {
2007          #endif // POSIX          #endif // POSIX
2008          Mode = stream_mode_read_write;          Mode = stream_mode_read_write;
2009    
2010            // get the overall file size required to save this file
2011            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
2012    
2013            // determine whether this file will yield in a large file (>=4GB) and
2014            // the RIFF file offset size to be used accordingly for all chunks
2015            FileOffsetSize = FileOffsetSizeFor(newFileSize);
2016    
2017          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
2018          unsigned long ulTotalSize  = WriteChunk(0, 0);          file_offset_t ullTotalSize;
2019          unsigned long ulActualSize = __GetFileSize(hFileWrite);          {
2020                // divide progress into subprogress
2021                progress_t subprogress;
2022                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
2023                // do the actual work
2024                ullTotalSize = WriteChunk(0, 0, &subprogress);
2025                // notify subprogress done
2026                __notify_progress(&subprogress, 1.f);
2027            }
2028            file_offset_t ullActualSize = __GetFileSize(hFileWrite);
2029    
2030          // resize file to the final size (if the file was originally larger)          // resize file to the final size (if the file was originally larger)
2031          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ullActualSize > ullTotalSize) ResizeFile(ullTotalSize);
   
         // forget all resized chunks  
         ResizedChunks.clear();  
2032    
2033          #if POSIX          #if POSIX
2034          if (hFileWrite) close(hFileWrite);          if (hFileWrite) close(hFileWrite);
# Line 1733  namespace RIFF { Line 2041  namespace RIFF {
2041    
2042          // associate new file with this File object from now on          // associate new file with this File object from now on
2043          Filename = path;          Filename = path;
2044            bIsNewFile = false;
2045          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
2046          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.
2047    
2048            __notify_progress(pProgress, 1.0); // notify done
2049      }      }
2050    
2051      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(file_offset_t ullNewSize) {
2052          #if POSIX          #if POSIX
2053          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ullNewSize) < 0)
2054              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
2055          #elif defined(WIN32)          #elif defined(WIN32)
2056            const LARGE_INTEGER liFilePos = { .QuadPart = ullNewSize };
2057          if (          if (
2058              SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||              !SetFilePointerEx(hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN) ||
2059              !SetEndOfFile(hFileWrite)              !SetEndOfFile(hFileWrite)
2060          ) throw Exception("Could not resize file \"" + Filename + "\"");          ) throw Exception("Could not resize file \"" + Filename + "\"");
2061          #else          #else
# Line 1753  namespace RIFF { Line 2065  namespace RIFF {
2065      }      }
2066    
2067      File::~File() {      File::~File() {
2068         #if DEBUG          #if DEBUG
2069         std::cout << "File::~File()" << std::endl;          std::cout << "File::~File()" << std::endl;
2070         #endif // DEBUG          #endif // DEBUG
2071            Cleanup();
2072        }
2073    
2074        /**
2075         * Returns @c true if this file has been created new from scratch and
2076         * has not been stored to disk yet.
2077         */
2078        bool File::IsNew() const {
2079            return bIsNewFile;
2080        }
2081    
2082        void File::Cleanup() {
2083          #if POSIX          #if POSIX
2084          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
2085          #elif defined(WIN32)          #elif defined(WIN32)
# Line 1767  namespace RIFF { Line 2091  namespace RIFF {
2091          pFile = NULL;          pFile = NULL;
2092      }      }
2093    
2094      void File::LogAsResized(Chunk* pResizedChunk) {      /**
2095          ResizedChunks.insert(pResizedChunk);       * Returns the current size of this file (in bytes) as it is currently
2096         * yet stored on disk. If this file does not yet exist on disk (i.e. when
2097         * this RIFF File has just been created from scratch and Save() has not
2098         * been called yet) then this method returns 0.
2099         */
2100        file_offset_t File::GetCurrentFileSize() const {
2101            file_offset_t size = 0;
2102            try {
2103                size = __GetFileSize(hFileRead);
2104            } catch (...) {
2105                size = 0;
2106            }
2107            return size;
2108      }      }
2109    
2110      void File::UnlogResized(Chunk* pResizedChunk) {      /**
2111          ResizedChunks.erase(pResizedChunk);       * Returns the required size (in bytes) for this RIFF File to be saved to
2112         * disk. The precise size of the final file on disk depends on the RIFF
2113         * file offset size actually used internally in all headers of the RIFF
2114         * chunks. By default libgig handles the required file offset size
2115         * automatically for you; that means it is using 32 bit offsets for files
2116         * smaller than 4 GB and 64 bit offsets for files equal or larger than
2117         * 4 GB. You may however also override this default behavior by passing the
2118         * respective option to the RIFF File constructor to force one particular
2119         * offset size. In the latter case this method will return the file size
2120         * for the requested forced file offset size that will be used when calling
2121         * Save() later on.
2122         *
2123         * You may also use the overridden method below to get the file size for
2124         * an arbitrary other file offset size instead.
2125         *
2126         * @see offset_size_t
2127         * @see GetFileOffsetSize()
2128         */
2129        file_offset_t File::GetRequiredFileSize() {
2130            return GetRequiredFileSize(FileOffsetPreference);
2131      }      }
2132    
2133      unsigned long File::GetFileSize() {      /**
2134          return __GetFileSize(hFileRead);       * Returns the rquired size (in bytes) for this RIFF file to be saved to
2135         * disk, assuming the passed @a fileOffsestSize would be used for the
2136         * Save() operation.
2137         *
2138         * This overridden method essentialy behaves like the above method, with
2139         * the difference that you must provide a specific RIFF @a fileOffsetSize
2140         * for calculating the theoretical final file size.
2141         *
2142         * @see GetFileOffsetSize()
2143         */
2144        file_offset_t File::GetRequiredFileSize(offset_size_t fileOffsetSize) {
2145            switch (fileOffsetSize) {
2146                case offset_size_auto: {
2147                    file_offset_t fileSize = GetRequiredFileSize(offset_size_32bit);
2148                    if (fileSize >> 32)
2149                        return GetRequiredFileSize(offset_size_64bit);
2150                    else
2151                        return fileSize;
2152                }
2153                case offset_size_32bit: break;
2154                case offset_size_64bit: break;
2155                default: throw Exception("Internal error: Invalid RIFF::offset_size_t");
2156            }
2157            return RequiredPhysicalSize(FileOffsetSize);
2158        }
2159    
2160        int File::FileOffsetSizeFor(file_offset_t fileSize) const {
2161            switch (FileOffsetPreference) {
2162                case offset_size_auto:
2163                    return (fileSize >> 32) ? 8 : 4;
2164                case offset_size_32bit:
2165                    return 4;
2166                case offset_size_64bit:
2167                    return 8;
2168                default:
2169                    throw Exception("Internal error: Invalid RIFF::offset_size_t");
2170            }
2171        }
2172    
2173        /**
2174         * Returns the current size (in bytes) of file offsets stored in the
2175         * headers of all chunks of this file.
2176         *
2177         * Most RIFF files are using 32 bit file offsets internally, which limits
2178         * them to a maximum file size of less than 4 GB though. In contrast to the
2179         * common standard, this RIFF File class implementation supports handling of
2180         * RIFF files equal or larger than 4 GB. In such cases 64 bit file offsets
2181         * have to be used in all headers of all RIFF Chunks when being stored to a
2182         * physical file. libgig by default automatically selects the correct file
2183         * offset size for you. You may however also force one particular file
2184         * offset size by supplying the respective option to the RIFF::File
2185         * constructor.
2186         *
2187         * This method can be used to check which RIFF file offset size is currently
2188         * being used for this RIFF File.
2189         *
2190         * @returns current RIFF file offset size used (in bytes)
2191         * @see offset_size_t
2192         */
2193        int File::GetFileOffsetSize() const {
2194            return FileOffsetSize;
2195        }
2196    
2197        /**
2198         * Returns the required size (in bytes) of file offsets stored in the
2199         * headers of all chunks of this file if the current RIFF tree would be
2200         * saved to disk by calling Save().
2201         *
2202         * See GetFileOffsetSize() for mor details about RIFF file offsets.
2203         *
2204         * @returns RIFF file offset size required (in bytes) if being saved
2205         * @see offset_size_t
2206         */
2207        int File::GetRequiredFileOffsetSize() {
2208            return FileOffsetSizeFor(GetCurrentFileSize());
2209      }      }
2210    
2211      #if POSIX      #if POSIX
2212      unsigned long File::__GetFileSize(int hFile) {      file_offset_t File::__GetFileSize(int hFile) const {
2213          struct stat filestat;          struct stat filestat;
2214          fstat(hFile, &filestat);          if (fstat(hFile, &filestat) == -1)
2215          long size = filestat.st_size;              throw Exception("POSIX FS error: could not determine file size");
2216          return size;          return filestat.st_size;
2217      }      }
2218      #elif defined(WIN32)      #elif defined(WIN32)
2219      unsigned long File::__GetFileSize(HANDLE hFile) {      file_offset_t File::__GetFileSize(HANDLE hFile) const {
2220          DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);          LARGE_INTEGER size;
2221          if (dwSize == INVALID_FILE_SIZE)          if (!GetFileSizeEx(hFile, &size))
2222              throw Exception("Windows FS error: could not determine file size");              throw Exception("Windows FS error: could not determine file size");
2223          return dwSize;          return size.QuadPart;
2224      }      }
2225      #else // standard C functions      #else // standard C functions
2226      unsigned long File::__GetFileSize(FILE* hFile) {      file_offset_t File::__GetFileSize(FILE* hFile) const {
2227          long curpos = ftell(hFile);          off_t curpos = ftello(hFile);
2228          fseek(hFile, 0, SEEK_END);          if (fseeko(hFile, 0, SEEK_END) == -1)
2229          long size = ftell(hFile);              throw Exception("FS error: could not determine file size");
2230          fseek(hFile, curpos, SEEK_SET);          off_t size = ftello(hFile);
2231            fseeko(hFile, curpos, SEEK_SET);
2232          return size;          return size;
2233      }      }
2234      #endif      #endif

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

  ViewVC Help
Powered by ViewVC