/[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 1678 by persson, Sun Feb 10 16:07:22 2008 UTC revision 3921 by schoenebeck, Mon Jun 14 09:28:04 2021 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-2007 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2021 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 21  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
24    #include <algorithm>
25    #include <set>
26  #include <string.h>  #include <string.h>
27    
28  #include "RIFF.h"  #include "RIFF.h"
29    
30  #include "helper.h"  #include "helper.h"
31    
32    #if POSIX
33    # include <errno.h>
34    #endif
35    
36  namespace RIFF {  namespace RIFF {
37    
38  // *************** Internal functions **************  // *************** Internal functions **************
# Line 46  namespace RIFF { Line 52  namespace RIFF {
52          return sPath;          return sPath;
53      }      }
54    
55        inline static bool _isValidHandle(File::Handle handle) {
56            #if defined(WIN32)
57            return handle != INVALID_HANDLE_VALUE;
58            #else
59            return handle;
60            #endif
61        }
62    
63        inline static void _close(File::Handle handle) {
64            if (!_isValidHandle(handle)) return;
65            #if POSIX
66            close(handle);
67            #elif defined(WIN32)
68            CloseHandle(handle);
69            #else
70            fclose(handle);
71            #endif
72        }
73    
74    
75    
76    // *************** progress_t ***************
77    // *
78    
79        progress_t::progress_t() {
80            callback    = NULL;
81            custom      = NULL;
82            __range_min = 0.0f;
83            __range_max = 1.0f;
84        }
85    
86        /**
87         * Divides this progress task into the requested amount of equal weighted
88         * sub-progress tasks and returns a vector with those subprogress tasks.
89         *
90         * @param iSubtasks - total amount sub tasks this task should be subdivided
91         * @returns subtasks
92         */
93        std::vector<progress_t> progress_t::subdivide(int iSubtasks) {
94            std::vector<progress_t> v;
95            for (int i = 0; i < iSubtasks; ++i) {
96                progress_t p;
97                __divide_progress(this, &p, iSubtasks, i);
98                v.push_back(p);
99            }
100            return v;
101        }
102    
103        /**
104         * Divides this progress task into the requested amount of sub-progress
105         * tasks, where each one of those new sub-progress tasks is created with its
106         * requested individual weight / portion, and finally returns a vector
107         * with those new subprogress tasks.
108         *
109         * The amount of subprogresses to be created is determined by this method
110         * by calling @c vSubTaskPortions.size() .
111         *
112         * Example: consider you wanted to create 3 subprogresses where the 1st
113         * subtask should be assigned 10% of the new 3 subprogresses' overall
114         * progress, the 2nd subtask should be assigned 50% of the new 3
115         * subprogresses' overall progress, and the 3rd subtask should be assigned
116         * 40%, then you might call this method like this:
117         * @code
118         * std::vector<progress_t> subprogresses = progress.subdivide({0.1, 0.5, 0.4});
119         * @endcode
120         *
121         * @param vSubTaskPortions - amount and individual weight of subtasks to be
122         *                           created
123         * @returns subtasks
124         */
125        std::vector<progress_t> progress_t::subdivide(std::vector<float> vSubTaskPortions) {
126            float fTotal = 0.f; // usually 1.0, but we sum the portions up below to be sure
127            for (int i = 0; i < vSubTaskPortions.size(); ++i)
128                fTotal += vSubTaskPortions[i];
129    
130            float fLow = 0.f, fHigh = 0.f;
131            std::vector<progress_t> v;
132            for (int i = 0; i < vSubTaskPortions.size(); ++i) {
133                fLow  = fHigh;
134                fHigh = vSubTaskPortions[i];
135                progress_t p;
136                __divide_progress(this, &p, fTotal, fLow, fHigh);
137                v.push_back(p);
138            }
139            return v;
140        }
141    
142    
143    
144  // *************** Chunk **************  // *************** Chunk **************
145  // *  // *
146    
147      Chunk::Chunk(File* pFile) {      Chunk::Chunk(File* pFile) {
148          #if DEBUG          #if DEBUG_RIFF
149          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
150          #endif // DEBUG          #endif // DEBUG_RIFF
151          ulPos      = 0;          chunkPos.ullPos = 0;
152          pParent    = NULL;          pParent    = NULL;
153          pChunkData = NULL;          pChunkData = NULL;
154          ulChunkDataSize = 0;          ullCurrentChunkSize = 0;
155            ullNewChunkSize = 0;
156            ullChunkDataSize = 0;
157          ChunkID    = CHUNK_ID_RIFF;          ChunkID    = CHUNK_ID_RIFF;
158          this->pFile = pFile;          this->pFile = pFile;
159      }      }
160    
161      Chunk::Chunk(File* pFile, unsigned long StartPos, List* Parent) {      Chunk::Chunk(File* pFile, file_offset_t StartPos, List* Parent) {
162          #if DEBUG          #if DEBUG_RIFF
163          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;
164          #endif // DEBUG          #endif // DEBUG_RIFF
165          this->pFile   = pFile;          this->pFile   = pFile;
166          ulStartPos    = StartPos + CHUNK_HEADER_SIZE;          ullStartPos   = StartPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
167          pParent       = Parent;          pParent       = Parent;
168          ulPos         = 0;          chunkPos.ullPos = 0;
169          pChunkData    = NULL;          pChunkData    = NULL;
170          ulChunkDataSize = 0;          ullCurrentChunkSize = 0;
171            ullNewChunkSize = 0;
172            ullChunkDataSize = 0;
173          ReadHeader(StartPos);          ReadHeader(StartPos);
174      }      }
175    
176      Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, uint uiBodySize) {      Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, file_offset_t ullBodySize) {
177          this->pFile      = pFile;          this->pFile      = pFile;
178          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
179          this->pParent    = pParent;          this->pParent    = pParent;
180          ulPos            = 0;          chunkPos.ullPos  = 0;
181          pChunkData       = NULL;          pChunkData       = NULL;
         ulChunkDataSize  = 0;  
182          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
183          CurrentChunkSize = 0;          ullChunkDataSize = 0;
184          NewChunkSize     = uiBodySize;          ullCurrentChunkSize = 0;
185            ullNewChunkSize  = ullBodySize;
186      }      }
187    
188      Chunk::~Chunk() {      Chunk::~Chunk() {
         pFile->UnlogResized(this);  
189          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
190      }      }
191    
192      void Chunk::ReadHeader(unsigned long fPos) {      void Chunk::ReadHeader(file_offset_t filePos) {
193          #if DEBUG          #if DEBUG_RIFF
194          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << filePos << ") ";
195          #endif // DEBUG          #endif // DEBUG_RIFF
196            ChunkID = 0;
197            ullNewChunkSize = ullCurrentChunkSize = 0;
198    
199            const File::Handle hRead = pFile->FileHandle();
200    
201          #if POSIX          #if POSIX
202          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(hRead, filePos, SEEK_SET) != -1) {
203              read(pFile->hFileRead, &ChunkID, 4);              read(hRead, &ChunkID, 4);
204              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(hRead, &ullCurrentChunkSize, pFile->FileOffsetSize);
205          #elif defined(WIN32)          #elif defined(WIN32)
206          if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {          LARGE_INTEGER liFilePos;
207            liFilePos.QuadPart = filePos;
208            if (SetFilePointerEx(hRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
209              DWORD dwBytesRead;              DWORD dwBytesRead;
210              ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);              ReadFile(hRead, &ChunkID, 4, &dwBytesRead, NULL);
211              ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);              ReadFile(hRead, &ullCurrentChunkSize, pFile->FileOffsetSize, &dwBytesRead, NULL);
212          #else          #else
213          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseeko(hRead, filePos, SEEK_SET)) {
214              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, hRead);
215              fread(&CurrentChunkSize, 4, 1, pFile->hFileRead);              fread(&ullCurrentChunkSize, pFile->FileOffsetSize, 1, hRead);
216          #endif // POSIX          #endif // POSIX
217              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
218              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
# Line 123  namespace RIFF { Line 226  namespace RIFF {
226              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
227              if (!pFile->bEndianNative) {              if (!pFile->bEndianNative) {
228                  //swapBytes_32(&ChunkID);                  //swapBytes_32(&ChunkID);
229                  swapBytes_32(&CurrentChunkSize);                  if (pFile->FileOffsetSize == 4)
230                        swapBytes_32(&ullCurrentChunkSize);
231                    else
232                        swapBytes_64(&ullCurrentChunkSize);
233              }              }
234              #if DEBUG              #if DEBUG_RIFF
235              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
236              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << ullCurrentChunkSize << " ";
237              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
238              #endif // DEBUG              #endif // DEBUG_RIFF
239              NewChunkSize = CurrentChunkSize;              ullNewChunkSize = ullCurrentChunkSize;
240          }          }
241      }      }
242    
243      void Chunk::WriteHeader(unsigned long fPos) {      void Chunk::WriteHeader(file_offset_t filePos) {
244          uint32_t uiNewChunkID = ChunkID;          uint32_t uiNewChunkID = ChunkID;
245          if (ChunkID == CHUNK_ID_RIFF) {          if (ChunkID == CHUNK_ID_RIFF) {
246              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
# Line 144  namespace RIFF { Line 250  namespace RIFF {
250              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
251          }          }
252    
253          uint32_t uiNewChunkSize = NewChunkSize;          uint64_t ullNewChunkSize = this->ullNewChunkSize;
254          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
255              swapBytes_32(&uiNewChunkSize);              if (pFile->FileOffsetSize == 4)
256                    swapBytes_32(&ullNewChunkSize);
257                else
258                    swapBytes_64(&ullNewChunkSize);
259          }          }
260    
261            const File::Handle hWrite = pFile->FileWriteHandle();
262    
263          #if POSIX          #if POSIX
264          if (lseek(pFile->hFileWrite, fPos, SEEK_SET) != -1) {          if (lseek(hWrite, filePos, SEEK_SET) != -1) {
265              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(hWrite, &uiNewChunkID, 4);
266              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(hWrite, &ullNewChunkSize, pFile->FileOffsetSize);
267          }          }
268          #elif defined(WIN32)          #elif defined(WIN32)
269          if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {          LARGE_INTEGER liFilePos;
270            liFilePos.QuadPart = filePos;
271            if (SetFilePointerEx(hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
272              DWORD dwBytesWritten;              DWORD dwBytesWritten;
273              WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);              WriteFile(hWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
274              WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);              WriteFile(hWrite, &ullNewChunkSize, pFile->FileOffsetSize, &dwBytesWritten, NULL);
275          }          }
276          #else          #else
277          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseeko(hWrite, filePos, SEEK_SET)) {
278              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, hWrite);
279              fwrite(&uiNewChunkSize, 4, 1, pFile->hFileWrite);              fwrite(&ullNewChunkSize, pFile->FileOffsetSize, 1, hWrite);
280          }          }
281          #endif // POSIX          #endif // POSIX
282      }      }
# Line 172  namespace RIFF { Line 285  namespace RIFF {
285       *  Returns the String representation of the chunk's ID (e.g. "RIFF",       *  Returns the String representation of the chunk's ID (e.g. "RIFF",
286       *  "LIST").       *  "LIST").
287       */       */
288      String Chunk::GetChunkIDString() {      String Chunk::GetChunkIDString() const {
289          return convertToString(ChunkID);          return convertToString(ChunkID);
290      }      }
291    
292      /**      /**
293         * This is an internal-only method which must not be used by any application
294         * and might change at any time.
295         *
296         * Returns a reference (memory location) of the chunk's current file
297         * (read/write) position variable which depends on the current value of
298         * File::IsIOPerThread().
299         */
300        file_offset_t& Chunk::GetPosUnsafeRef() {
301            if (!pFile->IsIOPerThread()) return chunkPos.ullPos;
302            const std::thread::id tid = std::this_thread::get_id();
303            return chunkPos.byThread[tid];
304        }
305    
306        /**
307         * Current read/write position within the chunk data body (starting with 0).
308         *
309         * @see File::IsIOPerThread() for multi-threaded streaming
310         */
311        file_offset_t Chunk::GetPos() const {
312            if (!pFile->IsIOPerThread()) return chunkPos.ullPos;
313            const std::thread::id tid = std::this_thread::get_id();
314            std::lock_guard<std::mutex> lock(chunkPos.mutex);
315            return chunkPos.byThread[tid];
316        }
317    
318        /**
319         * Current, actual offset in file of current chunk data body read/write
320         * position.
321         *
322         * @see File::IsIOPerThread() for multi-threaded streaming
323         */
324        file_offset_t Chunk::GetFilePos() const {
325            return ullStartPos + GetPos();
326        }
327    
328        /**
329       *  Sets the position within the chunk body, thus within the data portion       *  Sets the position within the chunk body, thus within the data portion
330       *  of the chunk (in bytes).       *  of the chunk (in bytes).
331       *       *
# Line 187  namespace RIFF { Line 336  namespace RIFF {
336       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,
337       *                  if omitted \a Where relates to beginning of the chunk       *                  if omitted \a Where relates to beginning of the chunk
338       *                  data       *                  data
339         *  @see File::IsIOPerThread() for multi-threaded streaming
340       */       */
341      unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {      file_offset_t Chunk::SetPos(file_offset_t Where, stream_whence_t Whence) {
342       #if DEBUG          #if DEBUG_RIFF
343       std::cout << "Chunk::SetPos(ulong)" << std::endl;          std::cout << "Chunk::SetPos(file_offset_t,stream_whence_t)" << std::endl;
344       #endif // DEBUG          #endif // DEBUG_RIFF
345            std::lock_guard<std::mutex> lock(chunkPos.mutex);
346            file_offset_t& pos = GetPosUnsafeRef();
347          switch (Whence) {          switch (Whence) {
348              case stream_curpos:              case stream_curpos:
349                  ulPos += Where;                  pos += Where;
350                  break;                  break;
351              case stream_end:              case stream_end:
352                  ulPos = CurrentChunkSize - 1 - Where;                  pos = ullCurrentChunkSize - 1 - Where;
353                  break;                  break;
354              case stream_backward:              case stream_backward:
355                  ulPos -= Where;                  pos -= Where;
356                  break;                  break;
357              case stream_start: default:              case stream_start: default:
358                  ulPos = Where;                  pos = Where;
359                  break;                  break;
360          }          }
361          if (ulPos > CurrentChunkSize) ulPos = CurrentChunkSize;          if (pos > ullCurrentChunkSize) pos = ullCurrentChunkSize;
362          return ulPos;          return pos;
363      }      }
364    
365      /**      /**
# Line 219  namespace RIFF { Line 371  namespace RIFF {
371       *  of the chunk data.       *  of the chunk data.
372       *       *
373       *  @returns  number of bytes left to read       *  @returns  number of bytes left to read
374         *  @see File::IsIOPerThread() for multi-threaded streaming
375       */       */
376      unsigned long Chunk::RemainingBytes() {      file_offset_t Chunk::RemainingBytes() const {
377         #if DEBUG          #if DEBUG_RIFF
378         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;          std::cout << "Chunk::Remainingbytes()=" << ullCurrentChunkSize - ullPos << std::endl;
379         #endif // DEBUG          #endif // DEBUG_RIFF
380          return CurrentChunkSize - ulPos;          const file_offset_t pos = GetPos();
381            return (ullCurrentChunkSize > pos) ? ullCurrentChunkSize - pos : 0;
382        }
383    
384        /**
385         *  Returns the actual total size in bytes (including header) of this Chunk
386         *  if being stored to a file.
387         *
388         *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
389         *                          being saved to a file
390         */
391        file_offset_t Chunk::RequiredPhysicalSize(int fileOffsetSize) {
392            return CHUNK_HEADER_SIZE(fileOffsetSize) + // RIFF chunk header
393                   ullNewChunkSize + // chunks's actual data body
394                   ullNewChunkSize % 2; // optional pad byte
395      }      }
396    
397      /**      /**
# Line 237  namespace RIFF { Line 404  namespace RIFF {
404       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
405       *    already reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
406       *    possible without SetPos()       *    possible without SetPos()
407         *
408         *  @see File::IsIOPerThread() for multi-threaded streaming
409       */       */
410      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() const {
411        #if DEBUG          #if DEBUG_RIFF
412        std::cout << "Chunk::GetState()" << std::endl;          std::cout << "Chunk::GetState()" << std::endl;
413        #endif // DEBUG          #endif // DEBUG_RIFF
414          #if POSIX  
415          if (pFile->hFileRead == 0) return stream_closed;          const File::Handle hRead = pFile->FileHandle();
416          #elif defined (WIN32)  
417          if (pFile->hFileRead == INVALID_HANDLE_VALUE)          if (!_isValidHandle(hRead))
418              return stream_closed;              return stream_closed;
419          #else  
420          if (pFile->hFileRead == NULL) return stream_closed;          const file_offset_t pos = GetPos();
421          #endif // POSIX          if (pos < ullCurrentChunkSize)    return stream_ready;
422          if (ulPos < CurrentChunkSize) return stream_ready;          else                              return stream_end_reached;
         else                          return stream_end_reached;  
423      }      }
424    
425      /**      /**
# Line 267  namespace RIFF { Line 435  namespace RIFF {
435       *  @param WordCount  number of data words to read       *  @param WordCount  number of data words to read
436       *  @param WordSize   size of each data word to read       *  @param WordSize   size of each data word to read
437       *  @returns          number of successfully read data words or 0 if end       *  @returns          number of successfully read data words or 0 if end
438       *                    of file reached or error occured       *                    of file reached or error occurred
439         *  @see File::IsIOPerThread() for multi-threaded streaming
440       */       */
441      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) {
442         #if DEBUG          #if DEBUG_RIFF
443         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;          std::cout << "Chunk::Read(void*,file_offset_t,file_offset_t)" << std::endl;
444         #endif // DEBUG          #endif // DEBUG_RIFF
445          if (ulPos >= CurrentChunkSize) return 0;          //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
446          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          const file_offset_t pos = GetPos();
447            if (pos >= ullCurrentChunkSize) return 0;
448            if (pos + WordCount * WordSize >= ullCurrentChunkSize)
449                WordCount = (ullCurrentChunkSize - pos) / WordSize;
450    
451            const File::Handle hRead = pFile->FileHandle();
452    
453          #if POSIX          #if POSIX
454          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(hRead, ullStartPos + pos, SEEK_SET) < 0) return 0;
455          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          ssize_t readWords = read(hRead, pData, WordCount * WordSize);
456          if (readWords < 1) return 0;          if (readWords < 1) {
457                #if DEBUG_RIFF
458                std::cerr << "POSIX read() failed: " << strerror(errno) << std::endl << std::flush;
459                #endif // DEBUG_RIFF
460                return 0;
461            }
462          readWords /= WordSize;          readWords /= WordSize;
463          #elif defined(WIN32)          #elif defined(WIN32)
464          if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;          LARGE_INTEGER liFilePos;
465            liFilePos.QuadPart = ullStartPos + pos;
466            if (!SetFilePointerEx(hRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN))
467                return 0;
468          DWORD readWords;          DWORD readWords;
469          ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);          ReadFile(hRead, 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)
470          if (readWords < 1) return 0;          if (readWords < 1) return 0;
471          readWords /= WordSize;          readWords /= WordSize;
472          #else // standard C functions          #else // standard C functions
473          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseeko(hRead, ullStartPos + pos, SEEK_SET)) return 0;
474          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          file_offset_t readWords = fread(pData, WordSize, WordCount, hRead);
475          #endif // POSIX          #endif // POSIX
476          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
477              switch (WordSize) {              switch (WordSize) {
478                  case 2:                  case 2:
479                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
480                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
481                      break;                      break;
482                  case 4:                  case 4:
483                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
484                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
485                      break;                      break;
486                    case 8:
487                        for (file_offset_t iWord = 0; iWord < readWords; iWord++)
488                            swapBytes_64((uint64_t*) pData + iWord);
489                        break;
490                  default:                  default:
491                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (file_offset_t iWord = 0; iWord < readWords; iWord++)
492                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
493                      break;                      break;
494              }              }
# Line 323  namespace RIFF { Line 510  namespace RIFF {
510       *  @param WordSize   size of each data word to write       *  @param WordSize   size of each data word to write
511       *  @returns          number of successfully written data words       *  @returns          number of successfully written data words
512       *  @throws RIFF::Exception  if write operation would exceed current       *  @throws RIFF::Exception  if write operation would exceed current
513       *                           chunk size or any IO error occured       *                           chunk size or any IO error occurred
514       *  @see Resize()       *  @see Resize()
515         *  @see File::IsIOPerThread() for multi-threaded streaming
516       */       */
517      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) {
518          if (pFile->Mode != stream_mode_read_write)          const File::HandlePair io = pFile->FileHandlePair();
519            if (io.Mode != stream_mode_read_write)
520              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");
521          if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)          const file_offset_t pos = GetPos();
522            if (pos >= ullCurrentChunkSize || pos + WordCount * WordSize > ullCurrentChunkSize)
523              throw Exception("End of chunk reached while trying to write data");              throw Exception("End of chunk reached while trying to write data");
524          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
525              switch (WordSize) {              switch (WordSize) {
526                  case 2:                  case 2:
527                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
528                          swapBytes_16((uint16_t*) pData + iWord);                          swapBytes_16((uint16_t*) pData + iWord);
529                      break;                      break;
530                  case 4:                  case 4:
531                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
532                          swapBytes_32((uint32_t*) pData + iWord);                          swapBytes_32((uint32_t*) pData + iWord);
533                      break;                      break;
534                    case 8:
535                        for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
536                            swapBytes_64((uint64_t*) pData + iWord);
537                        break;
538                  default:                  default:
539                      for (unsigned long iWord = 0; iWord < WordCount; iWord++)                      for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
540                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);                          swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
541                      break;                      break;
542              }              }
543          }          }
544          #if POSIX          #if POSIX
545          if (lseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET) < 0) {          if (lseek(io.hWrite, ullStartPos + pos, SEEK_SET) < 0) {
546              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(pos) +
547                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + pos) + " in file)");
548          }          }
549          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          ssize_t writtenWords = write(io.hWrite, pData, WordCount * WordSize);
550          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");
551          writtenWords /= WordSize;          writtenWords /= WordSize;
552          #elif defined(WIN32)          #elif defined(WIN32)
553          if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {          LARGE_INTEGER liFilePos;
554              throw Exception("Could not seek to position " + ToString(ulPos) +          liFilePos.QuadPart = ullStartPos + pos;
555                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");          if (!SetFilePointerEx(io.hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
556                throw Exception("Could not seek to position " + ToString(pos) +
557                                " in chunk (" + ToString(ullStartPos + pos) + " in file)");
558          }          }
559          DWORD writtenWords;          DWORD writtenWords;
560          WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);          WriteFile(io.hWrite, 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)
561          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");
562          writtenWords /= WordSize;          writtenWords /= WordSize;
563          #else // standard C functions          #else // standard C functions
564          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseeko(io.hWrite, ullStartPos + pos, SEEK_SET)) {
565              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(pos) +
566                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                              " in chunk (" + ToString(ullStartPos + pos) + " in file)");
567          }          }
568          unsigned long writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);          file_offset_t writtenWords = fwrite(pData, WordSize, WordCount, io.hWrite);
569          #endif // POSIX          #endif // POSIX
570          SetPos(writtenWords * WordSize, stream_curpos);          SetPos(writtenWords * WordSize, stream_curpos);
571          return writtenWords;          return writtenWords;
572      }      }
573    
574      /** 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. */
575      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) {
576          unsigned long readWords = Read(pData, WordCount, WordSize);          file_offset_t readWords = Read(pData, WordCount, WordSize);
577          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");          if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");
578          return readWords;          return readWords;
579      }      }
# Line 390  namespace RIFF { Line 586  namespace RIFF {
586       * @param pData             destination buffer       * @param pData             destination buffer
587       * @param WordCount         number of 8 Bit signed integers to read       * @param WordCount         number of 8 Bit signed integers to read
588       * @returns                 number of read integers       * @returns                 number of read integers
589       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
590       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
591         * @see File::IsIOPerThread() for multi-threaded streaming
592       */       */
593      unsigned long Chunk::ReadInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt8(int8_t* pData, file_offset_t WordCount) {
594         #if DEBUG          #if DEBUG_RIFF
595         std::cout << "Chunk::ReadInt8(int8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt8(int8_t*,file_offset_t)" << std::endl;
596         #endif // DEBUG          #endif // DEBUG_RIFF
597          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
598      }      }
599    
# Line 411  namespace RIFF { Line 608  namespace RIFF {
608       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
609       * @param WordCount         number of 8 Bit signed integers to write       * @param WordCount         number of 8 Bit signed integers to write
610       * @returns                 number of written integers       * @returns                 number of written integers
611       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
612       * @see Resize()       * @see Resize()
613         * @see File::IsIOPerThread() for multi-threaded streaming
614       */       */
615      unsigned long Chunk::WriteInt8(int8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt8(int8_t* pData, file_offset_t WordCount) {
616          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
617      }      }
618    
# Line 427  namespace RIFF { Line 625  namespace RIFF {
625       * @param pData             destination buffer       * @param pData             destination buffer
626       * @param WordCount         number of 8 Bit unsigned integers to read       * @param WordCount         number of 8 Bit unsigned integers to read
627       * @returns                 number of read integers       * @returns                 number of read integers
628       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
629       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
630         * @see File::IsIOPerThread() for multi-threaded streaming
631       */       */
632      unsigned long Chunk::ReadUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint8(uint8_t* pData, file_offset_t WordCount) {
633         #if DEBUG          #if DEBUG_RIFF
634         std::cout << "Chunk::ReadUint8(uint8_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint8(uint8_t*,file_offset_t)" << std::endl;
635         #endif // DEBUG          #endif // DEBUG_RIFF
636          return ReadSceptical(pData, WordCount, 1);          return ReadSceptical(pData, WordCount, 1);
637      }      }
638    
# Line 448  namespace RIFF { Line 647  namespace RIFF {
647       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
648       * @param WordCount         number of 8 Bit unsigned integers to write       * @param WordCount         number of 8 Bit unsigned integers to write
649       * @returns                 number of written integers       * @returns                 number of written integers
650       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
651       * @see Resize()       * @see Resize()
652         * @see File::IsIOPerThread() for multi-threaded streaming
653       */       */
654      unsigned long Chunk::WriteUint8(uint8_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint8(uint8_t* pData, file_offset_t WordCount) {
655          return Write(pData, WordCount, 1);          return Write(pData, WordCount, 1);
656      }      }
657    
# Line 464  namespace RIFF { Line 664  namespace RIFF {
664       * @param pData             destination buffer       * @param pData             destination buffer
665       * @param WordCount         number of 16 Bit signed integers to read       * @param WordCount         number of 16 Bit signed integers to read
666       * @returns                 number of read integers       * @returns                 number of read integers
667       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
668       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
669         * @see File::IsIOPerThread() for multi-threaded streaming
670       */       */
671      unsigned long Chunk::ReadInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt16(int16_t* pData, file_offset_t WordCount) {
672        #if DEBUG          #if DEBUG_RIFF
673        std::cout << "Chunk::ReadInt16(int16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt16(int16_t*,file_offset_t)" << std::endl;
674        #endif // DEBUG          #endif // DEBUG_RIFF
675          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
676      }      }
677    
# Line 485  namespace RIFF { Line 686  namespace RIFF {
686       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
687       * @param WordCount         number of 16 Bit signed integers to write       * @param WordCount         number of 16 Bit signed integers to write
688       * @returns                 number of written integers       * @returns                 number of written integers
689       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
690       * @see Resize()       * @see Resize()
691         * @see File::IsIOPerThread() for multi-threaded streaming
692       */       */
693      unsigned long Chunk::WriteInt16(int16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt16(int16_t* pData, file_offset_t WordCount) {
694          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
695      }      }
696    
# Line 501  namespace RIFF { Line 703  namespace RIFF {
703       * @param pData             destination buffer       * @param pData             destination buffer
704       * @param WordCount         number of 8 Bit unsigned integers to read       * @param WordCount         number of 8 Bit unsigned integers to read
705       * @returns                 number of read integers       * @returns                 number of read integers
706       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
707       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
708         * @see File::IsIOPerThread() for multi-threaded streaming
709       */       */
710      unsigned long Chunk::ReadUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint16(uint16_t* pData, file_offset_t WordCount) {
711        #if DEBUG          #if DEBUG_RIFF
712        std::cout << "Chunk::ReadUint16(uint16_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint16(uint16_t*,file_offset_t)" << std::endl;
713        #endif // DEBUG          #endif // DEBUG_RIFF
714          return ReadSceptical(pData, WordCount, 2);          return ReadSceptical(pData, WordCount, 2);
715      }      }
716    
# Line 522  namespace RIFF { Line 725  namespace RIFF {
725       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
726       * @param WordCount         number of 16 Bit unsigned integers to write       * @param WordCount         number of 16 Bit unsigned integers to write
727       * @returns                 number of written integers       * @returns                 number of written integers
728       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
729       * @see Resize()       * @see Resize()
730         * @see File::IsIOPerThread() for multi-threaded streaming
731       */       */
732      unsigned long Chunk::WriteUint16(uint16_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint16(uint16_t* pData, file_offset_t WordCount) {
733          return Write(pData, WordCount, 2);          return Write(pData, WordCount, 2);
734      }      }
735    
# Line 538  namespace RIFF { Line 742  namespace RIFF {
742       * @param pData             destination buffer       * @param pData             destination buffer
743       * @param WordCount         number of 32 Bit signed integers to read       * @param WordCount         number of 32 Bit signed integers to read
744       * @returns                 number of read integers       * @returns                 number of read integers
745       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
746       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
747         * @see File::IsIOPerThread() for multi-threaded streaming
748       */       */
749      unsigned long Chunk::ReadInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadInt32(int32_t* pData, file_offset_t WordCount) {
750         #if DEBUG          #if DEBUG_RIFF
751         std::cout << "Chunk::ReadInt32(int32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadInt32(int32_t*,file_offset_t)" << std::endl;
752         #endif // DEBUG          #endif // DEBUG_RIFF
753          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
754      }      }
755    
# Line 559  namespace RIFF { Line 764  namespace RIFF {
764       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
765       * @param WordCount         number of 32 Bit signed integers to write       * @param WordCount         number of 32 Bit signed integers to write
766       * @returns                 number of written integers       * @returns                 number of written integers
767       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
768       * @see Resize()       * @see Resize()
769         * @see File::IsIOPerThread() for multi-threaded streaming
770       */       */
771      unsigned long Chunk::WriteInt32(int32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteInt32(int32_t* pData, file_offset_t WordCount) {
772          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
773      }      }
774    
# Line 575  namespace RIFF { Line 781  namespace RIFF {
781       * @param pData             destination buffer       * @param pData             destination buffer
782       * @param WordCount         number of 32 Bit unsigned integers to read       * @param WordCount         number of 32 Bit unsigned integers to read
783       * @returns                 number of read integers       * @returns                 number of read integers
784       * @throws RIFF::Exception  if an error occured or less than       * @throws RIFF::Exception  if an error occurred or less than
785       *                          \a WordCount integers could be read!       *                          \a WordCount integers could be read!
786         * @see File::IsIOPerThread() for multi-threaded streaming
787       */       */
788      unsigned long Chunk::ReadUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::ReadUint32(uint32_t* pData, file_offset_t WordCount) {
789         #if DEBUG          #if DEBUG_RIFF
790         std::cout << "Chunk::ReadUint32(uint32_t*,ulong)" << std::endl;          std::cout << "Chunk::ReadUint32(uint32_t*,file_offset_t)" << std::endl;
791         #endif // DEBUG          #endif // DEBUG_RIFF
792          return ReadSceptical(pData, WordCount, 4);          return ReadSceptical(pData, WordCount, 4);
793      }      }
794    
795      /**      /**
796         * Reads a null-padded string of size characters and copies it
797         * into the string \a s. The position within the chunk will
798         * automatically be incremented.
799         *
800         * @param s                 destination string
801         * @param size              number of characters to read
802         * @throws RIFF::Exception  if an error occurred or less than
803         *                          \a size characters could be read!
804         * @see File::IsIOPerThread() for multi-threaded streaming
805         */
806        void Chunk::ReadString(String& s, int size) {
807            char* buf = new char[size];
808            ReadSceptical(buf, 1, size);
809            s.assign(buf, std::find(buf, buf + size, '\0'));
810            delete[] buf;
811        }
812    
813        /**
814       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
815       * buffer pointed by \a pData to the chunk's body, directly to the       * buffer pointed by \a pData to the chunk's body, directly to the
816       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 596  namespace RIFF { Line 821  namespace RIFF {
821       * @param pData             source buffer (containing the data)       * @param pData             source buffer (containing the data)
822       * @param WordCount         number of 32 Bit unsigned integers to write       * @param WordCount         number of 32 Bit unsigned integers to write
823       * @returns                 number of written integers       * @returns                 number of written integers
824       * @throws RIFF::Exception  if an IO error occured       * @throws RIFF::Exception  if an IO error occurred
825       * @see Resize()       * @see Resize()
826         * @see File::IsIOPerThread() for multi-threaded streaming
827       */       */
828      unsigned long Chunk::WriteUint32(uint32_t* pData, unsigned long WordCount) {      file_offset_t Chunk::WriteUint32(uint32_t* pData, file_offset_t WordCount) {
829          return Write(pData, WordCount, 4);          return Write(pData, WordCount, 4);
830      }      }
831    
# Line 608  namespace RIFF { Line 834  namespace RIFF {
834       * the chunk.       * the chunk.
835       *       *
836       * @returns                 read integer word       * @returns                 read integer word
837       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
838         * @see File::IsIOPerThread() for multi-threaded streaming
839       */       */
840      int8_t Chunk::ReadInt8() {      int8_t Chunk::ReadInt8() {
841        #if DEBUG          #if DEBUG_RIFF
842        std::cout << "Chunk::ReadInt8()" << std::endl;          std::cout << "Chunk::ReadInt8()" << std::endl;
843        #endif // DEBUG          #endif // DEBUG_RIFF
844          int8_t word;          int8_t word;
845          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
846          return word;          return word;
# Line 624  namespace RIFF { Line 851  namespace RIFF {
851       * within the chunk.       * within the chunk.
852       *       *
853       * @returns                 read integer word       * @returns                 read integer word
854       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
855         * @see File::IsIOPerThread() for multi-threaded streaming
856       */       */
857      uint8_t Chunk::ReadUint8() {      uint8_t Chunk::ReadUint8() {
858        #if DEBUG          #if DEBUG_RIFF
859        std::cout << "Chunk::ReadUint8()" << std::endl;          std::cout << "Chunk::ReadUint8()" << std::endl;
860        #endif // DEBUG          #endif // DEBUG_RIFF
861          uint8_t word;          uint8_t word;
862          ReadSceptical(&word,1,1);          ReadSceptical(&word,1,1);
863          return word;          return word;
# Line 641  namespace RIFF { Line 869  namespace RIFF {
869       * needed.       * needed.
870       *       *
871       * @returns                 read integer word       * @returns                 read integer word
872       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
873         * @see File::IsIOPerThread() for multi-threaded streaming
874       */       */
875      int16_t Chunk::ReadInt16() {      int16_t Chunk::ReadInt16() {
876        #if DEBUG          #if DEBUG_RIFF
877        std::cout << "Chunk::ReadInt16()" << std::endl;          std::cout << "Chunk::ReadInt16()" << std::endl;
878        #endif // DEBUG          #endif // DEBUG_RIFF
879          int16_t word;          int16_t word;
880          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
881          return word;          return word;
# Line 658  namespace RIFF { Line 887  namespace RIFF {
887       * needed.       * needed.
888       *       *
889       * @returns                 read integer word       * @returns                 read integer word
890       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
891         * @see File::IsIOPerThread() for multi-threaded streaming
892       */       */
893      uint16_t Chunk::ReadUint16() {      uint16_t Chunk::ReadUint16() {
894        #if DEBUG          #if DEBUG_RIFF
895        std::cout << "Chunk::ReadUint16()" << std::endl;          std::cout << "Chunk::ReadUint16()" << std::endl;
896        #endif // DEBUG          #endif // DEBUG_RIFF
897          uint16_t word;          uint16_t word;
898          ReadSceptical(&word,1,2);          ReadSceptical(&word,1,2);
899          return word;          return word;
# Line 675  namespace RIFF { Line 905  namespace RIFF {
905       * needed.       * needed.
906       *       *
907       * @returns                 read integer word       * @returns                 read integer word
908       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
909         * @see File::IsIOPerThread() for multi-threaded streaming
910       */       */
911      int32_t Chunk::ReadInt32() {      int32_t Chunk::ReadInt32() {
912        #if DEBUG          #if DEBUG_RIFF
913        std::cout << "Chunk::ReadInt32()" << std::endl;          std::cout << "Chunk::ReadInt32()" << std::endl;
914        #endif // DEBUG          #endif // DEBUG_RIFF
915          int32_t word;          int32_t word;
916          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
917          return word;          return word;
# Line 692  namespace RIFF { Line 923  namespace RIFF {
923       * needed.       * needed.
924       *       *
925       * @returns                 read integer word       * @returns                 read integer word
926       * @throws RIFF::Exception  if an error occured       * @throws RIFF::Exception  if an error occurred
927         * @see File::IsIOPerThread() for multi-threaded streamings
928       */       */
929      uint32_t Chunk::ReadUint32() {      uint32_t Chunk::ReadUint32() {
930        #if DEBUG          #if DEBUG_RIFF
931        std::cout << "Chunk::ReadUint32()" << std::endl;          std::cout << "Chunk::ReadUint32()" << std::endl;
932        #endif // DEBUG          #endif // DEBUG_RIFF
933          uint32_t word;          uint32_t word;
934          ReadSceptical(&word,1,4);          ReadSceptical(&word,1,4);
935          return word;          return word;
# Line 723  namespace RIFF { Line 955  namespace RIFF {
955       * @returns a pointer to the data in RAM on success, NULL otherwise       * @returns a pointer to the data in RAM on success, NULL otherwise
956       * @throws Exception if data buffer could not be enlarged       * @throws Exception if data buffer could not be enlarged
957       * @see ReleaseChunkData()       * @see ReleaseChunkData()
958         * @see File::IsIOPerThread() for multi-threaded streaming
959       */       */
960      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
961          if (!pChunkData && pFile->Filename != "") {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
962                File::Handle hRead = pFile->FileHandle();
963              #if POSIX              #if POSIX
964              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(hRead, ullStartPos, SEEK_SET) == -1) return NULL;
965              #elif defined(WIN32)              #elif defined(WIN32)
966              if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;              LARGE_INTEGER liFilePos;
967                liFilePos.QuadPart = ullStartPos;
968                if (!SetFilePointerEx(hRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN)) return NULL;
969              #else              #else
970              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseeko(hRead, ullStartPos, SEEK_SET)) return NULL;
971              #endif // POSIX              #endif // POSIX
972              unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;              file_offset_t ullBufferSize = (ullCurrentChunkSize > ullNewChunkSize) ? ullCurrentChunkSize : ullNewChunkSize;
973              pChunkData = new uint8_t[ulBufferSize];              pChunkData = new uint8_t[ullBufferSize];
974              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
975              memset(pChunkData, 0, ulBufferSize);              memset(pChunkData, 0, ullBufferSize);
976              #if POSIX              #if POSIX
977              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());              file_offset_t readWords = read(hRead, pChunkData, GetSize());
978              #elif defined(WIN32)              #elif defined(WIN32)
979              DWORD readWords;              DWORD readWords;
980              ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);              ReadFile(hRead, pChunkData, GetSize(), &readWords, NULL); //FIXME: won't load chunks larger than 2GB !
981              #else              #else
982              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              file_offset_t readWords = fread(pChunkData, 1, GetSize(), hRead);
983              #endif // POSIX              #endif // POSIX
984              if (readWords != GetSize()) {              if (readWords != GetSize()) {
985                  delete[] pChunkData;                  delete[] pChunkData;
986                  return (pChunkData = NULL);                  return (pChunkData = NULL);
987              }              }
988              ulChunkDataSize = ulBufferSize;              ullChunkDataSize = ullBufferSize;
989          } else if (NewChunkSize > ulChunkDataSize) {          } else if (ullNewChunkSize > ullChunkDataSize) {
990              uint8_t* pNewBuffer = new uint8_t[NewChunkSize];              uint8_t* pNewBuffer = new uint8_t[ullNewChunkSize];
991              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");
992              memset(pNewBuffer, 0 , NewChunkSize);              memset(pNewBuffer, 0 , ullNewChunkSize);
993              memcpy(pNewBuffer, pChunkData, ulChunkDataSize);              if (pChunkData) {
994              delete[] pChunkData;                  memcpy(pNewBuffer, pChunkData, ullChunkDataSize);
995              pChunkData      = pNewBuffer;                  delete[] pChunkData;
996              ulChunkDataSize = NewChunkSize;              }
997                pChunkData       = pNewBuffer;
998                ullChunkDataSize = ullNewChunkSize;
999          }          }
1000          return pChunkData;          return pChunkData;
1001      }      }
# Line 789  namespace RIFF { Line 1027  namespace RIFF {
1027       * calling File::Save() as this might exceed the current chunk's body       * calling File::Save() as this might exceed the current chunk's body
1028       * boundary!       * boundary!
1029       *       *
1030       * @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)
1031       * @throws RIFF::Exception  if \a iNewSize is less than 1       * @throws RIFF::Exception  if \a NewSize is less than 1 or unrealistic large
1032       * @see File::Save()       * @see File::Save()
1033       */       */
1034      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(file_offset_t NewSize) {
1035          if (iNewSize <= 0)          if (NewSize == 0)
1036              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));
1037          if (NewChunkSize == iNewSize) return;          if ((NewSize >> 48) != 0)
1038          NewChunkSize = iNewSize;              throw Exception("Unrealistic high chunk size detected: " + __resolveChunkPath(this));
1039          pFile->LogAsResized(this);          if (ullNewChunkSize == NewSize) return;
1040            ullNewChunkSize = NewSize;
1041      }      }
1042    
1043      /** @brief Write chunk persistently e.g. to disk.      /** @brief Write chunk persistently e.g. to disk.
1044       *       *
1045       * Stores the chunk persistently to its actual "physical" file.       * Stores the chunk persistently to its actual "physical" file.
1046       *       *
1047       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
1048       *                     chunk should be written to       *                     chunk should be written to
1049       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
1050       *                              the file       *                              the file
1051         * @param pProgress - optional: callback function for progress notification
1052       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
1053       *          \a ulWritePos incremented by this chunk's new size       *          \a ullWritePos incremented by this chunk's new size
1054       *          (including its header size of course)       *          (including its header size of course)
1055         * @see File::IsIOPerThread() for multi-threaded streaming
1056       */       */
1057      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      file_offset_t Chunk::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
1058          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
1059          ulWritePos += CHUNK_HEADER_SIZE;          ullWritePos += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1060    
1061            const File::HandlePair io = pFile->FileHandlePair();
1062    
1063          if (pFile->Mode != stream_mode_read_write)          if (io.Mode != stream_mode_read_write)
1064              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");
1065    
1066          // if the whole chunk body was loaded into RAM          // if the whole chunk body was loaded into RAM
# Line 826  namespace RIFF { Line 1069  namespace RIFF {
1069              LoadChunkData();              LoadChunkData();
1070              // write chunk data from RAM persistently to the file              // write chunk data from RAM persistently to the file
1071              #if POSIX              #if POSIX
1072              lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              lseek(io.hWrite, ullWritePos, SEEK_SET);
1073              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(io.hWrite, pChunkData, ullNewChunkSize) != ullNewChunkSize) {
1074                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
1075              }              }
1076              #elif defined(WIN32)              #elif defined(WIN32)
1077              SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);              LARGE_INTEGER liFilePos;
1078                liFilePos.QuadPart = ullWritePos;
1079                SetFilePointerEx(io.hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1080              DWORD dwBytesWritten;              DWORD dwBytesWritten;
1081              WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);              WriteFile(io.hWrite, pChunkData, ullNewChunkSize, &dwBytesWritten, NULL); //FIXME: won't save chunks larger than 2GB !
1082              if (dwBytesWritten != NewChunkSize) {              if (dwBytesWritten != ullNewChunkSize) {
1083                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
1084              }              }
1085              #else              #else
1086              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseeko(io.hWrite, ullWritePos, SEEK_SET);
1087              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, ullNewChunkSize, io.hWrite) != ullNewChunkSize) {
1088                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
1089              }              }
1090              #endif // POSIX              #endif // POSIX
1091          } else {          } else {
1092              // 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
1093              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1094              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              file_offset_t ullToMove = (ullNewChunkSize < ullCurrentChunkSize) ? ullNewChunkSize : ullCurrentChunkSize;
1095              #if defined(WIN32)              #if defined(WIN32)
1096              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
1097              #else              #else
1098              int iBytesMoved = 1;              int iBytesMoved = 1;
1099              #endif              #endif
1100              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (file_offset_t ullOffset = 0; ullToMove > 0 && iBytesMoved > 0; ullOffset += iBytesMoved, ullToMove -= iBytesMoved) {
1101                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ullToMove < 4096) ? int(ullToMove) : 4096;
1102                  #if POSIX                  #if POSIX
1103                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(io.hRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
1104                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = (int) read(io.hRead, pCopyBuffer, (size_t) iBytesMoved);
1105                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(io.hWrite, ullWritePos + ullOffset, SEEK_SET);
1106                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = (int) write(io.hWrite, pCopyBuffer, (size_t) iBytesMoved);
1107                  #elif defined(WIN32)                  #elif defined(WIN32)
1108                  SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  LARGE_INTEGER liFilePos;
1109                  ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  liFilePos.QuadPart = ullStartPos + ullCurrentDataOffset + ullOffset;
1110                  SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);                  SetFilePointerEx(io.hRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1111                  WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(io.hRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1112                    liFilePos.QuadPart = ullWritePos + ullOffset;
1113                    SetFilePointerEx(io.hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1114                    WriteFile(io.hWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1115                  #else                  #else
1116                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseeko(io.hRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
1117                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, io.hRead);
1118                  fseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  fseeko(io.hWrite, ullWritePos + ullOffset, SEEK_SET);
1119                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, io.hWrite);
1120                  #endif                  #endif
1121              }              }
1122              delete[] pCopyBuffer;              delete[] pCopyBuffer;
# Line 876  namespace RIFF { Line 1124  namespace RIFF {
1124          }          }
1125    
1126          // update this chunk's header          // update this chunk's header
1127          CurrentChunkSize = NewChunkSize;          ullCurrentChunkSize = ullNewChunkSize;
1128          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
1129    
1130            if (pProgress)
1131                __notify_progress(pProgress, 1.0); // notify done
1132    
1133          // update chunk's position pointers          // update chunk's position pointers
1134          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;          ullStartPos = ullOriginalPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1135          ulPos      = 0;          Chunk::__resetPos();
1136    
1137          // add pad byte if needed          // add pad byte if needed
1138          if ((ulStartPos + NewChunkSize) % 2 != 0) {          if ((ullStartPos + ullNewChunkSize) % 2 != 0) {
1139              const char cPadByte = 0;              const char cPadByte = 0;
1140              #if POSIX              #if POSIX
1141              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(io.hWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
1142              write(pFile->hFileWrite, &cPadByte, 1);              write(io.hWrite, &cPadByte, 1);
1143              #elif defined(WIN32)              #elif defined(WIN32)
1144              SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);              LARGE_INTEGER liFilePos;
1145                liFilePos.QuadPart = ullStartPos + ullNewChunkSize;
1146                SetFilePointerEx(io.hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1147              DWORD dwBytesWritten;              DWORD dwBytesWritten;
1148              WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);              WriteFile(io.hWrite, &cPadByte, 1, &dwBytesWritten, NULL);
1149              #else              #else
1150              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseeko(io.hWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
1151              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, io.hWrite);
1152              #endif              #endif
1153              return ulStartPos + NewChunkSize + 1;              return ullStartPos + ullNewChunkSize + 1;
1154          }          }
1155    
1156          return ulStartPos + NewChunkSize;          return ullStartPos + ullNewChunkSize;
1157      }      }
1158    
1159      void Chunk::__resetPos() {      void Chunk::__resetPos() {
1160          ulPos = 0;          std::lock_guard<std::mutex> lock(chunkPos.mutex);
1161            chunkPos.ullPos = 0;
1162            chunkPos.byThread.clear();
1163      }      }
1164    
1165    
# Line 913  namespace RIFF { Line 1168  namespace RIFF {
1168  // *  // *
1169    
1170      List::List(File* pFile) : Chunk(pFile) {      List::List(File* pFile) : Chunk(pFile) {
1171        #if DEBUG          #if DEBUG_RIFF
1172        std::cout << "List::List(File* pFile)" << std::endl;          std::cout << "List::List(File* pFile)" << std::endl;
1173        #endif // DEBUG          #endif // DEBUG_RIFF
1174          pSubChunks    = NULL;          pSubChunks    = NULL;
1175          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1176      }      }
1177    
1178      List::List(File* pFile, unsigned long StartPos, List* Parent)      List::List(File* pFile, file_offset_t StartPos, List* Parent)
1179        : Chunk(pFile, StartPos, Parent) {        : Chunk(pFile, StartPos, Parent) {
1180          #if DEBUG          #if DEBUG_RIFF
1181          std::cout << "List::List(File*,ulong,bool,List*)" << std::endl;          std::cout << "List::List(File*,file_offset_t,List*)" << std::endl;
1182          #endif // DEBUG          #endif // DEBUG_RIFF
1183          pSubChunks    = NULL;          pSubChunks    = NULL;
1184          pSubChunksMap = NULL;          pSubChunksMap = NULL;
1185          ReadHeader(StartPos);          ReadHeader(StartPos);
1186          ulStartPos    = StartPos + LIST_HEADER_SIZE;          ullStartPos = StartPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1187      }      }
1188    
1189      List::List(File* pFile, List* pParent, uint32_t uiListID)      List::List(File* pFile, List* pParent, uint32_t uiListID)
# Line 939  namespace RIFF { Line 1194  namespace RIFF {
1194      }      }
1195    
1196      List::~List() {      List::~List() {
1197        #if DEBUG          #if DEBUG_RIFF
1198        std::cout << "List::~List()" << std::endl;          std::cout << "List::~List()" << std::endl;
1199        #endif // DEBUG          #endif // DEBUG_RIFF
1200            DeleteChunkList();
1201        }
1202    
1203        void List::DeleteChunkList() {
1204          if (pSubChunks) {          if (pSubChunks) {
1205              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
1206              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 950  namespace RIFF { Line 1209  namespace RIFF {
1209                  iter++;                  iter++;
1210              }              }
1211              delete pSubChunks;              delete pSubChunks;
1212                pSubChunks = NULL;
1213            }
1214            if (pSubChunksMap) {
1215                delete pSubChunksMap;
1216                pSubChunksMap = NULL;
1217          }          }
1218          if (pSubChunksMap) delete pSubChunksMap;      }
1219    
1220        /**
1221         *  Returns subchunk at supplied @a pos position within this chunk list.
1222         *  If supplied @a pos is out of bounds then @c NULL is returned. The
1223         *  returned subchunk can either by an ordinary data chunk or a list chunk.
1224         *
1225         *  @param pos - position of sought subchunk within this list
1226         *  @returns pointer to the subchunk or NULL if supplied position is not
1227         *           within the valid range of this list
1228         */
1229        Chunk* List::GetSubChunkAt(size_t pos) {
1230            if (!pSubChunks) LoadSubChunks();
1231            if (pos >= pSubChunks->size()) return NULL;
1232            return (*pSubChunks)[pos];
1233      }      }
1234    
1235      /**      /**
# Line 966  namespace RIFF { Line 1244  namespace RIFF {
1244       *                   that ID       *                   that ID
1245       */       */
1246      Chunk* List::GetSubChunk(uint32_t ChunkID) {      Chunk* List::GetSubChunk(uint32_t ChunkID) {
1247        #if DEBUG          #if DEBUG_RIFF
1248        std::cout << "List::GetSubChunk(uint32_t)" << std::endl;          std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
1249        #endif // DEBUG          #endif // DEBUG_RIFF
1250          if (!pSubChunksMap) LoadSubChunks();          if (!pSubChunksMap) LoadSubChunks();
1251          return (*pSubChunksMap)[ChunkID];          return (*pSubChunksMap)[ChunkID];
1252      }      }
1253    
1254      /**      /**
1255         *  Returns sublist chunk with list type <i>\a ListType</i> at supplied
1256         *  @a pos position among all subchunks of type <i>\a ListType</i> within
1257         *  this chunk list. If supplied @a pos is out of bounds then @c NULL is
1258         *  returned.
1259         *
1260         *  @param pos - position of sought sublist within this list
1261         *  @returns pointer to the sublist or NULL if if supplied position is not
1262         *           within valid range
1263         */
1264        List* List::GetSubListAt(size_t pos) {
1265            if (!pSubChunks) LoadSubChunks();
1266            if (pos >= pSubChunks->size()) return NULL;
1267            for (size_t iCk = 0, iLst = 0; iCk < pSubChunks->size(); ++iCk) {
1268                Chunk* pChunk = (*pSubChunks)[iCk];
1269                if (pChunk->GetChunkID() != CHUNK_ID_LIST) continue;
1270                if (iLst == pos) return (List*) pChunk;
1271                ++iLst;
1272            }
1273            return NULL;
1274        }
1275    
1276        /**
1277       *  Returns sublist chunk with list type <i>\a ListType</i> within this       *  Returns sublist chunk with list type <i>\a ListType</i> within this
1278       *  chunk list. Use this method if you expect only one sublist chunk of       *  chunk list. Use this method if you expect only one sublist chunk of
1279       *  that type in the list. It there are more than one, it's undetermined       *  that type in the list. If there are more than one, it's undetermined
1280       *  which one of them will be returned! If there are no sublists with       *  which one of them will be returned! If there are no sublists with
1281       *  that desired list type, NULL will be returned.       *  that desired list type, NULL will be returned.
1282       *       *
# Line 985  namespace RIFF { Line 1285  namespace RIFF {
1285       *                    that type       *                    that type
1286       */       */
1287      List* List::GetSubList(uint32_t ListType) {      List* List::GetSubList(uint32_t ListType) {
1288          #if DEBUG          #if DEBUG_RIFF
1289          std::cout << "List::GetSubList(uint32_t)" << std::endl;          std::cout << "List::GetSubList(uint32_t)" << std::endl;
1290          #endif // DEBUG          #endif // DEBUG_RIFF
1291          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1292          ChunkList::iterator iter = pSubChunks->begin();          ChunkList::iterator iter = pSubChunks->begin();
1293          ChunkList::iterator end  = pSubChunks->end();          ChunkList::iterator end  = pSubChunks->end();
# Line 1002  namespace RIFF { Line 1302  namespace RIFF {
1302      }      }
1303    
1304      /**      /**
1305       *  Returns the first subchunk within the list. You have to call this       *  Returns the first subchunk within the list (which may be an ordinary
1306         *  chunk as well as a list chunk). You have to call this
1307       *  method before you can call GetNextSubChunk(). Recall it when you want       *  method before you can call GetNextSubChunk(). Recall it when you want
1308       *  to start from the beginning of the list again.       *  to start from the beginning of the list again.
1309       *       *
1310       *  @returns  pointer to the first subchunk within the list, NULL       *  @returns  pointer to the first subchunk within the list, NULL
1311       *            otherwise       *            otherwise
1312         *  @deprecated  This method is not reentrant-safe, use GetSubChunkAt()
1313         *               instead.
1314       */       */
1315      Chunk* List::GetFirstSubChunk() {      Chunk* List::GetFirstSubChunk() {
1316          #if DEBUG          #if DEBUG_RIFF
1317          std::cout << "List::GetFirstSubChunk()" << std::endl;          std::cout << "List::GetFirstSubChunk()" << std::endl;
1318          #endif // DEBUG          #endif // DEBUG_RIFF
1319          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1320          ChunksIterator = pSubChunks->begin();          ChunksIterator = pSubChunks->begin();
1321          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1322      }      }
1323    
1324      /**      /**
1325       *  Returns the next subchunk within the list. You have to call       *  Returns the next subchunk within the list (which may be an ordinary
1326         *  chunk as well as a list chunk). You have to call
1327       *  GetFirstSubChunk() before you can use this method!       *  GetFirstSubChunk() before you can use this method!
1328       *       *
1329       *  @returns  pointer to the next subchunk within the list or NULL if       *  @returns  pointer to the next subchunk within the list or NULL if
1330       *            end of list is reached       *            end of list is reached
1331         *  @deprecated  This method is not reentrant-safe, use GetSubChunkAt()
1332         *               instead.
1333       */       */
1334      Chunk* List::GetNextSubChunk() {      Chunk* List::GetNextSubChunk() {
1335          #if DEBUG          #if DEBUG_RIFF
1336          std::cout << "List::GetNextSubChunk()" << std::endl;          std::cout << "List::GetNextSubChunk()" << std::endl;
1337          #endif // DEBUG          #endif // DEBUG_RIFF
1338          if (!pSubChunks) return NULL;          if (!pSubChunks) return NULL;
1339          ChunksIterator++;          ChunksIterator++;
1340          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;          return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
# Line 1042  namespace RIFF { Line 1348  namespace RIFF {
1348       *       *
1349       *  @returns  pointer to the first sublist within the list, NULL       *  @returns  pointer to the first sublist within the list, NULL
1350       *            otherwise       *            otherwise
1351         *  @deprecated  This method is not reentrant-safe, use GetSubListAt()
1352         *               instead.
1353       */       */
1354      List* List::GetFirstSubList() {      List* List::GetFirstSubList() {
1355          #if DEBUG          #if DEBUG_RIFF
1356          std::cout << "List::GetFirstSubList()" << std::endl;          std::cout << "List::GetFirstSubList()" << std::endl;
1357          #endif // DEBUG          #endif // DEBUG_RIFF
1358          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1359          ListIterator            = pSubChunks->begin();          ListIterator            = pSubChunks->begin();
1360          ChunkList::iterator end = pSubChunks->end();          ChunkList::iterator end = pSubChunks->end();
# Line 1064  namespace RIFF { Line 1372  namespace RIFF {
1372       *       *
1373       *  @returns  pointer to the next sublist within the list, NULL if       *  @returns  pointer to the next sublist within the list, NULL if
1374       *            end of list is reached       *            end of list is reached
1375         *  @deprecated  This method is not reentrant-safe, use GetSubListAt()
1376         *               instead.
1377       */       */
1378      List* List::GetNextSubList() {      List* List::GetNextSubList() {
1379          #if DEBUG          #if DEBUG_RIFF
1380          std::cout << "List::GetNextSubList()" << std::endl;          std::cout << "List::GetNextSubList()" << std::endl;
1381          #endif // DEBUG          #endif // DEBUG_RIFF
1382          if (!pSubChunks) return NULL;          if (!pSubChunks) return NULL;
1383          if (ListIterator == pSubChunks->end()) return NULL;          if (ListIterator == pSubChunks->end()) return NULL;
1384          ListIterator++;          ListIterator++;
# Line 1081  namespace RIFF { Line 1391  namespace RIFF {
1391      }      }
1392    
1393      /**      /**
1394       *  Returns number of subchunks within the list.       *  Returns number of subchunks within the list (including list chunks).
1395       */       */
1396      unsigned int List::CountSubChunks() {      size_t List::CountSubChunks() {
1397          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1398          return pSubChunks->size();          return pSubChunks->size();
1399      }      }
# Line 1092  namespace RIFF { Line 1402  namespace RIFF {
1402       *  Returns number of subchunks within the list with chunk ID       *  Returns number of subchunks within the list with chunk ID
1403       *  <i>\a ChunkId</i>.       *  <i>\a ChunkId</i>.
1404       */       */
1405      unsigned int List::CountSubChunks(uint32_t ChunkID) {      size_t List::CountSubChunks(uint32_t ChunkID) {
1406          unsigned int result = 0;          size_t result = 0;
1407          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1408          ChunkList::iterator iter = pSubChunks->begin();          ChunkList::iterator iter = pSubChunks->begin();
1409          ChunkList::iterator end  = pSubChunks->end();          ChunkList::iterator end  = pSubChunks->end();
# Line 1109  namespace RIFF { Line 1419  namespace RIFF {
1419      /**      /**
1420       *  Returns number of sublists within the list.       *  Returns number of sublists within the list.
1421       */       */
1422      unsigned int List::CountSubLists() {      size_t List::CountSubLists() {
1423          return CountSubChunks(CHUNK_ID_LIST);          return CountSubChunks(CHUNK_ID_LIST);
1424      }      }
1425    
# Line 1117  namespace RIFF { Line 1427  namespace RIFF {
1427       *  Returns number of sublists within the list with list type       *  Returns number of sublists within the list with list type
1428       *  <i>\a ListType</i>       *  <i>\a ListType</i>
1429       */       */
1430      unsigned int List::CountSubLists(uint32_t ListType) {      size_t List::CountSubLists(uint32_t ListType) {
1431          unsigned int result = 0;          size_t result = 0;
1432          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1433          ChunkList::iterator iter = pSubChunks->begin();          ChunkList::iterator iter = pSubChunks->begin();
1434          ChunkList::iterator end  = pSubChunks->end();          ChunkList::iterator end  = pSubChunks->end();
# Line 1135  namespace RIFF { Line 1445  namespace RIFF {
1445      /** @brief Creates a new sub chunk.      /** @brief Creates a new sub chunk.
1446       *       *
1447       * 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
1448       * 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.
1449       * 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
1450       * actual file and <b>before</b> performing any data write operations       * actual file and <b>before</b> performing any data write operations
1451       * on the new chunk!       * on the new chunk!
1452       *       *
1453       * @param uiChunkID  - chunk ID of the new chunk       * @param uiChunkID  - chunk ID of the new chunk
1454       * @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
1455       *                     data size (without header)       *                      data size (without header)
1456       * @throws RIFF::Exception if \a uiBodySize equals zero       * @throws RIFF::Exception if \a ullBodySize equals zero
1457       */       */
1458      Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {      Chunk* List::AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize) {
1459          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");
1460          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1461          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);          Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1462          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1463          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1464          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(ullBodySize);
1465          NewChunkSize += CHUNK_HEADER_SIZE;          ullNewChunkSize += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1466          return pNewChunk;          return pNewChunk;
1467      }      }
1468    
1469      /** @brief Moves a sub chunk.      /** @brief Moves a sub chunk witin this list.
1470       *       *
1471       * Moves a sub chunk from one position in a list to another       * Moves a sub chunk from one position in this list to another
1472       * position in the same list. The pSrc chunk is placed before the       * position in the same list. The pSrc chunk is placed before the
1473       * pDst chunk.       * pDst chunk.
1474       *       *
# Line 1170  namespace RIFF { Line 1479  namespace RIFF {
1479       */       */
1480      void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {      void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1481          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1482          pSubChunks->remove(pSrc);          for (size_t i = 0; i < pSubChunks->size(); ++i) {
1483          ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);              if ((*pSubChunks)[i] == pSrc) {
1484          pSubChunks->insert(iter, pSrc);                  pSubChunks->erase(pSubChunks->begin() + i);
1485                    ChunkList::iterator iter =
1486                        find(pSubChunks->begin(), pSubChunks->end(), pDst);
1487                    pSubChunks->insert(iter, pSrc);
1488                    return;
1489                }
1490            }
1491        }
1492    
1493        /** @brief Moves a sub chunk from this list to another list.
1494         *
1495         * Moves a sub chunk from this list list to the end of another
1496         * list.
1497         *
1498         * @param pSrc - sub chunk to be moved
1499         * @param pDst - destination list where the chunk shall be moved to
1500         */
1501        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1502            if (pNewParent == this || !pNewParent) return;
1503            if (!pSubChunks) LoadSubChunks();
1504            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1505            ChunkList::iterator iter =
1506                find(pSubChunks->begin(), pSubChunks->end(), pSrc);
1507            if (iter == pSubChunks->end()) return;
1508            pSubChunks->erase(iter);
1509            pNewParent->pSubChunks->push_back(pSrc);
1510            // update chunk id map of this List
1511            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1512                pSubChunksMap->erase(pSrc->GetChunkID());
1513                // try to find another chunk of the same chunk ID
1514                ChunkList::iterator iter = pSubChunks->begin();
1515                ChunkList::iterator end  = pSubChunks->end();
1516                for (; iter != end; ++iter) {
1517                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1518                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1519                        break; // we're done, stop search
1520                    }
1521                }
1522            }
1523            // update chunk id map of other list
1524            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1525                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1526      }      }
1527    
1528      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
# Line 1189  namespace RIFF { Line 1539  namespace RIFF {
1539          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1540          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1541          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1542          NewChunkSize += LIST_HEADER_SIZE;          ullNewChunkSize += LIST_HEADER_SIZE(pFile->FileOffsetSize);
         pFile->LogAsResized(this);  
1543          return pNewListChunk;          return pNewListChunk;
1544      }      }
1545    
# Line 1206  namespace RIFF { Line 1555  namespace RIFF {
1555       */       */
1556      void List::DeleteSubChunk(Chunk* pSubChunk) {      void List::DeleteSubChunk(Chunk* pSubChunk) {
1557          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
1558          pSubChunks->remove(pSubChunk);          ChunkList::iterator iter =
1559                find(pSubChunks->begin(), pSubChunks->end(), pSubChunk);
1560            if (iter == pSubChunks->end()) return;
1561            pSubChunks->erase(iter);
1562          if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {          if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1563              pSubChunksMap->erase(pSubChunk->GetChunkID());              pSubChunksMap->erase(pSubChunk->GetChunkID());
1564              // try to find another chunk of the same chunk ID              // try to find another chunk of the same chunk ID
# Line 1222  namespace RIFF { Line 1574  namespace RIFF {
1574          delete pSubChunk;          delete pSubChunk;
1575      }      }
1576    
1577      void List::ReadHeader(unsigned long fPos) {      /**
1578        #if DEBUG       *  Returns the actual total size in bytes (including List chunk header and
1579        std::cout << "List::Readheader(ulong) ";       *  all subchunks) of this List Chunk if being stored to a file.
1580        #endif // DEBUG       *
1581          Chunk::ReadHeader(fPos);       *  @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
1582          NewChunkSize = CurrentChunkSize -= 4;       *                          being saved to a file
1583         */
1584        file_offset_t List::RequiredPhysicalSize(int fileOffsetSize) {
1585            if (!pSubChunks) LoadSubChunks();
1586            file_offset_t size = LIST_HEADER_SIZE(fileOffsetSize);
1587            ChunkList::iterator iter = pSubChunks->begin();
1588            ChunkList::iterator end  = pSubChunks->end();
1589            for (; iter != end; ++iter)
1590                size += (*iter)->RequiredPhysicalSize(fileOffsetSize);
1591            return size;
1592        }
1593    
1594        void List::ReadHeader(file_offset_t filePos) {
1595            #if DEBUG_RIFF
1596            std::cout << "List::Readheader(file_offset_t) ";
1597            #endif // DEBUG_RIFF
1598            Chunk::ReadHeader(filePos);
1599            if (ullCurrentChunkSize < 4) return;
1600            ullNewChunkSize = ullCurrentChunkSize -= 4;
1601    
1602            const File::Handle hRead = pFile->FileHandle();
1603    
1604          #if POSIX          #if POSIX
1605          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(hRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1606          read(pFile->hFileRead, &ListType, 4);          read(hRead, &ListType, 4);
1607          #elif defined(WIN32)          #elif defined(WIN32)
1608          SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          LARGE_INTEGER liFilePos;
1609            liFilePos.QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1610            SetFilePointerEx(hRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1611          DWORD dwBytesRead;          DWORD dwBytesRead;
1612          ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);          ReadFile(hRead, &ListType, 4, &dwBytesRead, NULL);
1613          #else          #else
1614          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(hRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1615          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, hRead);
1616          #endif // POSIX          #endif // POSIX
1617        #if DEBUG          #if DEBUG_RIFF
1618        std::cout << "listType=" << convertToString(ListType) << std::endl;          std::cout << "listType=" << convertToString(ListType) << std::endl;
1619        #endif // DEBUG          #endif // DEBUG_RIFF
1620          if (!pFile->bEndianNative) {          if (!pFile->bEndianNative) {
1621              //swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1622          }          }
1623      }      }
1624    
1625      void List::WriteHeader(unsigned long fPos) {      void List::WriteHeader(file_offset_t filePos) {
1626          // 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
1627          NewChunkSize += 4;          ullNewChunkSize += 4;
1628          Chunk::WriteHeader(fPos);          Chunk::WriteHeader(filePos);
1629          NewChunkSize -= 4; // just revert the +4 incrementation          ullNewChunkSize -= 4; // just revert the +4 incrementation
1630    
1631            const File::Handle hWrite = pFile->FileWriteHandle();
1632    
1633          #if POSIX          #if POSIX
1634          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(hWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1635          write(pFile->hFileWrite, &ListType, 4);          write(hWrite, &ListType, 4);
1636          #elif defined(WIN32)          #elif defined(WIN32)
1637          SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);          LARGE_INTEGER liFilePos;
1638            liFilePos.QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1639            SetFilePointerEx(hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1640          DWORD dwBytesWritten;          DWORD dwBytesWritten;
1641          WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);          WriteFile(hWrite, &ListType, 4, &dwBytesWritten, NULL);
1642          #else          #else
1643          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseeko(hWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1644          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, hWrite);
1645          #endif // POSIX          #endif // POSIX
1646      }      }
1647    
1648      void List::LoadSubChunks() {      void List::LoadSubChunks(progress_t* pProgress) {
1649         #if DEBUG          #if DEBUG_RIFF
1650         std::cout << "List::LoadSubChunks()";          std::cout << "List::LoadSubChunks()";
1651         #endif // DEBUG          #endif // DEBUG_RIFF
1652          if (!pSubChunks) {          if (!pSubChunks) {
1653              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1654              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1655              #if defined(WIN32)  
1656              if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;              const File::Handle hRead = pFile->FileHandle();
1657              #else              if (!_isValidHandle(hRead)) return;
1658              if (!pFile->hFileRead) return;  
1659              #endif              const file_offset_t ullOriginalPos = GetPos();
             unsigned long uiOriginalPos = GetPos();  
1660              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1661              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE(pFile->FileOffsetSize)) {
1662                  Chunk* ck;                  Chunk* ck;
1663                  uint32_t ckid;                  uint32_t ckid;
1664                  Read(&ckid, 4, 1);                  // return value check is required here to prevent a potential
1665         #if DEBUG                  // garbage data use of 'ckid' below in case Read() failed
1666         std::cout << " ckid=" << convertToString(ckid) << std::endl;                  if (Read(&ckid, 4, 1) != 4)
1667         #endif // DEBUG                      throw Exception("LoadSubChunks(): Failed reading RIFF chunk ID");
1668                    #if DEBUG_RIFF
1669                    std::cout << " ckid=" << convertToString(ckid) << std::endl;
1670                    #endif // DEBUG_RIFF
1671                    const file_offset_t pos = GetPos();
1672                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1673                      ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::List(pFile, ullStartPos + pos - 4, this);
1674                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1675                  }                  }
1676                  else { // simple chunk                  else { // simple chunk
1677                      ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);                      ck = new RIFF::Chunk(pFile, ullStartPos + pos - 4, this);
1678                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1679                  }                  }
1680                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1681                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1682                  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
1683              }              }
1684              SetPos(uiOriginalPos); // restore position before this call              SetPos(ullOriginalPos); // restore position before this call
1685          }          }
1686            if (pProgress)
1687                __notify_progress(pProgress, 1.0); // notify done
1688      }      }
1689    
1690      void List::LoadSubChunksRecursively() {      void List::LoadSubChunksRecursively(progress_t* pProgress) {
1691          for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())          const int n = (int) CountSubLists();
1692              pList->LoadSubChunksRecursively();          int i = 0;
1693            for (List* pList = GetSubListAt(i); pList; pList = GetSubListAt(++i)) {
1694                if (pProgress) {
1695                    // divide local progress into subprogress
1696                    progress_t subprogress;
1697                    __divide_progress(pProgress, &subprogress, n, i);
1698                    // do the actual work
1699                    pList->LoadSubChunksRecursively(&subprogress);
1700                } else
1701                    pList->LoadSubChunksRecursively(NULL);
1702            }
1703            if (pProgress)
1704                __notify_progress(pProgress, 1.0); // notify done
1705      }      }
1706    
1707      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
# Line 1313  namespace RIFF { Line 1710  namespace RIFF {
1710       * subchunks (including sub list chunks) will be stored recursively as       * subchunks (including sub list chunks) will be stored recursively as
1711       * well.       * well.
1712       *       *
1713       * @param ulWritePos - position within the "physical" file where this       * @param ullWritePos - position within the "physical" file where this
1714       *                     list chunk should be written to       *                     list chunk should be written to
1715       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ullCurrentDataOffset - offset of current (old) data within
1716       *                              the file       *                              the file
1717         * @param pProgress - optional: callback function for progress notification
1718       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
1719       *          \a ulWritePos incremented by this list chunk's new size       *          \a ullWritePos incremented by this list chunk's new size
1720       *          (including its header size of course)       *          (including its header size of course)
1721       */       */
1722      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      file_offset_t List::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
1723          const unsigned long ulOriginalPos = ulWritePos;          const file_offset_t ullOriginalPos = ullWritePos;
1724          ulWritePos += LIST_HEADER_SIZE;          ullWritePos += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1725    
1726          if (pFile->Mode != stream_mode_read_write)          if (pFile->GetMode() != stream_mode_read_write)
1727              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");
1728    
1729          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1730          if (pSubChunks) {          if (pSubChunks) {
1731              for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {              size_t i = 0;
1732                  ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);              const size_t n = pSubChunks->size();
1733                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1734                    if (pProgress) {
1735                        // divide local progress into subprogress for loading current Instrument
1736                        progress_t subprogress;
1737                        __divide_progress(pProgress, &subprogress, n, i);
1738                        // do the actual work
1739                        ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, &subprogress);
1740                    } else
1741                        ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, NULL);
1742              }              }
1743          }          }
1744    
1745          // update this list chunk's header          // update this list chunk's header
1746          CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;          ullCurrentChunkSize = ullNewChunkSize = ullWritePos - ullOriginalPos - LIST_HEADER_SIZE(pFile->FileOffsetSize);
1747          WriteHeader(ulOriginalPos);          WriteHeader(ullOriginalPos);
1748    
1749          // offset of this list chunk in new written file may have changed          // offset of this list chunk in new written file may have changed
1750          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;          ullStartPos = ullOriginalPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1751    
1752          return ulWritePos;          if (pProgress)
1753                __notify_progress(pProgress, 1.0); // notify done
1754    
1755            return ullWritePos;
1756      }      }
1757    
1758      void List::__resetPos() {      void List::__resetPos() {
# Line 1357  namespace RIFF { Line 1767  namespace RIFF {
1767      /**      /**
1768       *  Returns string representation of the lists's id       *  Returns string representation of the lists's id
1769       */       */
1770      String List::GetListTypeString() {      String List::GetListTypeString() const {
1771          return convertToString(ListType);          return convertToString(ListType);
1772      }      }
1773    
# Line 1380  namespace RIFF { Line 1790  namespace RIFF {
1790       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1791       * @see AddSubChunk(), AddSubList(), SetByteOrder()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1792       */       */
1793      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType)
1794            : List(this), bIsNewFile(true), Layout(layout_standard),
1795              FileOffsetPreference(offset_size_auto)
1796        {
1797            io.isPerThread = false;
1798          #if defined(WIN32)          #if defined(WIN32)
1799          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;          io.hRead = io.hWrite = INVALID_HANDLE_VALUE;
1800          #else          #else
1801          hFileRead = hFileWrite = 0;          io.hRead = io.hWrite = 0;
1802          #endif          #endif
1803          Mode = stream_mode_closed;          io.Mode = stream_mode_closed;
1804          bEndianNative = true;          bEndianNative = true;
         ulStartPos = RIFF_HEADER_SIZE;  
1805          ListType = FileType;          ListType = FileType;
1806            FileOffsetSize = 4;
1807            ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1808      }      }
1809    
1810      /** @brief Load existing RIFF file.      /** @brief Load existing RIFF file.
# Line 1397  namespace RIFF { Line 1812  namespace RIFF {
1812       * Loads an existing RIFF file with all its chunks.       * Loads an existing RIFF file with all its chunks.
1813       *       *
1814       * @param path - path and file name of the RIFF file to open       * @param path - path and file name of the RIFF file to open
1815       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occurred while trying to load the
1816       *                         given RIFF file       *                         given RIFF file
1817       */       */
1818      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path)
1819        #if DEBUG          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard),
1820        std::cout << "File::File("<<path<<")" << std::endl;            FileOffsetPreference(offset_size_auto)
1821        #endif // DEBUG      {
1822            #if DEBUG_RIFF
1823            std::cout << "File::File("<<path<<")" << std::endl;
1824            #endif // DEBUG_RIFF
1825          bEndianNative = true;          bEndianNative = true;
1826            FileOffsetSize = 4;
1827            try {
1828                __openExistingFile(path);
1829                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1830                    throw RIFF::Exception("Not a RIFF file");
1831                }
1832            }
1833            catch (...) {
1834                Cleanup();
1835                throw;
1836            }
1837        }
1838    
1839        /** @brief Load existing RIFF-like file.
1840         *
1841         * Loads an existing file, which is not a "real" RIFF file, but similar to
1842         * an ordinary RIFF file.
1843         *
1844         * A "real" RIFF file contains at top level a List chunk either with chunk
1845         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1846         * case, and if it finds the toplevel List chunk to have another chunk ID
1847         * than one of those two expected ones, it would throw an Exception and
1848         * would refuse to load the file accordingly.
1849         *
1850         * Since there are however a lot of file formats which use the same simple
1851         * principles of the RIFF format, with another toplevel List chunk ID
1852         * though, you can use this alternative constructor here to be able to load
1853         * and handle those files in the same way as you would do with "real" RIFF
1854         * files.
1855         *
1856         * @param path - path and file name of the RIFF-alike file to be opened
1857         * @param FileType - expected toplevel List chunk ID (this is the very
1858         *                   first chunk found in the file)
1859         * @param Endian - whether the file uses little endian or big endian layout
1860         * @param layout - general file structure type
1861         * @param fileOffsetSize - (optional) preference how to deal with large files
1862         * @throws RIFF::Exception if error occurred while trying to load the
1863         *                         given RIFF-alike file
1864         */
1865        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout, offset_size_t fileOffsetSize)
1866            : List(this), Filename(path), bIsNewFile(false), Layout(layout),
1867              FileOffsetPreference(fileOffsetSize)
1868        {
1869            SetByteOrder(Endian);
1870            if (fileOffsetSize < offset_size_auto || fileOffsetSize > offset_size_64bit)
1871                throw Exception("Invalid RIFF::offset_size_t");
1872            FileOffsetSize = 4;
1873            try {
1874                __openExistingFile(path, &FileType);
1875            }
1876            catch (...) {
1877                Cleanup();
1878                throw;
1879            }
1880        }
1881    
1882        /**
1883         * Opens an already existing RIFF file or RIFF-alike file. This method
1884         * shall only be called once (in a File class constructor).
1885         *
1886         * @param path - path and file name of the RIFF file or RIFF-alike file to
1887         *               be opened
1888         * @param FileType - (optional) expected chunk ID of first chunk in file
1889         * @throws RIFF::Exception if error occurred while trying to load the
1890         *                         given RIFF file or RIFF-alike file
1891         */
1892        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1893            io.isPerThread = false;
1894          #if POSIX          #if POSIX
1895          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          io.hRead = io.hWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1896          if (hFileRead <= 0) {          if (io.hRead == -1) {
1897              hFileRead = hFileWrite = 0;              io.hRead = io.hWrite = 0;
1898              throw RIFF::Exception("Can't open \"" + path + "\"");              String sError = strerror(errno);
1899                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1900          }          }
1901          #elif defined(WIN32)          #elif defined(WIN32)
1902          hFileRead = hFileWrite = CreateFile(          io.hRead = io.hWrite = CreateFile(
1903                                       path.c_str(), GENERIC_READ,                                       path.c_str(), GENERIC_READ,
1904                                       FILE_SHARE_READ | FILE_SHARE_WRITE,                                       FILE_SHARE_READ | FILE_SHARE_WRITE,
1905                                       NULL, OPEN_EXISTING,                                       NULL, OPEN_EXISTING,
1906                                       FILE_ATTRIBUTE_NORMAL |                                       FILE_ATTRIBUTE_NORMAL |
1907                                       FILE_FLAG_RANDOM_ACCESS, NULL                                       FILE_FLAG_RANDOM_ACCESS, NULL
1908                                   );                                   );
1909          if (hFileRead == INVALID_HANDLE_VALUE) {          if (io.hRead == INVALID_HANDLE_VALUE) {
1910              hFileRead = hFileWrite = INVALID_HANDLE_VALUE;              io.hRead = io.hWrite = INVALID_HANDLE_VALUE;
1911              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1912          }          }
1913          #else          #else
1914          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          io.hRead = io.hWrite = fopen(path.c_str(), "rb");
1915          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!io.hRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1916          #endif // POSIX          #endif // POSIX
1917          Mode = stream_mode_read;          io.Mode = stream_mode_read;
1918          ulStartPos = RIFF_HEADER_SIZE;  
1919          ReadHeader(0);          // determine RIFF file offset size to be used (in RIFF chunk headers)
1920          if (ChunkID != CHUNK_ID_RIFF) {          // according to the current file offset preference
1921              throw RIFF::Exception("Not a RIFF file");          FileOffsetSize = FileOffsetSizeFor(GetCurrentFileSize());
1922    
1923            switch (Layout) {
1924                case layout_standard: // this is a normal RIFF file
1925                    ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1926                    ReadHeader(0);
1927                    if (FileType && ChunkID != *FileType)
1928                        throw RIFF::Exception("Invalid file container ID");
1929                    break;
1930                case layout_flat: // non-standard RIFF-alike file
1931                    ullStartPos = 0;
1932                    ullNewChunkSize = ullCurrentChunkSize = GetCurrentFileSize();
1933                    if (FileType) {
1934                        uint32_t ckid;
1935                        if (Read(&ckid, 4, 1) != 4) {
1936                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1937                        } else if (ckid != *FileType) {
1938                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1939                            throw RIFF::Exception("Invalid file header ID" + s);
1940                        }
1941                        SetPos(0); // reset to first byte of file
1942                    }
1943                    LoadSubChunks();
1944                    break;
1945          }          }
1946      }      }
1947    
1948      String File::GetFileName() {      String File::GetFileName() const {
1949          return Filename;          return Filename;
1950      }      }
1951        
1952        void File::SetFileName(const String& path) {
1953            Filename = path;
1954        }
1955    
1956        /**
1957         * This is an internal-only method which must not be used by any application
1958         * and might change at any time.
1959         *
1960         * Resolves and returns a reference (memory location) of the RIFF file's
1961         * internal and OS dependent file I/O handles which are intended to be used
1962         * by the calling thread.
1963         */
1964        File::HandlePair& File::FileHandlePairUnsafeRef() {
1965            if (io.byThread.empty()) return io;
1966            const std::thread::id tid = std::this_thread::get_id();
1967            const auto it = io.byThread.find(tid);
1968            return (it != io.byThread.end()) ?
1969                it->second :
1970                io.byThread[tid] = {
1971                    #if defined(WIN32)
1972                    .hRead  = INVALID_HANDLE_VALUE,
1973                    .hWrite = INVALID_HANDLE_VALUE,
1974                    #else
1975                    .hRead  = 0,
1976                    .hWrite = 0,
1977                    #endif
1978                    .Mode = stream_mode_closed
1979                };
1980        }
1981    
1982        /**
1983         * Returns the OS dependent file I/O read and write handles intended to be
1984         * used by the calling thread.
1985         *
1986         * @see File::IsIOPerThread() for multi-threaded streaming
1987         */
1988        File::HandlePair File::FileHandlePair() const {
1989            std::lock_guard<std::mutex> lock(io.mutex);
1990            if (io.byThread.empty()) return io;
1991            const std::thread::id tid = std::this_thread::get_id();
1992            const auto it = io.byThread.find(tid);
1993            return (it != io.byThread.end()) ?
1994                it->second :
1995                io.byThread[tid] = {
1996                    #if defined(WIN32)
1997                    .hRead  = INVALID_HANDLE_VALUE,
1998                    .hWrite = INVALID_HANDLE_VALUE,
1999                    #else
2000                    .hRead  = 0,
2001                    .hWrite = 0,
2002                    #endif
2003                    .Mode = stream_mode_closed
2004                };
2005         }
2006    
2007        /**
2008         * Returns the OS dependent file I/O read handle intended to be used by the
2009         * calling thread.
2010         *
2011         * @see File::IsIOPerThread() for multi-threaded streaming
2012         */
2013        File::Handle File::FileHandle() const {
2014            return FileHandlePair().hRead;
2015        }
2016    
2017        /**
2018         * Returns the OS dependent file I/O write handle intended to be used by the
2019         * calling thread.
2020         *
2021         * @see File::IsIOPerThread() for multi-threaded streaming
2022         */
2023        File::Handle File::FileWriteHandle() const {
2024            return FileHandlePair().hWrite;
2025        }
2026    
2027        /**
2028         * Returns the file I/O mode currently being available for the calling
2029         * thread for this RIFF file (either ro, rw or closed).
2030         *
2031         * @see File::IsIOPerThread() for multi-threaded streaming
2032         */
2033        stream_mode_t File::GetMode() const {
2034            return FileHandlePair().Mode;
2035        }
2036    
2037      stream_mode_t File::GetMode() {      layout_t File::GetLayout() const {
2038          return Mode;          return Layout;
2039      }      }
2040    
2041      /** @brief Change file access mode.      /** @brief Change file access mode.
# Line 1451  namespace RIFF { Line 2046  namespace RIFF {
2046       * @param NewMode - new file access mode       * @param NewMode - new file access mode
2047       * @returns true if mode was changed, false if current mode already       * @returns true if mode was changed, false if current mode already
2048       *          equals new mode       *          equals new mode
2049       * @throws RIFF::Exception if new file access mode is unknown       * @throws RIFF::Exception if file could not be opened in requested file
2050         *         access mode or if passed access mode is unknown
2051         * @see File::IsIOPerThread() for multi-threaded streaming
2052       */       */
2053      bool File::SetMode(stream_mode_t NewMode) {      bool File::SetMode(stream_mode_t NewMode) {
2054          if (NewMode != Mode) {          bool bResetPos = false;
2055            bool res = SetModeInternal(NewMode, &bResetPos);
2056            // resetting position must be handled outside above's call to avoid any
2057            // potential dead lock, as SetModeInternal() acquires a lock and
2058            // __resetPos() acquires a lock by itself (not a theoretical issue!)
2059            if (bResetPos)
2060                __resetPos(); // reset read/write position of ALL 'Chunk' objects
2061            return res;
2062        }
2063    
2064        bool File::SetModeInternal(stream_mode_t NewMode, bool* pResetPos) {
2065            std::lock_guard<std::mutex> lock(io.mutex);
2066            HandlePair& io = FileHandlePairUnsafeRef();
2067            if (NewMode != io.Mode) {
2068              switch (NewMode) {              switch (NewMode) {
2069                  case stream_mode_read:                  case stream_mode_read:
2070                        if (_isValidHandle(io.hRead)) _close(io.hRead);
2071                      #if POSIX                      #if POSIX
2072                      if (hFileRead) close(hFileRead);                      io.hRead = io.hWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
2073                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                      if (io.hRead == -1) {
2074                      if (hFileRead < 0) {                          io.hRead = io.hWrite = 0;
2075                          hFileRead = hFileWrite = 0;                          String sError = strerror(errno);
2076                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
2077                      }                      }
2078                      #elif defined(WIN32)                      #elif defined(WIN32)
2079                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      io.hRead = io.hWrite = CreateFile(
                     hFileRead = hFileWrite = CreateFile(  
2080                                                   Filename.c_str(), GENERIC_READ,                                                   Filename.c_str(), GENERIC_READ,
2081                                                   FILE_SHARE_READ | FILE_SHARE_WRITE,                                                   FILE_SHARE_READ | FILE_SHARE_WRITE,
2082                                                   NULL, OPEN_EXISTING,                                                   NULL, OPEN_EXISTING,
# Line 1474  namespace RIFF { Line 2084  namespace RIFF {
2084                                                   FILE_FLAG_RANDOM_ACCESS,                                                   FILE_FLAG_RANDOM_ACCESS,
2085                                                   NULL                                                   NULL
2086                                               );                                               );
2087                      if (hFileRead == INVALID_HANDLE_VALUE) {                      if (io.hRead == INVALID_HANDLE_VALUE) {
2088                          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;                          io.hRead = io.hWrite = INVALID_HANDLE_VALUE;
2089                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
2090                      }                      }
2091                      #else                      #else
2092                      if (hFileRead) fclose(hFileRead);                      io.hRead = io.hWrite = fopen(Filename.c_str(), "rb");
2093                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");                      if (!io.hRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
                     if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");  
2094                      #endif                      #endif
2095                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      *pResetPos = true;
2096                      break;                      break;
2097                  case stream_mode_read_write:                  case stream_mode_read_write:
2098                        if (_isValidHandle(io.hRead)) _close(io.hRead);
2099                      #if POSIX                      #if POSIX
2100                      if (hFileRead) close(hFileRead);                      io.hRead = io.hWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
2101                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);                      if (io.hRead == -1) {
2102                      if (hFileRead < 0) {                          io.hRead = io.hWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
2103                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          String sError = strerror(errno);
2104                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
2105                      }                      }
2106                      #elif defined(WIN32)                      #elif defined(WIN32)
2107                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      io.hRead = io.hWrite = CreateFile(
                     hFileRead = hFileWrite = CreateFile(  
2108                                                   Filename.c_str(),                                                   Filename.c_str(),
2109                                                   GENERIC_READ | GENERIC_WRITE,                                                   GENERIC_READ | GENERIC_WRITE,
2110                                                   FILE_SHARE_READ,                                                   FILE_SHARE_READ,
# Line 1504  namespace RIFF { Line 2113  namespace RIFF {
2113                                                   FILE_FLAG_RANDOM_ACCESS,                                                   FILE_FLAG_RANDOM_ACCESS,
2114                                                   NULL                                                   NULL
2115                                               );                                               );
2116                      if (hFileRead == INVALID_HANDLE_VALUE) {                      if (io.hRead == INVALID_HANDLE_VALUE) {
2117                          hFileRead = hFileWrite = CreateFile(                          io.hRead = io.hWrite = CreateFile(
2118                                                       Filename.c_str(), GENERIC_READ,                                                       Filename.c_str(), GENERIC_READ,
2119                                                       FILE_SHARE_READ | FILE_SHARE_WRITE,                                                       FILE_SHARE_READ | FILE_SHARE_WRITE,
2120                                                       NULL, OPEN_EXISTING,                                                       NULL, OPEN_EXISTING,
# Line 1516  namespace RIFF { Line 2125  namespace RIFF {
2125                          throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
2126                      }                      }
2127                      #else                      #else
2128                      if (hFileRead) fclose(hFileRead);                      io.hRead = io.hWrite = fopen(Filename.c_str(), "r+b");
2129                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");                      if (!io.hRead) {
2130                      if (!hFileRead) {                          io.hRead = io.hWrite = fopen(Filename.c_str(), "rb");
                         hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");  
2131                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
2132                      }                      }
2133                      #endif                      #endif
2134                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      *pResetPos = true;
2135                      break;                      break;
2136                  case stream_mode_closed:                  case stream_mode_closed:
2137                        if (_isValidHandle(io.hRead)) _close(io.hRead);
2138                        if (_isValidHandle(io.hWrite)) _close(io.hWrite);
2139                      #if POSIX                      #if POSIX
2140                      if (hFileRead)  close(hFileRead);                      io.hRead = io.hWrite = 0;
                     if (hFileWrite) close(hFileWrite);  
2141                      #elif defined(WIN32)                      #elif defined(WIN32)
2142                      if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      io.hRead = io.hWrite = INVALID_HANDLE_VALUE;
                     if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);  
2143                      #else                      #else
2144                      if (hFileRead)  fclose(hFileRead);                      io.hRead = io.hWrite = NULL;
                     if (hFileWrite) fclose(hFileWrite);  
2145                      #endif                      #endif
                     hFileRead = hFileWrite = 0;  
2146                      break;                      break;
2147                  default:                  default:
2148                      throw Exception("Unknown file access mode");                      throw Exception("Unknown file access mode");
2149              }              }
2150              Mode = NewMode;              io.Mode = NewMode;
2151              return true;              return true;
2152          }          }
2153          return false;          return false;
# Line 1567  namespace RIFF { Line 2173  namespace RIFF {
2173      /** @brief Save changes to same file.      /** @brief Save changes to same file.
2174       *       *
2175       * Make all changes of all chunks persistent by writing them to the       * Make all changes of all chunks persistent by writing them to the
2176       * 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.  
2177       *       *
2178         * @param pProgress - optional: callback function for progress notification
2179       * @throws RIFF::Exception if there is an empty chunk or empty list       * @throws RIFF::Exception if there is an empty chunk or empty list
2180       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occurred
2181         * @see File::IsIOPerThread() for multi-threaded streaming
2182       */       */
2183      void File::Save() {      void File::Save(progress_t* pProgress) {
2184            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
2185            if (Layout == layout_flat)
2186                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
2187    
2188          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
2189          LoadSubChunksRecursively();          if (pProgress) {
2190                // divide progress into subprogress
2191                progress_t subprogress;
2192                __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
2193                // do the actual work
2194                LoadSubChunksRecursively(&subprogress);
2195                // notify subprogress done
2196                __notify_progress(&subprogress, 1.f);
2197            } else
2198                LoadSubChunksRecursively(NULL);
2199    
2200          // reopen file in write mode          // reopen file in write mode
2201          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
2202    
2203            // get the current file size as it is now still physically stored on disk
2204            const file_offset_t workingFileSize = GetCurrentFileSize();
2205    
2206            // get the overall file size required to save this file
2207            const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
2208    
2209            // determine whether this file will yield in a large file (>=4GB) and
2210            // the RIFF file offset size to be used accordingly for all chunks
2211            FileOffsetSize = FileOffsetSizeFor(newFileSize);
2212    
2213            const HandlePair io = FileHandlePair();
2214            const Handle hRead  = io.hRead;
2215            const Handle hWrite = io.hWrite;
2216    
2217          // to be able to save the whole file without loading everything into          // to be able to save the whole file without loading everything into
2218          // 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
2219          // enlarge the file with the sum of all _positive_ chunk size          // enlarge the file with the overall positive file size change,
2220          // 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
2221          // calculated sum and finally update / rewrite the file by copying          // positive file size difference and finally update / rewrite the file
2222          // 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
2223            // 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 ulDiff = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2 - (*iter)->GetSize() - (*iter)->GetSize() % 2;  
             if (ulDiff > 0) ulPositiveSizeDiff += ulDiff;  
         }  
   
         unsigned long ulWorkingFileSize = GetFileSize();  
2224    
2225          // if there are positive size changes...          // if there are positive size changes...
2226          if (ulPositiveSizeDiff > 0) {          file_offset_t positiveSizeDiff = 0;
2227            if (newFileSize > workingFileSize) {
2228                positiveSizeDiff = newFileSize - workingFileSize;
2229    
2230                // divide progress into subprogress
2231                progress_t subprogress;
2232                if (pProgress)
2233                    __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
2234    
2235              // ... we enlarge this file first ...              // ... we enlarge this file first ...
2236              ulWorkingFileSize += ulPositiveSizeDiff;              ResizeFile(newFileSize);
2237              ResizeFile(ulWorkingFileSize);  
2238              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
2239              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
             const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;  
2240              #if defined(WIN32)              #if defined(WIN32)
2241              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
2242              #else              #else
2243              int iBytesMoved = 1;              ssize_t iBytesMoved = 1;
2244              #endif              #endif
2245              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {              for (file_offset_t ullPos = workingFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
2246                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;                  iBytesMoved = (ullPos < 4096) ? ullPos : 4096;
2247                  ulPos -= iBytesMoved;                  ullPos -= iBytesMoved;
2248                  #if POSIX                  #if POSIX
2249                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hRead, ullPos, SEEK_SET);
2250                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hRead, pCopyBuffer, iBytesMoved);
2251                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hWrite, ullPos + positiveSizeDiff, SEEK_SET);
2252                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hWrite, pCopyBuffer, iBytesMoved);
2253                  #elif defined(WIN32)                  #elif defined(WIN32)
2254                  SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);                  LARGE_INTEGER liFilePos;
2255                  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  liFilePos.QuadPart = ullPos;
2256                  SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);                  SetFilePointerEx(hRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
2257                  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);                  ReadFile(hRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
2258                    liFilePos.QuadPart = ullPos + positiveSizeDiff;
2259                    SetFilePointerEx(hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
2260                    WriteFile(hWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
2261                  #else                  #else
2262                  fseek(hFileRead, ulPos, SEEK_SET);                  fseeko(hRead, ullPos, SEEK_SET);
2263                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hRead);
2264                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  fseeko(hWrite, ullPos + positiveSizeDiff, SEEK_SET);
2265                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hWrite);
2266                  #endif                  #endif
2267                    if (pProgress && !(iNotif % 8) && iBytesMoved > 0)
2268                        __notify_progress(&subprogress, float(workingFileSize - ullPos) / float(workingFileSize));
2269              }              }
2270              delete[] pCopyBuffer;              delete[] pCopyBuffer;
2271              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");
2272    
2273                if (pProgress)
2274                    __notify_progress(&subprogress, 1.f); // notify subprogress done
2275          }          }
2276    
2277          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree ...
2278          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);  
2279          unsigned long ulActualSize = __GetFileSize(hFileWrite);          // divide progress into subprogress
2280            progress_t subprogress;
2281            if (pProgress)
2282                __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
2283            // do the actual work
2284            const file_offset_t finalSize = WriteChunk(0, positiveSizeDiff, pProgress ? &subprogress : NULL);
2285            const file_offset_t finalActualSize = __GetFileSize(hWrite);
2286            // notify subprogress done
2287            if (pProgress)
2288                __notify_progress(&subprogress, 1.f);
2289    
2290          // resize file to the final size          // resize file to the final size
2291          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (finalSize < finalActualSize) ResizeFile(finalSize);
2292    
2293          // forget all resized chunks          if (pProgress)
2294          ResizedChunks.clear();              __notify_progress(pProgress, 1.0); // notify done
2295      }      }
2296    
2297      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1660  namespace RIFF { Line 2306  namespace RIFF {
2306       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
2307       *       *
2308       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
2309         * @param pProgress - optional: callback function for progress notification
2310         * @see File::IsIOPerThread() for multi-threaded streaming
2311       */       */
2312      void File::Save(const String& path) {      void File::Save(const String& path, progress_t* pProgress) {
2313          //TODO: we should make a check here if somebody tries to write to the same file and automatically call the other Save() method in that case          //TODO: we should make a check here if somebody tries to write to the same file and automatically call the other Save() method in that case
2314    
2315            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
2316            if (Layout == layout_flat)
2317                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
2318    
2319          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
2320          LoadSubChunksRecursively();          if (pProgress) {
2321                // divide progress into subprogress
2322                progress_t subprogress;
2323                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
2324                // do the actual work
2325                LoadSubChunksRecursively(&subprogress);
2326                // notify subprogress done
2327                __notify_progress(&subprogress, 1.f);
2328            } else
2329                LoadSubChunksRecursively(NULL);
2330    
2331            if (!bIsNewFile) SetMode(stream_mode_read);
2332    
2333            {
2334                std::lock_guard<std::mutex> lock(io.mutex);
2335                HandlePair& io = FileHandlePairUnsafeRef();
2336    
2337          if (Filename.length() > 0) SetMode(stream_mode_read);              // open the other (new) file for writing and truncate it to zero size
2338          // open the other (new) file for writing and truncate it to zero size              #if POSIX
2339          #if POSIX              io.hWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
2340          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);              if (io.hWrite == -1) {
2341          if (hFileWrite < 0) {                  io.hWrite = io.hRead;
2342              hFileWrite = hFileRead;                  String sError = strerror(errno);
2343              throw Exception("Could not open file \"" + path + "\" for writing");                  throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
2344          }              }
2345          #elif defined(WIN32)              #elif defined(WIN32)
2346          hFileWrite = CreateFile(              io.hWrite = CreateFile(
2347                           path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,                  path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
2348                           NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |                  NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
2349                           FILE_FLAG_RANDOM_ACCESS, NULL                  FILE_FLAG_RANDOM_ACCESS, NULL
2350                       );              );
2351          if (hFileWrite == INVALID_HANDLE_VALUE) {              if (io.hWrite == INVALID_HANDLE_VALUE) {
2352              hFileWrite = hFileRead;                  io.hWrite = io.hRead;
2353              throw Exception("Could not open file \"" + path + "\" for writing");                  throw Exception("Could not open file \"" + path + "\" for writing");
2354          }              }
2355          #else              #else
2356          hFileWrite = fopen(path.c_str(), "w+b");              io.hWrite = fopen(path.c_str(), "w+b");
2357          if (!hFileWrite) {              if (!io.hWrite) {
2358              hFileWrite = hFileRead;                  io.hWrite = io.hRead;
2359              throw Exception("Could not open file \"" + path + "\" for writing");                  throw Exception("Could not open file \"" + path + "\" for writing");
2360                }
2361                #endif // POSIX
2362                io.Mode = stream_mode_read_write;
2363          }          }
         #endif // POSIX  
         Mode = stream_mode_read_write;  
2364    
2365          // write complete RIFF tree to the other (new) file          // get the overall file size required to save this file
2366          unsigned long ulTotalSize  = WriteChunk(0, 0);          const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
         unsigned long ulActualSize = __GetFileSize(hFileWrite);  
2367    
2368          // resize file to the final size (if the file was originally larger)          // determine whether this file will yield in a large file (>=4GB) and
2369          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          // the RIFF file offset size to be used accordingly for all chunks
2370            FileOffsetSize = FileOffsetSizeFor(newFileSize);
2371    
2372          // forget all resized chunks          // write complete RIFF tree to the other (new) file
2373          ResizedChunks.clear();          file_offset_t ullTotalSize;
2374            if (pProgress) {
2375                // divide progress into subprogress
2376                progress_t subprogress;
2377                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
2378                // do the actual work
2379                ullTotalSize = WriteChunk(0, 0, &subprogress);
2380                // notify subprogress done
2381                __notify_progress(&subprogress, 1.f);
2382            } else
2383                ullTotalSize = WriteChunk(0, 0, NULL);
2384    
2385          #if POSIX          const file_offset_t ullActualSize = __GetFileSize(FileWriteHandle());
         if (hFileWrite) close(hFileWrite);  
         #elif defined(WIN32)  
         if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);  
         #else  
         if (hFileWrite) fclose(hFileWrite);  
         #endif  
         hFileWrite = hFileRead;  
2386    
2387          // associate new file with this File object from now on          // resize file to the final size (if the file was originally larger)
2388          Filename = path;          if (ullActualSize > ullTotalSize) ResizeFile(ullTotalSize);
2389          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...  
2390            {
2391                std::lock_guard<std::mutex> lock(io.mutex);
2392                HandlePair& io = FileHandlePairUnsafeRef();
2393    
2394                if (_isValidHandle(io.hWrite)) _close(io.hWrite);
2395                io.hWrite = io.hRead;
2396    
2397                // associate new file with this File object from now on
2398                Filename = path;
2399                bIsNewFile = false;
2400                io.Mode = (stream_mode_t) -1; // Just set it to an undefined mode ...
2401            }
2402          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
2403    
2404            if (pProgress)
2405                __notify_progress(pProgress, 1.0); // notify done
2406      }      }
2407    
2408      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(file_offset_t ullNewSize) {
2409            const Handle hWrite = FileWriteHandle();
2410          #if POSIX          #if POSIX
2411          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hWrite, ullNewSize) < 0)
2412              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
2413          #elif defined(WIN32)          #elif defined(WIN32)
2414            LARGE_INTEGER liFilePos;
2415            liFilePos.QuadPart = ullNewSize;
2416          if (          if (
2417              SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||              !SetFilePointerEx(hWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN) ||
2418              !SetEndOfFile(hFileWrite)              !SetEndOfFile(hWrite)
2419          ) throw Exception("Could not resize file \"" + Filename + "\"");          ) throw Exception("Could not resize file \"" + Filename + "\"");
2420          #else          #else
2421          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
# Line 1735  namespace RIFF { Line 2424  namespace RIFF {
2424      }      }
2425    
2426      File::~File() {      File::~File() {
2427         #if DEBUG          #if DEBUG_RIFF
2428         std::cout << "File::~File()" << std::endl;          std::cout << "File::~File()" << std::endl;
2429         #endif // DEBUG          #endif // DEBUG_RIFF
2430          #if POSIX          Cleanup();
2431          if (hFileRead) close(hFileRead);      }
2432          #elif defined(WIN32)  
2433          if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);      /**
2434          #else       * Returns @c true if this file has been created new from scratch and
2435          if (hFileRead) fclose(hFileRead);       * has not been stored to disk yet.
2436          #endif // POSIX       */
2437        bool File::IsNew() const {
2438            return bIsNewFile;
2439      }      }
2440    
2441      void File::LogAsResized(Chunk* pResizedChunk) {      void File::Cleanup() {
2442          ResizedChunks.insert(pResizedChunk);          if (IsIOPerThread()) {
2443                for (auto it = io.byThread.begin(); it != io.byThread.end(); ++it) {
2444                    _close(it->second.hRead);
2445                }
2446            } else {
2447                _close(io.hRead);
2448            }
2449            DeleteChunkList();
2450            pFile = NULL;
2451      }      }
2452    
2453      void File::UnlogResized(Chunk* pResizedChunk) {      /**
2454          ResizedChunks.erase(pResizedChunk);       * Returns the current size of this file (in bytes) as it is currently
2455         * yet stored on disk. If this file does not yet exist on disk (i.e. when
2456         * this RIFF File has just been created from scratch and Save() has not
2457         * been called yet) then this method returns 0.
2458         */
2459        file_offset_t File::GetCurrentFileSize() const {
2460            file_offset_t size = 0;
2461            const Handle hRead = FileHandle();
2462            try {
2463                size = __GetFileSize(hRead);
2464            } catch (...) {
2465                size = 0;
2466            }
2467            return size;
2468      }      }
2469    
2470      unsigned long File::GetFileSize() {      /**
2471          return __GetFileSize(hFileRead);       * Returns the required size (in bytes) for this RIFF File to be saved to
2472         * disk. The precise size of the final file on disk depends on the RIFF
2473         * file offset size actually used internally in all headers of the RIFF
2474         * chunks. By default libgig handles the required file offset size
2475         * automatically for you; that means it is using 32 bit offsets for files
2476         * smaller than 4 GB and 64 bit offsets for files equal or larger than
2477         * 4 GB. You may however also override this default behavior by passing the
2478         * respective option to the RIFF File constructor to force one particular
2479         * offset size. In the latter case this method will return the file size
2480         * for the requested forced file offset size that will be used when calling
2481         * Save() later on.
2482         *
2483         * You may also use the overridden method below to get the file size for
2484         * an arbitrary other file offset size instead.
2485         *
2486         * @see offset_size_t
2487         * @see GetFileOffsetSize()
2488         */
2489        file_offset_t File::GetRequiredFileSize() {
2490            return GetRequiredFileSize(FileOffsetPreference);
2491        }
2492    
2493        /**
2494         * Returns the rquired size (in bytes) for this RIFF file to be saved to
2495         * disk, assuming the passed @a fileOffsestSize would be used for the
2496         * Save() operation.
2497         *
2498         * This overridden method essentialy behaves like the above method, with
2499         * the difference that you must provide a specific RIFF @a fileOffsetSize
2500         * for calculating the theoretical final file size.
2501         *
2502         * @see GetFileOffsetSize()
2503         */
2504        file_offset_t File::GetRequiredFileSize(offset_size_t fileOffsetSize) {
2505            switch (fileOffsetSize) {
2506                case offset_size_auto: {
2507                    file_offset_t fileSize = GetRequiredFileSize(offset_size_32bit);
2508                    if (fileSize >> 32)
2509                        return GetRequiredFileSize(offset_size_64bit);
2510                    else
2511                        return fileSize;
2512                }
2513                case offset_size_32bit: break;
2514                case offset_size_64bit: break;
2515                default: throw Exception("Internal error: Invalid RIFF::offset_size_t");
2516            }
2517            return RequiredPhysicalSize(FileOffsetSize);
2518        }
2519    
2520        int File::FileOffsetSizeFor(file_offset_t fileSize) const {
2521            switch (FileOffsetPreference) {
2522                case offset_size_auto:
2523                    return (fileSize >> 32) ? 8 : 4;
2524                case offset_size_32bit:
2525                    return 4;
2526                case offset_size_64bit:
2527                    return 8;
2528                default:
2529                    throw Exception("Internal error: Invalid RIFF::offset_size_t");
2530            }
2531        }
2532    
2533        /**
2534         * Returns the current size (in bytes) of file offsets stored in the
2535         * headers of all chunks of this file.
2536         *
2537         * Most RIFF files are using 32 bit file offsets internally, which limits
2538         * them to a maximum file size of less than 4 GB though. In contrast to the
2539         * common standard, this RIFF File class implementation supports handling of
2540         * RIFF files equal or larger than 4 GB. In such cases 64 bit file offsets
2541         * have to be used in all headers of all RIFF Chunks when being stored to a
2542         * physical file. libgig by default automatically selects the correct file
2543         * offset size for you. You may however also force one particular file
2544         * offset size by supplying the respective option to the RIFF::File
2545         * constructor.
2546         *
2547         * This method can be used to check which RIFF file offset size is currently
2548         * being used for this RIFF File.
2549         *
2550         * @returns current RIFF file offset size used (in bytes)
2551         * @see offset_size_t
2552         */
2553        int File::GetFileOffsetSize() const {
2554            return FileOffsetSize;
2555        }
2556    
2557        /**
2558         * Returns the required size (in bytes) of file offsets stored in the
2559         * headers of all chunks of this file if the current RIFF tree would be
2560         * saved to disk by calling Save().
2561         *
2562         * See GetFileOffsetSize() for mor details about RIFF file offsets.
2563         *
2564         * @returns RIFF file offset size required (in bytes) if being saved
2565         * @see offset_size_t
2566         */
2567        int File::GetRequiredFileOffsetSize() {
2568            return FileOffsetSizeFor(GetCurrentFileSize());
2569        }
2570    
2571        /** @brief Whether file streams are independent for each thread.
2572         *
2573         * All file I/O operations like reading from a RIFF chunk body (e.g. by
2574         * calling Chunk::Read(), Chunk::ReadInt8()), writing to a RIFF chunk body
2575         * (e.g. by calling Chunk::Write(), Chunk::WriteInt8()) or saving the
2576         * current RIFF tree structure to some file (e.g. by calling Save())
2577         * operate on a file I/O stream state, i.e. there is a "current" file
2578         * read/write position and reading/writing by a certain amount of bytes
2579         * automatically advances that "current" file position.
2580         *
2581         * By default there is only one stream state for a RIFF::File object, which
2582         * is not an issue as long as only one thread is using the RIFF::File
2583         * object at a time (which might also be the case in a collaborative /
2584         * coroutine multi-threaded scenario).
2585         *
2586         * If however a RIFF::File object is read/written @b simultaniously by
2587         * multiple threads this can lead to undefined behaviour as the individual
2588         * threads would concurrently alter the file stream position. For such a
2589         * concurrent multithreaded file I/O scenario @c SetIOPerThread(true) might
2590         * be enabled which causes each thread to automatically use its own file
2591         * stream state.
2592         *
2593         * @returns true if each thread has its own file stream state
2594         *          (default: false)
2595         * @see SetIOPerThread()
2596         */
2597        bool File::IsIOPerThread() const {
2598            //NOTE: Not caring about atomicity here at all, for three reasons:
2599            // 1. SetIOPerThread() is assumed to be called only once for the entire
2600            //    life time of a RIFF::File, usually very early at its lifetime, and
2601            //    hence a change to isPerThread should already safely be propagated
2602            //    before any other thread would actually read this boolean flag.
2603            // 2. This method is called very frequently, and therefore any
2604            //    synchronization techique would hurt runtime efficiency.
2605            // 3. Using even a mutex lock here might easily cause a deadlock due to
2606            //    other locks been taken in this .cpp file, i.e. at a higher call
2607            //    stack level (and this is the main reason why I removed it here).
2608            return io.isPerThread;
2609        }
2610    
2611        /** @brief Enable/disable file streams being independent for each thread.
2612         *
2613         * By enabling this feature (default off) each thread will automatically use
2614         * its own file I/O stream state for allowing simultanious multi-threaded
2615         * file read/write operations.
2616         *
2617         * @b NOTE: After having enabled this feature, the individual threads must
2618         * at least once check GetState() and if their file I/O stream is yet closed
2619         * they must call SetMode() (i.e. once) respectively to open their own file
2620         * handles before being able to use any of the Read() or Write() methods.
2621         *
2622         * @param enable - @c true: one independent stream state per thread,
2623         *                 @c false: only one stream in total shared by @b all threads
2624         * @see IsIOPerThread() for more details about this feature
2625         */
2626        void File::SetIOPerThread(bool enable) {
2627            std::lock_guard<std::mutex> lock(io.mutex);
2628            if (!io.byThread.empty() == enable) return;
2629            io.isPerThread = enable;
2630            if (enable) {
2631                const std::thread::id tid = std::this_thread::get_id();
2632                io.byThread[tid] = io;
2633            } else {
2634                // retain an arbitrary handle pair, close all other handle pairs
2635                for (auto it = io.byThread.begin(); it != io.byThread.end(); ++it) {
2636                    if (it == io.byThread.begin()) {
2637                        io.hRead  = it->second.hRead;
2638                        io.hWrite = it->second.hWrite;
2639                    } else {
2640                        _close(it->second.hRead);
2641                        _close(it->second.hWrite);
2642                    }
2643                }
2644                io.byThread.clear();
2645            }
2646      }      }
2647    
2648      #if POSIX      #if POSIX
2649      unsigned long File::__GetFileSize(int hFile) {      file_offset_t File::__GetFileSize(int hFile) const {
2650          struct stat filestat;          struct stat filestat;
2651          fstat(hFile, &filestat);          if (fstat(hFile, &filestat) == -1)
2652          long size = filestat.st_size;              throw Exception("POSIX FS error: could not determine file size");
2653          return size;          return filestat.st_size;
2654      }      }
2655      #elif defined(WIN32)      #elif defined(WIN32)
2656      unsigned long File::__GetFileSize(HANDLE hFile) {      file_offset_t File::__GetFileSize(HANDLE hFile) const {
2657          DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);          LARGE_INTEGER size;
2658          if (dwSize == INVALID_FILE_SIZE)          if (!GetFileSizeEx(hFile, &size))
2659              throw Exception("Windows FS error: could not determine file size");              throw Exception("Windows FS error: could not determine file size");
2660          return dwSize;          return size.QuadPart;
2661      }      }
2662      #else // standard C functions      #else // standard C functions
2663      unsigned long File::__GetFileSize(FILE* hFile) {      file_offset_t File::__GetFileSize(FILE* hFile) const {
2664          long curpos = ftell(hFile);          off_t curpos = ftello(hFile);
2665          fseek(hFile, 0, SEEK_END);          if (fseeko(hFile, 0, SEEK_END) == -1)
2666          long size = ftell(hFile);              throw Exception("FS error: could not determine file size");
2667          fseek(hFile, curpos, SEEK_SET);          off_t size = ftello(hFile);
2668            fseeko(hFile, curpos, SEEK_SET);
2669          return size;          return size;
2670      }      }
2671      #endif      #endif
# Line 1787  namespace RIFF { Line 2674  namespace RIFF {
2674  // *************** Exception ***************  // *************** Exception ***************
2675  // *  // *
2676    
2677        Exception::Exception() {
2678        }
2679    
2680        Exception::Exception(String format, ...) {
2681            va_list arg;
2682            va_start(arg, format);
2683            Message = assemble(format, arg);
2684            va_end(arg);
2685        }
2686    
2687        Exception::Exception(String format, va_list arg) {
2688            Message = assemble(format, arg);
2689        }
2690    
2691      void Exception::PrintMessage() {      void Exception::PrintMessage() {
2692          std::cout << "RIFF::Exception: " << Message << std::endl;          std::cout << "RIFF::Exception: " << Message << std::endl;
2693      }      }
2694    
2695        String Exception::assemble(String format, va_list arg) {
2696            char* buf = NULL;
2697            vasprintf(&buf, format.c_str(), arg);
2698            String s = buf;
2699            free(buf);
2700            return s;
2701        }
2702    
2703    
2704  // *************** functions ***************  // *************** functions ***************
2705  // *  // *

Legend:
Removed from v.1678  
changed lines
  Added in v.3921

  ViewVC Help
Powered by ViewVC