/[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 2911 by schoenebeck, Tue Jan 13 15:28:37 2015 UTC revision 2912 by schoenebeck, Tue May 17 14:30:10 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-2015 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 73  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) {          if (SetFilePointerEx(pFile->hFileRead, filePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
129              DWORD dwBytesRead;              DWORD dwBytesRead;
130              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
131              ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);              ReadFile(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize, &dwBytesRead, NULL);
132          #else          #else
133          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseeko(pFile->hFileRead, filePos, SEEK_SET)) {
134              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
135              fread(&CurrentChunkSize, 4, 1, pFile->hFileRead);              fread(&ullCurrentChunkSize, pFile->FileOffsetSize, 1, pFile->hFileRead);
136          #endif // POSIX          #endif // POSIX
137              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
138              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
# Line 147  namespace RIFF { Line 146  namespace RIFF {
146              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
147              if (!pFile->bEndianNative) {              if (!pFile->bEndianNative) {
148                  //swapBytes_32(&ChunkID);                  //swapBytes_32(&ChunkID);
149                  swapBytes_32(&CurrentChunkSize);                  if (pFile->FileOffsetSize == 4)
150                        swapBytes_32(&ullCurrentChunkSize);
151                    else
152                        swapBytes_64(&ullCurrentChunkSize);
153              }              }
154              #if DEBUG              #if DEBUG
155              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
156              std::cout << "ckSize=" << CurrentChunkSize << " ";              std::cout << "ckSize=" << ullCurrentChunkSize << " ";
157              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
158              #endif // DEBUG              #endif // DEBUG
159              NewChunkSize = CurrentChunkSize;              ullNewChunkSize = ullCurrentChunkSize;
160          }          }
161      }      }
162    
163      void Chunk::WriteHeader(unsigned long fPos) {      void Chunk::WriteHeader(file_offset_t filePos) {
164          uint32_t uiNewChunkID = ChunkID;          uint32_t uiNewChunkID = ChunkID;
165          if (ChunkID == CHUNK_ID_RIFF) {          if (ChunkID == CHUNK_ID_RIFF) {
166              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
# Line 168  namespace RIFF { Line 170  namespace RIFF {
170              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
171          }          }
172    
173          uint32_t uiNewChunkSize = NewChunkSize;          uint64_t ullNewChunkSize = this->ullNewChunkSize;
174          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
175              swapBytes_32(&uiNewChunkSize);              if (pFile->FileOffsetSize == 4)
176                    swapBytes_32(&ullNewChunkSize);
177                else
178                    swapBytes_64(&ullNewChunkSize);
179          }          }
180    
181          #if POSIX          #if POSIX
182          if (lseek(pFile->hFileWrite, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileWrite, filePos, SEEK_SET) != -1) {
183              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
184              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize);
185          }          }
186          #elif defined(WIN32)          #elif defined(WIN32)
187          if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {          if (SetFilePointerEx(pFile->hFileWrite, filePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
188              DWORD dwBytesWritten;              DWORD dwBytesWritten;
189              WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
190              WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize, &dwBytesWritten, NULL);
191          }          }
192          #else          #else
193          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseeko(pFile->hFileWrite, filePos, SEEK_SET)) {
194              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
195              fwrite(&uiNewChunkSize, 4, 1, pFile->hFileWrite);              fwrite(&ullNewChunkSize, pFile->FileOffsetSize, 1, pFile->hFileWrite);
196          }          }
197          #endif // POSIX          #endif // POSIX
198      }      }
# Line 196  namespace RIFF { Line 201  namespace RIFF {
201       *  Returns the String representation of the chunk's ID (e.g. "RIFF",       *  Returns the String representation of the chunk's ID (e.g. "RIFF",
202       *  "LIST").       *  "LIST").
203       */       */
204      String Chunk::GetChunkIDString() {      String Chunk::GetChunkIDString() const {
205          return convertToString(ChunkID);          return convertToString(ChunkID);
206      }      }
207    
# Line 212  namespace RIFF { Line 217  namespace RIFF {
217       *                  if omitted \a Where relates to beginning of the chunk       *                  if omitted \a Where relates to beginning of the chunk
218       *                  data       *                  data
219       */       */
220      unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {      file_offset_t Chunk::SetPos(file_offset_t Where, stream_whence_t Whence) {
221       #if DEBUG          #if DEBUG
222       std::cout << "Chunk::SetPos(ulong)" << std::endl;          std::cout << "Chunk::SetPos(file_offset_t,stream_whence_t)" << std::endl;
223       #endif // DEBUG          #endif // DEBUG
224          switch (Whence) {          switch (Whence) {
225              case stream_curpos:              case stream_curpos:
226                  ulPos += Where;                  ullPos += Where;
227                  break;                  break;
228              case stream_end:              case stream_end:
229                  ulPos = CurrentChunkSize - 1 - Where;                  ullPos = ullCurrentChunkSize - 1 - Where;
230                  break;                  break;
231              case stream_backward:              case stream_backward:
232                  ulPos -= Where;                  ullPos -= Where;
233                  break;                  break;
234              case stream_start: default:              case stream_start: default:
235                  ulPos = Where;                  ullPos = Where;
236                  break;                  break;
237          }          }
238          if (ulPos > CurrentChunkSize) ulPos = CurrentChunkSize;          if (ullPos > ullCurrentChunkSize) ullPos = ullCurrentChunkSize;
239          return ulPos;          return ullPos;
240      }      }
241    
242      /**      /**
# Line 244  namespace RIFF { Line 249  namespace RIFF {
249       *       *
250       *  @returns  number of bytes left to read       *  @returns  number of bytes left to read
251       */       */
252      unsigned long Chunk::RemainingBytes() {      file_offset_t Chunk::RemainingBytes() const {
253         #if DEBUG          #if DEBUG
254         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;          std::cout << "Chunk::Remainingbytes()=" << ullCurrentChunkSize - ullPos << std::endl;
255         #endif // DEBUG          #endif // DEBUG
256          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;          return (ullCurrentChunkSize > ullPos) ? ullCurrentChunkSize - ullPos : 0;
257        }
258    
259        /**
260         *  Returns the actual total size in bytes (including header) of this Chunk
261         *  if being stored to a file.
262         *
263         *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
264         *                          being saved to a file
265         */
266        file_offset_t Chunk::RequiredPhysicalSize(int fileOffsetSize) {
267            return CHUNK_HEADER_SIZE(fileOffsetSize) + // RIFF chunk header
268                   ullNewChunkSize + // chunks's actual data body
269                   ullNewChunkSize % 2; // optional pad byte
270      }      }
271    
272      /**      /**
# Line 262  namespace RIFF { Line 280  namespace RIFF {
280       *    already reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
281       *    possible without SetPos()       *    possible without SetPos()
282       */       */
283      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() const {
284        #if DEBUG          #if DEBUG
285        std::cout << "Chunk::GetState()" << std::endl;          std::cout << "Chunk::GetState()" << std::endl;
286        #endif // DEBUG          #endif // DEBUG
287          #if POSIX          #if POSIX
288          if (pFile->hFileRead == 0) return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
289          #elif defined (WIN32)          #elif defined (WIN32)
# Line 274  namespace RIFF { Line 292  namespace RIFF {
292          #else          #else
293          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
294          #endif // POSIX          #endif // POSIX
295          if (ulPos < CurrentChunkSize) return stream_ready;          if (ullPos < ullCurrentChunkSize) return stream_ready;
296          else                          return stream_end_reached;          else                              return stream_end_reached;
297      }      }
298    
299      /**      /**
# Line 293  namespace RIFF { Line 311  namespace RIFF {
311       *  @returns          number of successfully read data words or 0 if end       *  @returns          number of successfully read data words or 0 if end
312       *                    of file reached or error occured       *                    of file reached or error occured
313       */       */
314      unsigned long Chunk::Read(void* pData, unsigned long WordCount, unsigned long WordSize) {      file_offset_t Chunk::Read(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
315         #if DEBUG          #if DEBUG
316         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;          std::cout << "Chunk::Read(void*,file_offset_t,file_offset_t)" << std::endl;
317         #endif // DEBUG          #endif // DEBUG
318          //if (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)
319          if (ulPos >= CurrentChunkSize) return 0;          if (ullPos >= ullCurrentChunkSize) return 0;
320          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ullPos + WordCount * WordSize >= ullCurrentChunkSize) WordCount = (ullCurrentChunkSize - ullPos) / WordSize;
321          #if POSIX          #if POSIX
322          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET) < 0) return 0;
323          ssize_t readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          ssize_t readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
324          if (readWords < 1) {          if (readWords < 1) {
325              #if DEBUG              #if DEBUG
# Line 311  namespace RIFF { Line 329  namespace RIFF {
329          }          }
330          readWords /= WordSize;          readWords /= WordSize;
331          #elif defined(WIN32)          #elif defined(WIN32)
332          if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;          if (!SetFilePointerEx(pFile->hFileRead, ullStartPos + ullPos, NULL/*new pos pointer*/, FILE_BEGIN))
333                return 0;
334          DWORD readWords;          DWORD readWords;
335          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)
336          if (readWords < 1) return 0;          if (readWords < 1) return 0;
337          readWords /= WordSize;          readWords /= WordSize;
338          #else // standard C functions          #else // standard C functions
339          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseeko(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET)) return 0;
340          size_t readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          file_offset_t readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
341          #endif // POSIX          #endif // POSIX
342          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
343              switch (WordSize) {              switch (WordSize) {
344                  case 2:                  case 2:
345                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
346                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
347                      break;                      break;
348                  case 4:                  case 4:
349                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
350                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
351                      break;                      break;
352                    case 8:
353                        for (file_offset_t iWord = 0; iWord < readWords; iWord++)
354                            swapBytes_64((uint64_t*) pData + iWord);
355                        break;
356                  default:                  default:
357                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
358                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
359                      break;                      break;
360              }              }
# Line 356  namespace RIFF { Line 379  namespace RIFF {
379       *                           chunk size or any IO error occured       *                           chunk size or any IO error occured
380       *  @see Resize()       *  @see Resize()
381       */       */
382      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) {
383          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
384              throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");              throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
385          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)          if (ullPos >= ullCurrentChunkSize || ullPos + WordCount * WordSize > ullCurrentChunkSize)
386              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
387          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
388              switch (WordSize) {              switch (WordSize) {
389                  case 2:                  case 2:
390                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
391                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
392                      break;                      break;
393                  case 4:                  case 4:
394                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
395                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
396                      break;                      break;
397                    case 8:
398                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
399                            swapBytes_64((uint64_t*) pData + iWord);
400                        break;
401                  default:                  default:
402                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
403                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
404                      break;                      break;
405              }              }
406          }          }
407          #if POSIX          #if POSIX
408          if (lseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET) < 0) {          if (lseek(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET) < 0) {
409              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ullPos) +
410                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
411          }          }
412          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          ssize_t writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
413          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");
414          writtenWords /= WordSize;          writtenWords /= WordSize;
415          #elif defined(WIN32)          #elif defined(WIN32)
416          if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {          if (!SetFilePointerEx(pFile->hFileWrite, ullStartPos + ullPos, NULL/*new pos pointer*/, FILE_BEGIN)) {
417              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ullPos) +
418                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
419          }          }
420          DWORD writtenWords;          DWORD writtenWords;
421          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)
422          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");
423          writtenWords /= WordSize;          writtenWords /= WordSize;
424          #else // standard C functions          #else // standard C functions
425          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseeko(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET)) {
426              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ullPos) +
427                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
428          }          }
429          unsigned long writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);          file_offset_t writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
430          #endif // POSIX          #endif // POSIX
431          SetPos(writtenWords * WordSize, stream_curpos);          SetPos(writtenWords * WordSize, stream_curpos);
432          return writtenWords;          return writtenWords;
433      }      }
434    
435      /** Just an internal wrapper for the main <i>Read()</i> method with additional Exception throwing on errors. */      /** Just an internal wrapper for the main <i>Read()</i> method with additional Exception throwing on errors. */
436      unsigned long Chunk::ReadSceptical(void* pData, unsigned long WordCount, unsigned long WordSize) {      file_offset_t Chunk::ReadSceptical(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
437          unsigned long readWords = Read(pData, WordCount, WordSize);          file_offset_t readWords = Read(pData, WordCount, WordSize);
438          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");
439          return readWords;          return readWords;
440      }      }
# Line 423  namespace RIFF { Line 450  namespace RIFF {
450       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
451       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
452       */       */
453      unsigned long Chunk::ReadInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt8(int8_t* pData, file_offset_t WordCount) {
454         #if DEBUG          #if DEBUG
455         std::cout << "Chunk::ReadInt8(int8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt8(int8_t*,file_offset_t)" << std::endl;
456         #endif // DEBUG          #endif // DEBUG
457          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
458      }      }
459    
# Line 444  namespace RIFF { Line 471  namespace RIFF {
471       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
472       * @see Resize()       * @see Resize()
473       */       */
474      unsigned long Chunk::WriteInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt8(int8_t* pData, file_offset_t WordCount) {
475          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
476      }      }
477    
# Line 460  namespace RIFF { Line 487  namespace RIFF {
487       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
488       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
489       */       */
490      unsigned long Chunk::ReadUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint8(uint8_t* pData, file_offset_t WordCount) {
491         #if DEBUG          #if DEBUG
492         std::cout << "Chunk::ReadUint8(uint8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint8(uint8_t*,file_offset_t)" << std::endl;
493         #endif // DEBUG          #endif // DEBUG
494          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
495      }      }
496    
# Line 481  namespace RIFF { Line 508  namespace RIFF {
508       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
509       * @see Resize()       * @see Resize()
510       */       */
511      unsigned long Chunk::WriteUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint8(uint8_t* pData, file_offset_t WordCount) {
512          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
513      }      }
514    
# Line 497  namespace RIFF { Line 524  namespace RIFF {
524       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
525       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
526       */       */
527      unsigned long Chunk::ReadInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt16(int16_t* pData, file_offset_t WordCount) {
528        #if DEBUG          #if DEBUG
529        std::cout << "Chunk::ReadInt16(int16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt16(int16_t*,file_offset_t)" << std::endl;
530        #endif // DEBUG          #endif // DEBUG
531          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
532      }      }
533    
# Line 518  namespace RIFF { Line 545  namespace RIFF {
545       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
546       * @see Resize()       * @see Resize()
547       */       */
548      unsigned long Chunk::WriteInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt16(int16_t* pData, file_offset_t WordCount) {
549          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
550      }      }
551    
# Line 534  namespace RIFF { Line 561  namespace RIFF {
561       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
562       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
563       */       */
564      unsigned long Chunk::ReadUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint16(uint16_t* pData, file_offset_t WordCount) {
565        #if DEBUG          #if DEBUG
566        std::cout << "Chunk::ReadUint16(uint16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint16(uint16_t*,file_offset_t)" << std::endl;
567        #endif // DEBUG          #endif // DEBUG
568          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
569      }      }
570    
# Line 555  namespace RIFF { Line 582  namespace RIFF {
582       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
583       * @see Resize()       * @see Resize()
584       */       */
585      unsigned long Chunk::WriteUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint16(uint16_t* pData, file_offset_t WordCount) {
586          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
587      }      }
588    
# Line 571  namespace RIFF { Line 598  namespace RIFF {
598       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
599       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
600       */       */
601      unsigned long Chunk::ReadInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt32(int32_t* pData, file_offset_t WordCount) {
602         #if DEBUG          #if DEBUG
603         std::cout << "Chunk::ReadInt32(int32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt32(int32_t*,file_offset_t)" << std::endl;
604         #endif // DEBUG          #endif // DEBUG
605          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
606      }      }
607    
# Line 592  namespace RIFF { Line 619  namespace RIFF {
619       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
620       * @see Resize()       * @see Resize()
621       */       */
622      unsigned long Chunk::WriteInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt32(int32_t* pData, file_offset_t WordCount) {
623          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
624      }      }
625    
# Line 608  namespace RIFF { Line 635  namespace RIFF {
635       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occured or less than
636       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
637       */       */
638      unsigned long Chunk::ReadUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint32(uint32_t* pData, file_offset_t WordCount) {
639         #if DEBUG          #if DEBUG
640         std::cout << "Chunk::ReadUint32(uint32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint32(uint32_t*,file_offset_t)" << std::endl;
641         #endif // DEBUG          #endif // DEBUG
642          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
643      }      }
644    
# Line 646  namespace RIFF { Line 673  namespace RIFF {
673       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occured
674       * @see Resize()       * @see Resize()
675       */       */
676      unsigned long Chunk::WriteUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint32(uint32_t* pData, file_offset_t WordCount) {
677          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
678      }      }
679    
# Line 658  namespace RIFF { Line 685  namespace RIFF {
685       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
686       */       */
687      int8_t Chunk::ReadInt8() {      int8_t Chunk::ReadInt8() {
688        #if DEBUG          #if DEBUG
689        std::cout << "Chunk::ReadInt8()" << std::endl;          std::cout << "Chunk::ReadInt8()" << std::endl;
690        #endif // DEBUG          #endif // DEBUG
691          int8_t word;          int8_t word;
692          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
693          return word;          return word;
# Line 674  namespace RIFF { Line 701  namespace RIFF {
701       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
702       */       */
703      uint8_t Chunk::ReadUint8() {      uint8_t Chunk::ReadUint8() {
704        #if DEBUG          #if DEBUG
705        std::cout << "Chunk::ReadUint8()" << std::endl;          std::cout << "Chunk::ReadUint8()" << std::endl;
706        #endif // DEBUG          #endif // DEBUG
707          uint8_t word;          uint8_t word;
708          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
709          return word;          return word;
# Line 691  namespace RIFF { Line 718  namespace RIFF {
718       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
719       */       */
720      int16_t Chunk::ReadInt16() {      int16_t Chunk::ReadInt16() {
721        #if DEBUG          #if DEBUG
722        std::cout << "Chunk::ReadInt16()" << std::endl;          std::cout << "Chunk::ReadInt16()" << std::endl;
723        #endif // DEBUG          #endif // DEBUG
724          int16_t word;          int16_t word;
725          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
726          return word;          return word;
# Line 708  namespace RIFF { Line 735  namespace RIFF {
735       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
736       */       */
737      uint16_t Chunk::ReadUint16() {      uint16_t Chunk::ReadUint16() {
738        #if DEBUG          #if DEBUG
739        std::cout << "Chunk::ReadUint16()" << std::endl;          std::cout << "Chunk::ReadUint16()" << std::endl;
740        #endif // DEBUG          #endif // DEBUG
741          uint16_t word;          uint16_t word;
742          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
743          return word;          return word;
# Line 725  namespace RIFF { Line 752  namespace RIFF {
752       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
753       */       */
754      int32_t Chunk::ReadInt32() {      int32_t Chunk::ReadInt32() {
755        #if DEBUG          #if DEBUG
756        std::cout << "Chunk::ReadInt32()" << std::endl;          std::cout << "Chunk::ReadInt32()" << std::endl;
757        #endif // DEBUG          #endif // DEBUG
758          int32_t word;          int32_t word;
759          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
760          return word;          return word;
# Line 742  namespace RIFF { Line 769  namespace RIFF {
769       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occured
770       */       */
771      uint32_t Chunk::ReadUint32() {      uint32_t Chunk::ReadUint32() {
772        #if DEBUG          #if DEBUG
773        std::cout << "Chunk::ReadUint32()" << std::endl;          std::cout << "Chunk::ReadUint32()" << std::endl;
774        #endif // DEBUG          #endif // DEBUG
775          uint32_t word;          uint32_t word;
776          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
777          return word;          return word;
# Line 774  namespace RIFF { Line 801  namespace RIFF {
801      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
802          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
803              #if POSIX              #if POSIX
804              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ullStartPos, SEEK_SET) == -1) return NULL;
805              #elif defined(WIN32)              #elif defined(WIN32)
806              if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;              if (!SetFilePointerEx(pFile->hFileRead, ullStartPos, NULL/*new pos pointer*/, FILE_BEGIN)) return NULL;
807              #else              #else
808              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseeko(pFile->hFileRead, ullStartPos, SEEK_SET)) return NULL;
809              #endif // POSIX              #endif // POSIX
810              unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;              file_offset_t ullBufferSize = (ullCurrentChunkSize > ullNewChunkSize) ? ullCurrentChunkSize : ullNewChunkSize;
811              pChunkData = new uint8_t[ulBufferSize];              pChunkData = new uint8_t[ullBufferSize];
812              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
813              memset(pChunkData, 0, ulBufferSize);              memset(pChunkData, 0, ullBufferSize);
814              #if POSIX              #if POSIX
815              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());              file_offset_t readWords = read(pFile->hFileRead, pChunkData, GetSize());
816              #elif defined(WIN32)              #elif defined(WIN32)
817              DWORD readWords;              DWORD readWords;
818              ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);              ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL); //FIXME: won't load chunks larger than 2GB !
819              #else              #else
820              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              file_offset_t readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
821              #endif // POSIX              #endif // POSIX
822              if (readWords != GetSize()) {              if (readWords != GetSize()) {
823                  delete[] pChunkData;                  delete[] pChunkData;
824                  return (pChunkData = NULL);                  return (pChunkData = NULL);
825              }              }
826              ulChunkDataSize = ulBufferSize;              ullChunkDataSize = ullBufferSize;
827          } else if (NewChunkSize > ulChunkDataSize) {          } else if (ullNewChunkSize > ullChunkDataSize) {
828              uint8_t* pNewBuffer = new uint8_t[NewChunkSize];              uint8_t* pNewBuffer = new uint8_t[ullNewChunkSize];
829              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");
830              memset(pNewBuffer, 0 , NewChunkSize);              memset(pNewBuffer, 0 , ullNewChunkSize);
831              memcpy(pNewBuffer, pChunkData, ulChunkDataSize);              memcpy(pNewBuffer, pChunkData, ullChunkDataSize);
832              delete[] pChunkData;              delete[] pChunkData;
833              pChunkData      = pNewBuffer;              pChunkData       = pNewBuffer;
834              ulChunkDataSize = NewChunkSize;              ullChunkDataSize = ullNewChunkSize;
835          }          }
836          return pChunkData;          return pChunkData;
837      }      }
# Line 836  namespace RIFF { Line 863  namespace RIFF {
863       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
864       * boundary!       * boundary!
865       *       *
866       * @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)
867       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a NewSize is less than 1 or Unrealistic large
868       * @see File::Save()       * @see File::Save()
869       */       */
870      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(file_offset_t NewSize) {
871          if (iNewSize <= 0)          if (NewSize == 0)
872              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));
873          if (NewChunkSize == iNewSize) return;          if ((NewSize >> 48) != 0)
874          NewChunkSize = iNewSize;              throw Exception("Unrealistic high chunk size detected: " + __resolveChunkPath(this));
875          pFile->LogAsResized(this);          if (ullNewChunkSize == NewSize) return;
876            ullNewChunkSize = NewSize;
877      }      }
878    
879      /** @brief Write chunk persistently e.g. to disk.      /** @brief Write chunk persistently e.g. to disk.
880       *       *
881       * Stores the chunk persistently to its actual "physical" file.       * Stores the chunk persistently to its actual "physical" file.
882       *       *
883       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
884       *                     chunk should be written to       *                     chunk should be written to
885       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
886       *                              the file       *                              the file
887       * @param pProgress - optional: callback function for progress notification       * @param pProgress - optional: callback function for progress notification
888       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
889       *          \a ulWritePos incremented by this chunk's new size       *          \a ullWritePos incremented by this chunk's new size
890       *          (including its header size of course)       *          (including its header size of course)
891       */       */
892      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset, progress_t* pProgress) {      file_offset_t Chunk::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
893          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
894          ulWritePos += CHUNK_HEADER_SIZE;          ullWritePos += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
895    
896          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
897              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 874  namespace RIFF { Line 902  namespace RIFF {
902              LoadChunkData();              LoadChunkData();
903              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
904              #if POSIX              #if POSIX
905              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(pFile->hFileWrite, ullWritePos, SEEK_SET);
906              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, ullNewChunkSize) != ullNewChunkSize) {
907                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
908              }              }
909              #elif defined(WIN32)              #elif defined(WIN32)
910              SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);              SetFilePointerEx(pFile->hFileWrite, ullWritePos, NULL/*new pos pointer*/, FILE_BEGIN);
911              DWORD dwBytesWritten;              DWORD dwBytesWritten;
912              WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, pChunkData, ullNewChunkSize, &dwBytesWritten, NULL); //FIXME: won't save chunks larger than 2GB !
913              if (dwBytesWritten != NewChunkSize) {              if (dwBytesWritten != ullNewChunkSize) {
914                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
915              }              }
916              #else              #else
917              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseeko(pFile->hFileWrite, ullWritePos, SEEK_SET);
918              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, ullNewChunkSize, pFile->hFileWrite) != ullNewChunkSize) {
919                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
920              }              }
921              #endif // POSIX              #endif // POSIX
922          } else {          } else {
923              // 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
924              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
925              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              file_offset_t ullToMove = (ullNewChunkSize < ullCurrentChunkSize) ? ullNewChunkSize : ullCurrentChunkSize;
926              #if defined(WIN32)              #if defined(WIN32)
927              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
928              #else              #else
929              int iBytesMoved = 1;              int iBytesMoved = 1;
930              #endif              #endif
931              for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (file_offset_t ullOffset = 0; ullToMove > 0 && iBytesMoved > 0; ullOffset += iBytesMoved, ullToMove -= iBytesMoved) {
932                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ullToMove < 4096) ? ullToMove : 4096;
933                  #if POSIX                  #if POSIX
934                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
935                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
936                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
937                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
938                  #elif defined(WIN32)                  #elif defined(WIN32)
939                  SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  SetFilePointerEx(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, NULL/*new pos pointer*/, FILE_BEGIN);
940                  ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
941                  SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  SetFilePointerEx(pFile->hFileWrite, ullWritePos + ullOffset, NULL/*new pos pointer*/, FILE_BEGIN);
942                  WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
943                  #else                  #else
944                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseeko(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
945                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
946                  fseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  fseeko(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
947                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
948                  #endif                  #endif
949              }              }
# Line 924  namespace RIFF { Line 952  namespace RIFF {
952          }          }
953    
954          // update this chunk's header          // update this chunk's header
955          CurrentChunkSize = NewChunkSize;          ullCurrentChunkSize = ullNewChunkSize;
956          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
957    
958          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
959    
960          // update chunk's position pointers          // update chunk's position pointers
961          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;          ullStartPos = ullOriginalPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
962          ulPos      = 0;          ullPos      = 0;
963    
964          // add pad byte if needed          // add pad byte if needed
965          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ullStartPos + ullNewChunkSize) % 2 != 0) {
966              const char cPadByte = 0;              const char cPadByte = 0;
967              #if POSIX              #if POSIX
968              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
969              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
970              #elif defined(WIN32)              #elif defined(WIN32)
971              SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);              SetFilePointerEx(pFile->hFileWrite, ullStartPos + ullNewChunkSize, NULL/*new pos pointer*/, FILE_BEGIN);
972              DWORD dwBytesWritten;              DWORD dwBytesWritten;
973              WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);              WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
974              #else              #else
975              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseeko(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
976              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
977              #endif              #endif
978              return ulStartPos + NewChunkSize + 1;              return ullStartPos + ullNewChunkSize + 1;
979          }          }
980    
981          return ulStartPos + NewChunkSize;          return ullStartPos + ullNewChunkSize;
982      }      }
983    
984      void Chunk::__resetPos() {      void Chunk::__resetPos() {
985          ulPos = 0;          ullPos = 0;
986      }      }
987    
988    
# Line 963  namespace RIFF { Line 991  namespace RIFF {
991  // *  // *
992    
993      List::List(File* pFile) : Chunk(pFile) {      List::List(File* pFile) : Chunk(pFile) {
994        #if DEBUG          #if DEBUG
995        std::cout << "List::List(File* pFile)" << std::endl;          std::cout << "List::List(File* pFile)" << std::endl;
996        #endif // DEBUG          #endif // DEBUG
997          pSubChunks    = NULL;          pSubChunks    = NULL;
998          pSubChunksMap = NULL;          pSubChunksMap = NULL;
999      }      }
1000    
1001      List::List(File* pFile, unsigned long StartPos, List* Parent)      List::List(File* pFile, file_offset_t StartPos, List* Parent)
1002        : Chunk(pFile, StartPos, Parent) {        : Chunk(pFile, StartPos, Parent) {
1003          #if DEBUG          #if DEBUG
1004          std::cout << "List::List(File*,ulong,bool,List*)" << std::endl;          std::cout << "List::List(File*,file_offset_t,List*)" << std::endl;
1005          #endif // DEBUG          #endif // DEBUG
1006          pSubChunks    = NULL;          pSubChunks    = NULL;
1007          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1008          ReadHeader(StartPos);          ReadHeader(StartPos);
1009          ulStartPos    = StartPos + LIST_HEADER_SIZE;          ullStartPos = StartPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1010      }      }
1011    
1012      List::List(File* pFile, List* pParent, uint32_t uiListID)      List::List(File* pFile, List* pParent, uint32_t uiListID)
# Line 989  namespace RIFF { Line 1017  namespace RIFF {
1017      }      }
1018    
1019      List::~List() {      List::~List() {
1020        #if DEBUG          #if DEBUG
1021        std::cout << "List::~List()" << std::endl;          std::cout << "List::~List()" << std::endl;
1022        #endif // DEBUG          #endif // DEBUG
1023          DeleteChunkList();          DeleteChunkList();
1024      }      }
1025    
# Line 1024  namespace RIFF { Line 1052  namespace RIFF {
1052       *                   that ID       *                   that ID
1053       */       */
1054      Chunk* List::GetSubChunk(uint32_t ChunkID) {      Chunk* List::GetSubChunk(uint32_t ChunkID) {
1055        #if DEBUG          #if DEBUG
1056        std::cout << "List::GetSubChunk(uint32_t)" << std::endl;          std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
1057        #endif // DEBUG          #endif // DEBUG
1058          if (!pSubChunksMap) LoadSubChunks();          if (!pSubChunksMap) LoadSubChunks();
1059          return (*pSubChunksMap)[ChunkID];          return (*pSubChunksMap)[ChunkID];
1060      }      }
# Line 1193  namespace RIFF { Line 1221  namespace RIFF {
1221      /** @brief Creates a new sub chunk.      /** @brief Creates a new sub chunk.
1222       *       *
1223       * 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
1224       * 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.
1225       * 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
1226       * actual file and <b>before</b> performing any data write operations       * actual file and <b>before</b> performing any data write operations
1227       * on the new chunk!       * on the new chunk!
1228       *       *
1229       * @param uiChunkID  - chunk ID of the new chunk       * @param uiChunkID  - chunk ID of the new chunk
1230       * @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
1231       *                     data size (without header)       *                      data size (without header)
1232       * @throws RIFF::Exception if \a uiBodySize equals zero       * @throws RIFF::Exception if \a ullBodySize equals zero
1233       */       */
1234      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize) {
1235          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");
1236          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1237          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1238          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1239          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1240          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(ullBodySize);
1241          NewChunkSize += CHUNK_HEADER_SIZE;          ullNewChunkSize += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1242          return pNewChunk;          return pNewChunk;
1243      }      }
1244    
# Line 1279  namespace RIFF { Line 1306  namespace RIFF {
1306          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1307          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1308          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1309          NewChunkSize += LIST_HEADER_SIZE;          ullNewChunkSize += LIST_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1310          return pNewListChunk;          return pNewListChunk;
1311      }      }
1312    
# Line 1312  namespace RIFF { Line 1338  namespace RIFF {
1338          delete pSubChunk;          delete pSubChunk;
1339      }      }
1340    
1341      void List::ReadHeader(unsigned long fPos) {      /**
1342        #if DEBUG       *  Returns the actual total size in bytes (including List chunk header and
1343        std::cout << "List::Readheader(ulong) ";       *  all subchunks) of this List Chunk if being stored to a file.
1344        #endif // DEBUG       *
1345          Chunk::ReadHeader(fPos);       *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
1346          if (CurrentChunkSize < 4) return;       *                          being saved to a file
1347          NewChunkSize = CurrentChunkSize -= 4;       */
1348        file_offset_t List::RequiredPhysicalSize(int fileOffsetSize) {
1349            if (!pSubChunks) LoadSubChunks();
1350            file_offset_t size = LIST_HEADER_SIZE(fileOffsetSize);
1351            ChunkList::iterator iter = pSubChunks->begin();
1352            ChunkList::iterator end  = pSubChunks->end();
1353            for (; iter != end; ++iter)
1354                size += (*iter)->RequiredPhysicalSize(fileOffsetSize);
1355            return size;
1356        }
1357    
1358        void List::ReadHeader(file_offset_t filePos) {
1359            #if DEBUG
1360            std::cout << "List::Readheader(file_offset_t) ";
1361            #endif // DEBUG
1362            Chunk::ReadHeader(filePos);
1363            if (ullCurrentChunkSize < 4) return;
1364            ullNewChunkSize = ullCurrentChunkSize -= 4;
1365          #if POSIX          #if POSIX
1366          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1367          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1368          #elif defined(WIN32)          #elif defined(WIN32)
1369          SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          SetFilePointerEx(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), NULL/*new pos pointer*/, FILE_BEGIN);
1370          DWORD dwBytesRead;          DWORD dwBytesRead;
1371          ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);          ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1372          #else          #else
1373          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1374          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
1375          #endif // POSIX          #endif // POSIX
1376        #if DEBUG          #if DEBUG
1377        std::cout << "listType=" << convertToString(ListType) << std::endl;          std::cout << "listType=" << convertToString(ListType) << std::endl;
1378        #endif // DEBUG          #endif // DEBUG
1379          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
1380              //swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1381          }          }
1382      }      }
1383    
1384      void List::WriteHeader(unsigned long fPos) {      void List::WriteHeader(file_offset_t filePos) {
1385          // 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
1386          NewChunkSize += 4;          ullNewChunkSize += 4;
1387          Chunk::WriteHeader(fPos);          Chunk::WriteHeader(filePos);
1388          NewChunkSize -= 4; // just revert the +4 incrementation          ullNewChunkSize -= 4; // just revert the +4 incrementation
1389          #if POSIX          #if POSIX
1390          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1391          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1392          #elif defined(WIN32)          #elif defined(WIN32)
1393          SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          SetFilePointerEx(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), NULL/*new pos pointer*/, FILE_BEGIN);
1394          DWORD dwBytesWritten;          DWORD dwBytesWritten;
1395          WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);          WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1396          #else          #else
1397          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1398          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
1399          #endif // POSIX          #endif // POSIX
1400      }      }
1401    
1402      void List::LoadSubChunks(progress_t* pProgress) {      void List::LoadSubChunks(progress_t* pProgress) {
1403         #if DEBUG          #if DEBUG
1404         std::cout << "List::LoadSubChunks()";          std::cout << "List::LoadSubChunks()";
1405         #endif // DEBUG          #endif // DEBUG
1406          if (!pSubChunks) {          if (!pSubChunks) {
1407              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1408              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
# Line 1368  namespace RIFF { Line 1411  namespace RIFF {
1411              #else              #else
1412              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1413              #endif              #endif
1414              unsigned long uiOriginalPos = GetPos();              file_offset_t ullOriginalPos = GetPos();
1415              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1416              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE(pFile->FileOffsetSize)) {
1417                  Chunk* ck;                  Chunk* ck;
1418                  uint32_t ckid;                  uint32_t ckid;
1419                  Read(&ckid, 4, 1);                  Read(&ckid, 4, 1);
1420         #if DEBUG                  #if DEBUG
1421         std::cout << " ckid=" << convertToString(ckid) << std::endl;                  std::cout << " ckid=" << convertToString(ckid) << std::endl;
1422         #endif // DEBUG                  #endif // DEBUG
1423                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1424                      ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::List(pFile, ullStartPos + ullPos - 4, this);
1425                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1426                  }                  }
1427                  else { // simple chunk                  else { // simple chunk
1428                      ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::Chunk(pFile, ullStartPos + ullPos - 4, this);
1429                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1430                  }                  }
1431                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1432                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1433                  if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte                  if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte
1434              }              }
1435              SetPos(uiOriginalPos); // restore position before this call              SetPos(ullOriginalPos); // restore position before this call
1436          }          }
1437          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
1438      }      }
# Line 1413  namespace RIFF { Line 1456  namespace RIFF {
1456       * subchunks (including sub list chunks) will be stored recursively as       * subchunks (including sub list chunks) will be stored recursively as
1457       * well.       * well.
1458       *       *
1459       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
1460       *                     list chunk should be written to       *                     list chunk should be written to
1461       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
1462       *                              the file       *                              the file
1463       * @param pProgress - optional: callback function for progress notification       * @param pProgress - optional: callback function for progress notification
1464       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
1465       *          \a ulWritePos incremented by this list chunk's new size       *          \a ullWritePos incremented by this list chunk's new size
1466       *          (including its header size of course)       *          (including its header size of course)
1467       */       */
1468      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset, progress_t* pProgress) {      file_offset_t List::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
1469          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
1470          ulWritePos += LIST_HEADER_SIZE;          ullWritePos += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1471    
1472          if (pFile->Mode != stream_mode_read_write)          if (pFile->Mode != stream_mode_read_write)
1473              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 1438  namespace RIFF { Line 1481  namespace RIFF {
1481                  progress_t subprogress;                  progress_t subprogress;
1482                  __divide_progress(pProgress, &subprogress, n, i);                  __divide_progress(pProgress, &subprogress, n, i);
1483                  // do the actual work                  // do the actual work
1484                  ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset, &subprogress);                  ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, &subprogress);
1485              }              }
1486          }          }
1487    
1488          // update this list chunk's header          // update this list chunk's header
1489          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          ullCurrentChunkSize = ullNewChunkSize = ullWritePos - ullOriginalPos - LIST_HEADER_SIZE(pFile->FileOffsetSize);
1490          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
1491    
1492          // offset of this list chunk in new written file may have changed          // offset of this list chunk in new written file may have changed
1493          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;          ullStartPos = ullOriginalPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1494    
1495           __notify_progress(pProgress, 1.0); // notify done           __notify_progress(pProgress, 1.0); // notify done
1496    
1497          return ulWritePos;          return ullWritePos;
1498      }      }
1499    
1500      void List::__resetPos() {      void List::__resetPos() {
# Line 1466  namespace RIFF { Line 1509  namespace RIFF {
1509      /**      /**
1510       *  Returns string representation of the lists's id       *  Returns string representation of the lists's id
1511       */       */
1512      String List::GetListTypeString() {      String List::GetListTypeString() const {
1513          return convertToString(ListType);          return convertToString(ListType);
1514      }      }
1515    
# Line 1490  namespace RIFF { Line 1533  namespace RIFF {
1533       * @see AddSubChunk(), AddSubList(), SetByteOrder()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1534       */       */
1535      File::File(uint32_t FileType)      File::File(uint32_t FileType)
1536          : List(this), bIsNewFile(true), Layout(layout_standard)          : List(this), bIsNewFile(true), Layout(layout_standard),
1537              FileOffsetPreference(offset_size_auto)
1538      {      {
1539          #if defined(WIN32)          #if defined(WIN32)
1540          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
# Line 1499  namespace RIFF { Line 1543  namespace RIFF {
1543          #endif          #endif
1544          Mode = stream_mode_closed;          Mode = stream_mode_closed;
1545          bEndianNative = true;          bEndianNative = true;
         ulStartPos = RIFF_HEADER_SIZE;  
1546          ListType = FileType;          ListType = FileType;
1547            FileOffsetSize = 4;
1548            ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1549      }      }
1550    
1551      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1512  namespace RIFF { Line 1557  namespace RIFF {
1557       *                         given RIFF file       *                         given RIFF file
1558       */       */
1559      File::File(const String& path)      File::File(const String& path)
1560          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard)          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard),
1561              FileOffsetPreference(offset_size_auto)
1562      {      {
1563         #if DEBUG          #if DEBUG
1564         std::cout << "File::File("<<path<<")" << std::endl;          std::cout << "File::File("<<path<<")" << std::endl;
1565         #endif // DEBUG          #endif // DEBUG
1566          bEndianNative = true;          bEndianNative = true;
1567            FileOffsetSize = 4;
1568          try {          try {
1569              __openExistingFile(path);              __openExistingFile(path);
1570              if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {              if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
# Line 1552  namespace RIFF { Line 1599  namespace RIFF {
1599       *                   first chunk found in the file)       *                   first chunk found in the file)
1600       * @param Endian - whether the file uses little endian or big endian layout       * @param Endian - whether the file uses little endian or big endian layout
1601       * @param layout - general file structure type       * @param layout - general file structure type
1602         * @param fileOffsetSize - (optional) preference how to deal with large files
1603       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occured while trying to load the
1604       *                         given RIFF-alike file       *                         given RIFF-alike file
1605       */       */
1606      File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout)      File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout, offset_size_t fileOffsetSize)
1607          : List(this), Filename(path), bIsNewFile(false), Layout(layout)          : List(this), Filename(path), bIsNewFile(false), Layout(layout),
1608              FileOffsetPreference(fileOffsetSize)
1609      {      {
1610          SetByteOrder(Endian);          SetByteOrder(Endian);
1611            if (fileOffsetSize < offset_size_auto || fileOffsetSize > offset_size_64bit)
1612                throw Exception("Invalid RIFF::offset_size_t");
1613            FileOffsetSize = 4;
1614          try {          try {
1615              __openExistingFile(path, &FileType);              __openExistingFile(path, &FileType);
1616          }          }
# Line 1579  namespace RIFF { Line 1631  namespace RIFF {
1631       *                         given RIFF file or RIFF-alike file       *                         given RIFF file or RIFF-alike file
1632       */       */
1633      void File::__openExistingFile(const String& path, uint32_t* FileType) {      void File::__openExistingFile(const String& path, uint32_t* FileType) {
         ResizedChunks.clear();  
1634          #if POSIX          #if POSIX
1635          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1636          if (hFileRead == -1) {          if (hFileRead == -1) {
# Line 1604  namespace RIFF { Line 1655  namespace RIFF {
1655          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1656          #endif // POSIX          #endif // POSIX
1657          Mode = stream_mode_read;          Mode = stream_mode_read;
1658    
1659            // determine RIFF file offset size to be used (in RIFF chunk headers)
1660            // according to the current file offset preference
1661            FileOffsetSize = FileOffsetSizeFor(GetCurrentFileSize());
1662    
1663          switch (Layout) {          switch (Layout) {
1664              case layout_standard: // this is a normal RIFF file              case layout_standard: // this is a normal RIFF file
1665                  ulStartPos = RIFF_HEADER_SIZE;                  ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1666                  ReadHeader(0);                  ReadHeader(0);
1667                  if (FileType && ChunkID != *FileType)                  if (FileType && ChunkID != *FileType)
1668                      throw RIFF::Exception("Invalid file container ID");                      throw RIFF::Exception("Invalid file container ID");
1669                  break;                  break;
1670              case layout_flat: // non-standard RIFF-alike file              case layout_flat: // non-standard RIFF-alike file
1671                  ulStartPos = 0;                  ullStartPos = 0;
1672                  NewChunkSize = CurrentChunkSize = GetFileSize();                  ullNewChunkSize = ullCurrentChunkSize = GetCurrentFileSize();
1673                  if (FileType) {                  if (FileType) {
1674                      uint32_t ckid;                      uint32_t ckid;
1675                      if (Read(&ckid, 4, 1) != 4) {                      if (Read(&ckid, 4, 1) != 4) {
# Line 1629  namespace RIFF { Line 1685  namespace RIFF {
1685          }          }
1686      }      }
1687    
1688      String File::GetFileName() {      String File::GetFileName() const {
1689          return Filename;          return Filename;
1690      }      }
1691            
# Line 1637  namespace RIFF { Line 1693  namespace RIFF {
1693          Filename = path;          Filename = path;
1694      }      }
1695    
1696      stream_mode_t File::GetMode() {      stream_mode_t File::GetMode() const {
1697          return Mode;          return Mode;
1698      }      }
1699    
# Line 1771  namespace RIFF { Line 1827  namespace RIFF {
1827      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1828       *       *
1829       * Make all changes of all chunks persistent by writing them to the       * Make all changes of all chunks persistent by writing them to the
1830       * 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.  
1831       *       *
1832       * @param pProgress - optional: callback function for progress notification       * @param pProgress - optional: callback function for progress notification
1833       * @throws RIFF::Exception if there is an empty chunk or empty list       * @throws RIFF::Exception if there is an empty chunk or empty list
# Line 1798  namespace RIFF { Line 1852  namespace RIFF {
1852          // reopen file in write mode          // reopen file in write mode
1853          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1854    
1855            // get the current file size as it is now still physically stored on disk
1856            const file_offset_t workingFileSize = GetCurrentFileSize();
1857    
1858            // get the overall file size required to save this file
1859            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1860    
1861            // determine whether this file will yield in a large file (>=4GB) and
1862            // the RIFF file offset size to be used accordingly for all chunks
1863            FileOffsetSize = FileOffsetSizeFor(newFileSize);
1864    
1865          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
1866          // RAM and without having to store the data in a temporary file, we          // RAM and without having to store the data in a temporary file, we
1867          // enlarge the file with the sum of all _positive_ chunk size          // enlarge the file with the overall positive file size change,
1868          // 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
1869          // calculated sum and finally update / rewrite the file by copying          // positive file size difference and finally update / rewrite the file
1870          // 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
1871            // 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();  
1872    
1873          // if there are positive size changes...          // if there are positive size changes...
1874          if (ulPositiveSizeDiff > 0) {          file_offset_t positiveSizeDiff = 0;
1875            if (newFileSize > workingFileSize) {
1876                positiveSizeDiff = newFileSize - workingFileSize;
1877    
1878              // divide progress into subprogress              // divide progress into subprogress
1879              progress_t subprogress;              progress_t subprogress;
1880              __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress              __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1881    
1882              // ... we enlarge this file first ...              // ... we enlarge this file first ...
1883              ulWorkingFileSize += ulPositiveSizeDiff;              ResizeFile(newFileSize);
1884              ResizeFile(ulWorkingFileSize);  
1885              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1886              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
             const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;  
1887              #if defined(WIN32)              #if defined(WIN32)
1888              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1889              #else              #else
1890              int iBytesMoved = 1;              int iBytesMoved = 1;
1891              #endif              #endif
1892              for (unsigned long ulPos = ulFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {              for (file_offset_t ullPos = workingFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1893                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;                  iBytesMoved = (ullPos < 4096) ? ullPos : 4096;
1894                  ulPos -= iBytesMoved;                  ullPos -= iBytesMoved;
1895                  #if POSIX                  #if POSIX
1896                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ullPos, SEEK_SET);
1897                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1898                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1899                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1900                  #elif defined(WIN32)                  #elif defined(WIN32)
1901                  SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);                  SetFilePointerEx(hFileRead, ullPos, NULL/*new pos pointer*/, FILE_BEGIN);
1902                  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1903                  SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);                  SetFilePointerEx(hFileWrite, ullPos + positiveSizeDiff, NULL/*new pos pointer*/, FILE_BEGIN);
1904                  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1905                  #else                  #else
1906                  fseek(hFileRead, ulPos, SEEK_SET);                  fseeko(hFileRead, ullPos, SEEK_SET);
1907                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1908                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  fseeko(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1909                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1910                  #endif                  #endif
1911                  if (!(iNotif % 8) && iBytesMoved > 0)                  if (!(iNotif % 8) && iBytesMoved > 0)
1912                      __notify_progress(&subprogress, float(ulFileSize - ulPos) / float(ulFileSize));                      __notify_progress(&subprogress, float(workingFileSize - ullPos) / float(workingFileSize));
1913              }              }
1914              delete[] pCopyBuffer;              delete[] pCopyBuffer;
1915              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");
# Line 1869  namespace RIFF { Line 1923  namespace RIFF {
1923          progress_t subprogress;          progress_t subprogress;
1924          __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress          __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
1925          // do the actual work          // do the actual work
1926          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff, &subprogress);          const file_offset_t finalSize = WriteChunk(0, positiveSizeDiff, &subprogress);
1927          unsigned long ulActualSize = __GetFileSize(hFileWrite);          const file_offset_t finalActualSize = __GetFileSize(hFileWrite);
1928          // notify subprogress done          // notify subprogress done
1929          __notify_progress(&subprogress, 1.f);          __notify_progress(&subprogress, 1.f);
1930    
1931          // resize file to the final size          // resize file to the final size
1932          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (finalSize < finalActualSize) ResizeFile(finalSize);
   
         // forget all resized chunks  
         ResizedChunks.clear();  
1933    
1934          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
1935      }      }
# Line 1943  namespace RIFF { Line 1994  namespace RIFF {
1994          #endif // POSIX          #endif // POSIX
1995          Mode = stream_mode_read_write;          Mode = stream_mode_read_write;
1996    
1997            // get the overall file size required to save this file
1998            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1999    
2000            // determine whether this file will yield in a large file (>=4GB) and
2001            // the RIFF file offset size to be used accordingly for all chunks
2002            FileOffsetSize = FileOffsetSizeFor(newFileSize);
2003    
2004          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
2005          unsigned long ulTotalSize;          file_offset_t ullTotalSize;
2006          {          {
2007              // divide progress into subprogress              // divide progress into subprogress
2008              progress_t subprogress;              progress_t subprogress;
2009              __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress              __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
2010              // do the actual work              // do the actual work
2011              ulTotalSize = WriteChunk(0, 0, &subprogress);              ullTotalSize = WriteChunk(0, 0, &subprogress);
2012              // notify subprogress done              // notify subprogress done
2013              __notify_progress(&subprogress, 1.f);              __notify_progress(&subprogress, 1.f);
2014          }          }
2015          unsigned long ulActualSize = __GetFileSize(hFileWrite);          file_offset_t ullActualSize = __GetFileSize(hFileWrite);
2016    
2017          // resize file to the final size (if the file was originally larger)          // resize file to the final size (if the file was originally larger)
2018          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ullActualSize > ullTotalSize) ResizeFile(ullTotalSize);
   
         // forget all resized chunks  
         ResizedChunks.clear();  
2019    
2020          #if POSIX          #if POSIX
2021          if (hFileWrite) close(hFileWrite);          if (hFileWrite) close(hFileWrite);
# Line 1980  namespace RIFF { Line 2035  namespace RIFF {
2035          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
2036      }      }
2037    
2038      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(file_offset_t ullNewSize) {
2039          #if POSIX          #if POSIX
2040          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ullNewSize) < 0)
2041              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
2042          #elif defined(WIN32)          #elif defined(WIN32)
2043          if (          if (
2044              SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||              !SetFilePointerEx(hFileWrite, ullNewSize, NULL/*new pos pointer*/, FILE_BEGIN) ||
2045              !SetEndOfFile(hFileWrite)              !SetEndOfFile(hFileWrite)
2046          ) throw Exception("Could not resize file \"" + Filename + "\"");          ) throw Exception("Could not resize file \"" + Filename + "\"");
2047          #else          #else
# Line 1996  namespace RIFF { Line 2051  namespace RIFF {
2051      }      }
2052    
2053      File::~File() {      File::~File() {
2054         #if DEBUG          #if DEBUG
2055         std::cout << "File::~File()" << std::endl;          std::cout << "File::~File()" << std::endl;
2056         #endif // DEBUG          #endif // DEBUG
2057          Cleanup();          Cleanup();
2058      }      }
2059        
2060      /**      /**
2061       * Returns @c true if this file has been created new from scratch and       * Returns @c true if this file has been created new from scratch and
2062       * has not been stored to disk yet.       * has not been stored to disk yet.
# Line 2020  namespace RIFF { Line 2075  namespace RIFF {
2075          #endif // POSIX          #endif // POSIX
2076          DeleteChunkList();          DeleteChunkList();
2077          pFile = NULL;          pFile = NULL;
         ResizedChunks.clear();  
2078      }      }
2079    
2080      void File::LogAsResized(Chunk* pResizedChunk) {      /**
2081          ResizedChunks.insert(pResizedChunk);       * Returns the current size of this file (in bytes) as it is currently
2082         * yet stored on disk. If this file does not yet exist on disk (i.e. when
2083         * this RIFF File has just been created from scratch and Save() has not
2084         * been called yet) then this method returns 0.
2085         */
2086        file_offset_t File::GetCurrentFileSize() const {
2087            file_offset_t size = 0;
2088            try {
2089                size = __GetFileSize(hFileRead);
2090            } catch (...) {
2091                size = 0;
2092            }
2093            return size;
2094        }
2095    
2096        /**
2097         * Returns the required size (in bytes) for this RIFF File to be saved to
2098         * disk. The precise size of the final file on disk depends on the RIFF
2099         * file offset size actually used internally in all headers of the RIFF
2100         * chunks. By default libgig handles the required file offset size
2101         * automatically for you; that means it is using 32 bit offsets for files
2102         * smaller than 4 GB and 64 bit offsets for files equal or larger than
2103         * 4 GB. You may however also override this default behavior by passing the
2104         * respective option to the RIFF File constructor to force one particular
2105         * offset size. In the latter case this method will return the file size
2106         * for the requested forced file offset size that will be used when calling
2107         * Save() later on.
2108         *
2109         * You may also use the overridden method below to get the file size for
2110         * an arbitrary other file offset size instead.
2111         *
2112         * @see offset_size_t
2113         * @see GetFileOffsetSize()
2114         */
2115        file_offset_t File::GetRequiredFileSize() {
2116            return GetRequiredFileSize(FileOffsetPreference);
2117        }
2118    
2119        /**
2120         * Returns the rquired size (in bytes) for this RIFF file to be saved to
2121         * disk, assuming the passed @a fileOffsestSize would be used for the
2122         * Save() operation.
2123         *
2124         * This overridden method essentialy behaves like the above method, with
2125         * the difference that you must provide a specific RIFF @a fileOffsetSize
2126         * for calculating the theoretical final file size.
2127         *
2128         * @see GetFileOffsetSize()
2129         */
2130        file_offset_t File::GetRequiredFileSize(offset_size_t fileOffsetSize) {
2131            switch (fileOffsetSize) {
2132                case offset_size_auto: {
2133                    file_offset_t fileSize = GetRequiredFileSize(offset_size_32bit);
2134                    if (fileSize >> 32)
2135                        return GetRequiredFileSize(offset_size_64bit);
2136                    else
2137                        return fileSize;
2138                }
2139                case offset_size_32bit: break;
2140                case offset_size_64bit: break;
2141                default: throw Exception("Internal error: Invalid RIFF::offset_size_t");
2142            }
2143            return RequiredPhysicalSize(FileOffsetSize);
2144        }
2145    
2146        int File::FileOffsetSizeFor(file_offset_t fileSize) const {
2147            switch (FileOffsetPreference) {
2148                case offset_size_auto:
2149                    return (fileSize >> 32) ? 8 : 4;
2150                case offset_size_32bit:
2151                    return 4;
2152                case offset_size_64bit:
2153                    return 8;
2154                default:
2155                    throw Exception("Internal error: Invalid RIFF::offset_size_t");
2156            }
2157      }      }
2158    
2159      void File::UnlogResized(Chunk* pResizedChunk) {      /**
2160          ResizedChunks.erase(pResizedChunk);       * Returns the current size (in bytes) of file offsets stored in the
2161         * headers of all chunks of this file.
2162         *
2163         * Most RIFF files are using 32 bit file offsets internally, which limits
2164         * them to a maximum file size of less than 4 GB though. In contrast to the
2165         * common standard, this RIFF File class implementation supports handling of
2166         * RIFF files equal or larger than 4 GB. In such cases 64 bit file offsets
2167         * have to be used in all headers of all RIFF Chunks when being stored to a
2168         * physical file. libgig by default automatically selects the correct file
2169         * offset size for you. You may however also force one particular file
2170         * offset size by supplying the respective option to the RIFF::File
2171         * constructor.
2172         *
2173         * This method can be used to check which RIFF file offset size is currently
2174         * being used for this RIFF File.
2175         *
2176         * @returns current RIFF file offset size used (in bytes)
2177         * @see offset_size_t
2178         */
2179        int File::GetFileOffsetSize() const {
2180            return FileOffsetSize;
2181      }      }
2182    
2183      unsigned long File::GetFileSize() {      /**
2184          return __GetFileSize(hFileRead);       * Returns the required size (in bytes) of file offsets stored in the
2185         * headers of all chunks of this file if the current RIFF tree would be
2186         * saved to disk by calling Save().
2187         *
2188         * See GetFileOffsetSize() for mor details about RIFF file offsets.
2189         *
2190         * @returns RIFF file offset size required (in bytes) if being saved
2191         * @see offset_size_t
2192         */
2193        int File::GetRequiredFileOffsetSize() {
2194            return FileOffsetSizeFor(GetCurrentFileSize());
2195      }      }
2196    
2197      #if POSIX      #if POSIX
2198      unsigned long File::__GetFileSize(int hFile) {      file_offset_t File::__GetFileSize(int hFile) const {
2199          struct stat filestat;          struct stat filestat;
2200          fstat(hFile, &filestat);          if (fstat(hFile, &filestat) == -1)
2201          long size = filestat.st_size;              throw Exception("POSIX FS error: could not determine file size");
2202          return size;          return filestat.st_size;
2203      }      }
2204      #elif defined(WIN32)      #elif defined(WIN32)
2205      unsigned long File::__GetFileSize(HANDLE hFile) {      file_offset_t File::__GetFileSize(HANDLE hFile) const {
2206          DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);          PLARGE_INTEGER size;
2207          if (dwSize == INVALID_FILE_SIZE)          if (!GetFileSizeEx(hFile, &size))
2208              throw Exception("Windows FS error: could not determine file size");              throw Exception("Windows FS error: could not determine file size");
2209          return dwSize;          return size;
2210      }      }
2211      #else // standard C functions      #else // standard C functions
2212      unsigned long File::__GetFileSize(FILE* hFile) {      file_offset_t File::__GetFileSize(FILE* hFile) const {
2213          long curpos = ftell(hFile);          off_t curpos = ftello(hFile);
2214          fseek(hFile, 0, SEEK_END);          if (fseeko(hFile, 0, SEEK_END) == -1)
2215          long size = ftell(hFile);              throw Exception("FS error: could not determine file size");
2216          fseek(hFile, curpos, SEEK_SET);          off_t size = ftello(hFile);
2217            fseeko(hFile, curpos, SEEK_SET);
2218          return size;          return size;
2219      }      }
2220      #endif      #endif

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

  ViewVC Help
Powered by ViewVC