/[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 24 by schoenebeck, Fri Dec 26 16:15:31 2003 UTC revision 1063 by schoenebeck, Sat Mar 3 21:45:25 2007 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003 by Christian Schoenebeck                           *   *   Copyright (C) 2003-2007 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  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 20  Line 20 
20   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston,                 *   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston,                 *
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23  #if 1  
24    #include <string.h>
25    
26  #include "RIFF.h"  #include "RIFF.h"
27    
28    #include "helper.h"
29    
30  namespace RIFF {  namespace RIFF {
31    
32  // *************** Chunk **************  // *************** Chunk **************
33  // *  // *
34    
35      Chunk::Chunk() {      Chunk::Chunk(File* pFile) {
36          #if DEBUG          #if DEBUG
37          std::cout << "Chunk::Chunk()" << std::endl;          std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
38          #endif // DEBUG          #endif // DEBUG
39          ulPos      = 0;          ulPos      = 0;
40          pParent    = NULL;          pParent    = NULL;
41          pChunkData = NULL;          pChunkData = NULL;
42            ulChunkDataSize = 0;
43            ChunkID    = CHUNK_ID_RIFF;
44            this->pFile = pFile;
45      }      }
46    
47      #if POSIX      Chunk::Chunk(File* pFile, unsigned long StartPos, List* Parent) {
     Chunk::Chunk(int hFile, unsigned long StartPos, bool EndianNative, List* Parent) {  
     #else  
     Chunk::Chunk(FILE* hFile, unsigned long StartPos, bool EndianNative, List* Parent) {  
     #endif // POSIX  
48          #if DEBUG          #if DEBUG
49          std::cout << "Chunk::Chunk(FILE,ulong,bool,List*),StartPos=" << StartPos << std::endl;          std::cout << "Chunk::Chunk(File*,ulong,bool,List*),StartPos=" << StartPos << std::endl;
50          #endif // DEBUG          #endif // DEBUG
51          Chunk::hFile  = hFile;          this->pFile   = pFile;
52          ulStartPos    = StartPos + CHUNK_HEADER_SIZE;          ulStartPos    = StartPos + CHUNK_HEADER_SIZE;
         bEndianNative = EndianNative;  
53          pParent       = Parent;          pParent       = Parent;
54          ulPos         = 0;          ulPos         = 0;
55          pChunkData    = NULL;          pChunkData    = NULL;
56            ulChunkDataSize = 0;
57          ReadHeader(StartPos);          ReadHeader(StartPos);
58      }      }
59    
60        Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, uint uiBodySize) {
61            this->pFile      = pFile;
62            ulStartPos       = 0; // arbitrary usually, since it will be updated when we write the chunk
63            this->pParent    = pParent;
64            ulPos            = 0;
65            pChunkData       = NULL;
66            ulChunkDataSize  = 0;
67            ChunkID          = uiChunkID;
68            CurrentChunkSize = 0;
69            NewChunkSize     = uiBodySize;
70        }
71    
72      Chunk::~Chunk() {      Chunk::~Chunk() {
73          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
74      }      }
# Line 63  namespace RIFF { Line 78  namespace RIFF {
78          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << fPos << ") ";
79          #endif // DEBUG          #endif // DEBUG
80          #if POSIX          #if POSIX
81          if (lseek(hFile, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
82              read(hFile, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
83              read(hFile, &ChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
84            #elif defined(WIN32)
85            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
86                DWORD dwBytesRead;
87                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
88                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
89          #else          #else
90          if (!fseek(hFile, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
91              fread(&ChunkID, 4, 1, hFile);              fread(&ChunkID, 4, 1, pFile->hFileRead);
92              fread(&ChunkSize, 4, 1, hFile);              fread(&CurrentChunkSize, 4, 1, pFile->hFileRead);
93          #endif // POSIX          #endif // POSIX
94              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
95              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
96                  bEndianNative = false;                  pFile->bEndianNative = false;
97              }              }
98              #else // little endian              #else // little endian
99              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
100                  bEndianNative = false;                  pFile->bEndianNative = false;
101                  ChunkID = CHUNK_ID_RIFF;                  ChunkID = CHUNK_ID_RIFF;
102              }              }
103              #endif // WORDS_BIGENDIAN              #endif // WORDS_BIGENDIAN
104              if (!bEndianNative) {              if (!pFile->bEndianNative) {
105                  //swapBytes_32(&ChunkID);                  //swapBytes_32(&ChunkID);
106                  swapBytes_32(&ChunkSize);                  swapBytes_32(&CurrentChunkSize);
107              }              }
108              #if DEBUG              #if DEBUG
109              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
110              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << ChunkSize << " ";
111              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << bEndianNative << std::endl;
112              #endif // DEBUG              #endif // DEBUG
113                NewChunkSize = CurrentChunkSize;
114          }          }
115      }      }
116    
117        void Chunk::WriteHeader(unsigned long fPos) {
118            uint32_t uiNewChunkID = ChunkID;
119            if (ChunkID == CHUNK_ID_RIFF) {
120                #if WORDS_BIGENDIAN
121                if (pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
122                #else // little endian
123                if (!pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
124                #endif // WORDS_BIGENDIAN
125            }
126    
127            uint32_t uiNewChunkSize = NewChunkSize;
128            if (!pFile->bEndianNative) {
129                swapBytes_32(&uiNewChunkSize);
130            }
131    
132            #if POSIX
133            if (lseek(pFile->hFileWrite, fPos, SEEK_SET) != -1) {
134                write(pFile->hFileWrite, &uiNewChunkID, 4);
135                write(pFile->hFileWrite, &uiNewChunkSize, 4);
136            }
137            #elif defined(WIN32)
138            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
139                DWORD dwBytesWritten;
140                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
141                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
142            }
143            #else
144            if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
145                fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
146                fwrite(&uiNewChunkSize, 4, 1, pFile->hFileWrite);
147            }
148            #endif // POSIX
149        }
150    
151      /**      /**
152       *  Returns the String representation of the chunk's ID (e.g. "RIFF",       *  Returns the String representation of the chunk's ID (e.g. "RIFF",
153       *  "LIST").       *  "LIST").
# Line 105  namespace RIFF { Line 160  namespace RIFF {
160       *  Sets the position within the chunk body, thus within the data portion       *  Sets the position within the chunk body, thus within the data portion
161       *  of the chunk (in bytes).       *  of the chunk (in bytes).
162       *       *
163         *  <b>Caution:</b> the position will be reset to zero whenever
164         *  File::Save() was called.
165         *
166       *  @param Where  - position offset (in bytes)       *  @param Where  - position offset (in bytes)
167       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,       *  @param Whence - optional: defines to what <i>\a Where</i> relates to,
168       *                  if omitted \a Where relates to beginning of the chunk       *                  if omitted \a Where relates to beginning of the chunk
# Line 119  namespace RIFF { Line 177  namespace RIFF {
177                  ulPos += Where;                  ulPos += Where;
178                  break;                  break;
179              case stream_end:              case stream_end:
180                  ulPos = ChunkSize - 1 - Where;                  ulPos = CurrentChunkSize - 1 - Where;
181                  break;                  break;
182              case stream_backward:              case stream_backward:
183                  ulPos -= Where;                  ulPos -= Where;
# Line 128  namespace RIFF { Line 186  namespace RIFF {
186                  ulPos = Where;                  ulPos = Where;
187                  break;                  break;
188          }          }
189          if (ulPos > ChunkSize) ulPos = ChunkSize;          if (ulPos > CurrentChunkSize) ulPos = CurrentChunkSize;
190          return ulPos;          return ulPos;
191      }      }
192    
# Line 144  namespace RIFF { Line 202  namespace RIFF {
202       */       */
203      unsigned long Chunk::RemainingBytes() {      unsigned long Chunk::RemainingBytes() {
204         #if DEBUG         #if DEBUG
205         std::cout << "Chunk::Remainingbytes()=" << ChunkSize - ulPos << std::endl;         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;
206         #endif // DEBUG         #endif // DEBUG
207          return ChunkSize - ulPos;          return CurrentChunkSize - ulPos;
208      }      }
209    
210      /**      /**
# Line 165  namespace RIFF { Line 223  namespace RIFF {
223        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
224        #endif // DEBUG        #endif // DEBUG
225          #if POSIX          #if POSIX
226          if (hFile == 0)        return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
227            #elif defined (WIN32)
228            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
229                return stream_closed;
230          #else          #else
231          if (hFile == NULL)     return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
232          #endif // POSIX          #endif // POSIX
233          if (ulPos < ChunkSize) return stream_ready;          if (ulPos < CurrentChunkSize) return stream_ready;
234          else                   return stream_end_reached;          else                          return stream_end_reached;
235      }      }
236    
237      /**      /**
# Line 192  namespace RIFF { Line 253  namespace RIFF {
253         #if DEBUG         #if DEBUG
254         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
255         #endif // DEBUG         #endif // DEBUG
256          if (ulPos >= ChunkSize) return 0;          if (ulPos >= CurrentChunkSize) return 0;
257          if (ulPos + WordCount * WordSize >= ChunkSize) WordCount = (ChunkSize - ulPos) / WordSize;          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
258          #if POSIX          #if POSIX
259          if (lseek(hFile, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;
260          unsigned long readWords = read(hFile, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
261            if (readWords < 1) return 0;
262            readWords /= WordSize;
263            #elif defined(WIN32)
264            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
265            DWORD readWords;
266            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
267          if (readWords < 1) return 0;          if (readWords < 1) return 0;
268          readWords /= WordSize;          readWords /= WordSize;
269          #else // standard C functions          #else // standard C functions
270          if (fseek(hFile, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
271          unsigned long readWords = fread(pData, WordSize, WordCount, hFile);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
272          #endif // POSIX          #endif // POSIX
273          if (!bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
274              switch (WordSize) {              switch (WordSize) {
275                  case 2:                  case 2:
276                      for (unsigned long iWord = 0; iWord < readWords; iWord++)                      for (unsigned long iWord = 0; iWord < readWords; iWord++)
# Line 223  namespace RIFF { Line 290  namespace RIFF {
290          return readWords;          return readWords;
291      }      }
292    
293        /**
294         *  Writes \a WordCount number of data words with given \a WordSize from
295         *  the buffer pointed by \a pData. Be sure to provide the correct
296         *  \a WordSize, as this will be important and taken into account for
297         *  eventual endian correction (swapping of bytes due to different
298         *  native byte order of a system). The position within the chunk will
299         *  automatically be incremented.
300         *
301         *  @param pData      source buffer (containing the data)
302         *  @param WordCount  number of data words to write
303         *  @param WordSize   size of each data word to write
304         *  @returns          number of successfully written data words
305         *  @throws RIFF::Exception  if write operation would exceed current
306         *                           chunk size or any IO error occured
307         *  @see Resize()
308         */
309        unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {
310            if (pFile->Mode != stream_mode_read_write)
311                throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
312            if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)
313                throw Exception("End of chunk reached while trying to write data");
314            if (!pFile->bEndianNative && WordSize != 1) {
315                switch (WordSize) {
316                    case 2:
317                        for (unsigned long iWord = 0; iWord < WordCount; iWord++)
318                            swapBytes_16((uint16_t*) pData + iWord);
319                        break;
320                    case 4:
321                        for (unsigned long iWord = 0; iWord < WordCount; iWord++)
322                            swapBytes_32((uint32_t*) pData + iWord);
323                        break;
324                    default:
325                        for (unsigned long iWord = 0; iWord < WordCount; iWord++)
326                            swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
327                        break;
328                }
329            }
330            #if POSIX
331            if (lseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET) < 0) {
332                throw Exception("Could not seek to position " + ToString(ulPos) +
333                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
334            }
335            unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
336            if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
337            writtenWords /= WordSize;
338            #elif defined(WIN32)
339            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
340                throw Exception("Could not seek to position " + ToString(ulPos) +
341                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");            
342            }
343            DWORD writtenWords;
344            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
345            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
346            writtenWords /= WordSize;
347            #else // standard C functions
348            if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
349                throw Exception("Could not seek to position " + ToString(ulPos) +
350                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
351            }
352            unsigned long writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
353            #endif // POSIX
354            SetPos(writtenWords * WordSize, stream_curpos);
355            return writtenWords;
356        }
357    
358      /** 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. */
359      unsigned long Chunk::ReadSceptical(void* pData, unsigned long WordCount, unsigned long WordSize) {      unsigned long Chunk::ReadSceptical(void* pData, unsigned long WordCount, unsigned long WordSize) {
360          unsigned long readWords = Read(pData, WordCount, WordSize);          unsigned long readWords = Read(pData, WordCount, WordSize);
# Line 249  namespace RIFF { Line 381  namespace RIFF {
381      }      }
382    
383      /**      /**
384         * Writes \a WordCount number of 8 Bit signed integer words from the
385         * buffer pointed by \a pData to the chunk's body, directly to the
386         * actual "physical" file. The position within the chunk will
387         * automatically be incremented. Note: you cannot write beyond the
388         * boundaries of the chunk, to append data to the chunk call Resize()
389         * before.
390         *
391         * @param pData             source buffer (containing the data)
392         * @param WordCount         number of 8 Bit signed integers to write
393         * @returns                 number of written integers
394         * @throws RIFF::Exception  if an IO error occured
395         * @see Resize()
396         */
397        unsigned long Chunk::WriteInt8(int8_t* pData, unsigned long WordCount) {
398            return Write(pData, WordCount, 1);
399        }
400    
401        /**
402       * Reads \a WordCount number of 8 Bit unsigned integer words and copies       * Reads \a WordCount number of 8 Bit unsigned integer words and copies
403       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
404       * allocated. The position within the chunk will automatically be       * allocated. The position within the chunk will automatically be
# Line 268  namespace RIFF { Line 418  namespace RIFF {
418      }      }
419    
420      /**      /**
421         * Writes \a WordCount number of 8 Bit unsigned integer words from the
422         * buffer pointed by \a pData to the chunk's body, directly to the
423         * actual "physical" file. The position within the chunk will
424         * automatically be incremented. Note: you cannot write beyond the
425         * boundaries of the chunk, to append data to the chunk call Resize()
426         * before.
427         *
428         * @param pData             source buffer (containing the data)
429         * @param WordCount         number of 8 Bit unsigned integers to write
430         * @returns                 number of written integers
431         * @throws RIFF::Exception  if an IO error occured
432         * @see Resize()
433         */
434        unsigned long Chunk::WriteUint8(uint8_t* pData, unsigned long WordCount) {
435            return Write(pData, WordCount, 1);
436        }
437    
438        /**
439       * Reads \a WordCount number of 16 Bit signed integer words and copies       * Reads \a WordCount number of 16 Bit signed integer words and copies
440       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
441       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 287  namespace RIFF { Line 455  namespace RIFF {
455      }      }
456    
457      /**      /**
458         * Writes \a WordCount number of 16 Bit signed integer words from the
459         * buffer pointed by \a pData to the chunk's body, directly to the
460         * actual "physical" file. The position within the chunk will
461         * automatically be incremented. Note: you cannot write beyond the
462         * boundaries of the chunk, to append data to the chunk call Resize()
463         * before.
464         *
465         * @param pData             source buffer (containing the data)
466         * @param WordCount         number of 16 Bit signed integers to write
467         * @returns                 number of written integers
468         * @throws RIFF::Exception  if an IO error occured
469         * @see Resize()
470         */
471        unsigned long Chunk::WriteInt16(int16_t* pData, unsigned long WordCount) {
472            return Write(pData, WordCount, 2);
473        }
474    
475        /**
476       * Reads \a WordCount number of 16 Bit unsigned integer words and copies       * Reads \a WordCount number of 16 Bit unsigned integer words and copies
477       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
478       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 306  namespace RIFF { Line 492  namespace RIFF {
492      }      }
493    
494      /**      /**
495         * Writes \a WordCount number of 16 Bit unsigned integer words from the
496         * buffer pointed by \a pData to the chunk's body, directly to the
497         * actual "physical" file. The position within the chunk will
498         * automatically be incremented. Note: you cannot write beyond the
499         * boundaries of the chunk, to append data to the chunk call Resize()
500         * before.
501         *
502         * @param pData             source buffer (containing the data)
503         * @param WordCount         number of 16 Bit unsigned integers to write
504         * @returns                 number of written integers
505         * @throws RIFF::Exception  if an IO error occured
506         * @see Resize()
507         */
508        unsigned long Chunk::WriteUint16(uint16_t* pData, unsigned long WordCount) {
509            return Write(pData, WordCount, 2);
510        }
511    
512        /**
513       * Reads \a WordCount number of 32 Bit signed integer words and copies       * Reads \a WordCount number of 32 Bit signed integer words and copies
514       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
515       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 325  namespace RIFF { Line 529  namespace RIFF {
529      }      }
530    
531      /**      /**
532         * Writes \a WordCount number of 32 Bit signed integer words from the
533         * buffer pointed by \a pData to the chunk's body, directly to the
534         * actual "physical" file. The position within the chunk will
535         * automatically be incremented. Note: you cannot write beyond the
536         * boundaries of the chunk, to append data to the chunk call Resize()
537         * before.
538         *
539         * @param pData             source buffer (containing the data)
540         * @param WordCount         number of 32 Bit signed integers to write
541         * @returns                 number of written integers
542         * @throws RIFF::Exception  if an IO error occured
543         * @see Resize()
544         */
545        unsigned long Chunk::WriteInt32(int32_t* pData, unsigned long WordCount) {
546            return Write(pData, WordCount, 4);
547        }
548    
549        /**
550       * Reads \a WordCount number of 32 Bit unsigned integer words and copies       * Reads \a WordCount number of 32 Bit unsigned integer words and copies
551       * it into the buffer pointed by \a pData. The buffer has to be       * it into the buffer pointed by \a pData. The buffer has to be
552       * allocated. Endian correction will automatically be done if needed.       * allocated. Endian correction will automatically be done if needed.
# Line 344  namespace RIFF { Line 566  namespace RIFF {
566      }      }
567    
568      /**      /**
569         * Writes \a WordCount number of 32 Bit unsigned integer words from the
570         * buffer pointed by \a pData to the chunk's body, directly to the
571         * actual "physical" file. The position within the chunk will
572         * automatically be incremented. Note: you cannot write beyond the
573         * boundaries of the chunk, to append data to the chunk call Resize()
574         * before.
575         *
576         * @param pData             source buffer (containing the data)
577         * @param WordCount         number of 32 Bit unsigned integers to write
578         * @returns                 number of written integers
579         * @throws RIFF::Exception  if an IO error occured
580         * @see Resize()
581         */
582        unsigned long Chunk::WriteUint32(uint32_t* pData, unsigned long WordCount) {
583            return Write(pData, WordCount, 4);
584        }
585    
586        /**
587       * Reads one 8 Bit signed integer word and increments the position within       * Reads one 8 Bit signed integer word and increments the position within
588       * the chunk.       * the chunk.
589       *       *
# Line 443  namespace RIFF { Line 683  namespace RIFF {
683          return word;          return word;
684      }      }
685    
686        /** @brief Load chunk body into RAM.
687         *
688         * Loads the whole chunk body into memory. You can modify the data in
689         * RAM and save the data by calling File::Save() afterwards.
690         *
691         * <b>Caution:</b> the buffer pointer will be invalidated once
692         * File::Save() was called. You have to call LoadChunkData() again to
693         * get a new, valid pointer whenever File::Save() was called.
694         *
695         * You can call LoadChunkData() again if you previously scheduled to
696         * enlarge this chunk with a Resize() call. In that case the buffer will
697         * be enlarged to the new, scheduled chunk size and you can already
698         * place the new chunk data to the buffer and finally call File::Save()
699         * to enlarge the chunk physically and write the new data in one rush.
700         * This approach is definitely recommended if you have to enlarge and
701         * write new data to a lot of chunks.
702         *
703         * @returns a pointer to the data in RAM on success, NULL otherwise
704         * @throws Exception if data buffer could not be enlarged
705         * @see ReleaseChunkData()
706         */
707      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
708          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "") {
709              #if POSIX              #if POSIX
710              if (lseek(hFile, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
711              pChunkData = new uint8_t[GetSize()];              #elif defined(WIN32)
712              if (!pChunkData) return NULL;              if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;
             unsigned long readWords = read(hFile, pChunkData, GetSize());  
713              #else              #else
714              if (fseek(hFile, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
715              pChunkData = new uint8_t[GetSize()];              #endif // POSIX
716                unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
717                pChunkData = new uint8_t[ulBufferSize];
718              if (!pChunkData) return NULL;              if (!pChunkData) return NULL;
719              unsigned long readWords = fread(pChunkData, 1, GetSize(), hFile);              memset(pChunkData, 0, ulBufferSize);
720                #if POSIX
721                unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
722                #elif defined(WIN32)
723                DWORD readWords;
724                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
725                #else
726                unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
727              #endif // POSIX              #endif // POSIX
728              if (readWords != GetSize()) {              if (readWords != GetSize()) {
729                  delete[] pChunkData;                  delete[] pChunkData;
730                  return (pChunkData = NULL);                  return (pChunkData = NULL);
731              }              }
732                ulChunkDataSize = ulBufferSize;
733            } else if (NewChunkSize > ulChunkDataSize) {
734                uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
735                if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
736                memset(pNewBuffer, 0 , NewChunkSize);
737                memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
738                delete[] pChunkData;
739                pChunkData      = pNewBuffer;
740                ulChunkDataSize = NewChunkSize;
741          }          }
742          return pChunkData;          return pChunkData;
743      }      }
744    
745        /** @brief Free loaded chunk body from RAM.
746         *
747         * Frees loaded chunk body data from memory (RAM). You should call
748         * File::Save() before calling this method if you modified the data to
749         * make the changes persistent.
750         */
751      void Chunk::ReleaseChunkData() {      void Chunk::ReleaseChunkData() {
752          if (pChunkData) {          if (pChunkData) {
753              delete[] pChunkData;              delete[] pChunkData;
# Line 471  namespace RIFF { Line 755  namespace RIFF {
755          }          }
756      }      }
757    
758        /** @brief Resize chunk.
759         *
760         * Resizes this chunk's body, that is the actual size of data possible
761         * to be written to this chunk. This call will return immediately and
762         * just schedule the resize operation. You should call File::Save() to
763         * actually perform the resize operation(s) "physically" to the file.
764         * As this can take a while on large files, it is recommended to call
765         * Resize() first on all chunks which have to be resized and finally to
766         * call File::Save() to perform all those resize operations in one rush.
767         *
768         * <b>Caution:</b> You cannot directly write to enlarged chunks before
769         * calling File::Save() as this might exceed the current chunk's body
770         * boundary!
771         *
772         * @param iNewSize - new chunk body size in bytes (must be greater than zero)
773         * @throws RIFF::Exception  if \a iNewSize is less than 1
774         * @see File::Save()
775         */
776        void Chunk::Resize(int iNewSize) {
777            if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");
778            if (NewChunkSize == iNewSize) return;
779            NewChunkSize = iNewSize;
780            pFile->LogAsResized(this);
781        }
782    
783        /** @brief Write chunk persistently e.g. to disk.
784         *
785         * Stores the chunk persistently to its actual "physical" file.
786         *
787         * @param ulWritePos - position within the "physical" file where this
788         *                     chunk should be written to
789         * @param ulCurrentDataOffset - offset of current (old) data within
790         *                              the file
791         * @returns new write position in the "physical" file, that is
792         *          \a ulWritePos incremented by this chunk's new size
793         *          (including its header size of course)
794         */
795        unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
796            const unsigned long ulOriginalPos = ulWritePos;
797            ulWritePos += CHUNK_HEADER_SIZE;
798    
799            if (pFile->Mode != stream_mode_read_write)
800                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
801    
802            // if the whole chunk body was loaded into RAM
803            if (pChunkData) {
804                // make sure chunk data buffer in RAM is at least as large as the new chunk size
805                LoadChunkData();
806                // write chunk data from RAM persistently to the file
807                #if POSIX
808                lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
809                if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
810                    throw Exception("Writing Chunk data (from RAM) failed");
811                }
812                #elif defined(WIN32)
813                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
814                DWORD dwBytesWritten;
815                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
816                if (dwBytesWritten != NewChunkSize) {
817                    throw Exception("Writing Chunk data (from RAM) failed");
818                }
819                #else
820                fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
821                if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
822                    throw Exception("Writing Chunk data (from RAM) failed");
823                }
824                #endif // POSIX
825            } else {
826                // move chunk data from the end of the file to the appropriate position
827                int8_t* pCopyBuffer = new int8_t[4096];
828                unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
829                #if defined(WIN32)
830                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
831                #else
832                int iBytesMoved = 1;
833                #endif
834                for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
835                    iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
836                    #if POSIX
837                    lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
838                    iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
839                    lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
840                    iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
841                    #elif defined(WIN32)
842                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
843                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
844                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
845                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
846                    #else
847                    fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
848                    iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
849                    fseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
850                    iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
851                    #endif
852                }
853                delete[] pCopyBuffer;
854                if (iBytesMoved < 0) throw Exception("Writing Chunk data (from file) failed");
855            }
856    
857            // update this chunk's header
858            CurrentChunkSize = NewChunkSize;
859            WriteHeader(ulOriginalPos);
860    
861            // update chunk's position pointers
862            ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;
863            ulPos      = 0;
864    
865            // add pad byte if needed
866            if ((ulStartPos + NewChunkSize) % 2 != 0) {
867                const char cPadByte = 0;
868                #if POSIX
869                lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
870                write(pFile->hFileWrite, &cPadByte, 1);
871                #elif defined(WIN32)
872                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
873                DWORD dwBytesWritten;
874                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
875                #else
876                fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
877                fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
878                #endif
879                return ulStartPos + NewChunkSize + 1;
880            }
881    
882            return ulStartPos + NewChunkSize;
883        }
884    
885        void Chunk::__resetPos() {
886            ulPos = 0;
887        }
888    
889    
890    
891  // *************** List ***************  // *************** List ***************
892  // *  // *
893    
894      List::List() : Chunk() {      List::List(File* pFile) : Chunk(pFile) {
895        #if DEBUG        #if DEBUG
896        std::cout << "List::List()" << std::endl;        std::cout << "List::List(File* pFile)" << std::endl;
897        #endif // DEBUG        #endif // DEBUG
898          pSubChunks    = NULL;          pSubChunks    = NULL;
899          pSubChunksMap = NULL;          pSubChunksMap = NULL;
900      }      }
901    
902      #if POSIX      List::List(File* pFile, unsigned long StartPos, List* Parent)
903      List::List(int hFile, unsigned long StartPos, bool EndianNative, List* Parent)        : Chunk(pFile, StartPos, Parent) {
     #else  
     List::List(FILE* hFile, unsigned long StartPos, bool EndianNative, List* Parent)  
     #endif // POSIX  
       : Chunk(hFile, StartPos, EndianNative, Parent) {  
904          #if DEBUG          #if DEBUG
905          std::cout << "List::List(FILE*,ulong,bool,List*)" << std::endl;          std::cout << "List::List(File*,ulong,bool,List*)" << std::endl;
906          #endif // DEBUG          #endif // DEBUG
907          pSubChunks    = NULL;          pSubChunks    = NULL;
908          pSubChunksMap = NULL;          pSubChunksMap = NULL;
# Line 499  namespace RIFF { Line 910  namespace RIFF {
910          ulStartPos    = StartPos + LIST_HEADER_SIZE;          ulStartPos    = StartPos + LIST_HEADER_SIZE;
911      }      }
912    
913        List::List(File* pFile, List* pParent, uint32_t uiListID)
914          : Chunk(pFile, pParent, CHUNK_ID_LIST, 0) {
915            pSubChunks    = NULL;
916            pSubChunksMap = NULL;
917            ListType      = uiListID;
918        }
919    
920      List::~List() {      List::~List() {
921        #if DEBUG        #if DEBUG
922        std::cout << "List::~List()" << std::endl;        std::cout << "List::~List()" << std::endl;
# Line 642  namespace RIFF { Line 1060  namespace RIFF {
1060      }      }
1061    
1062      /**      /**
1063       *  Returns number subchunks within the list.       *  Returns number of subchunks within the list.
1064       */       */
1065      unsigned int List::CountSubChunks() {      unsigned int List::CountSubChunks() {
1066          if (!pSubChunks) LoadSubChunks();          if (!pSubChunks) LoadSubChunks();
# Line 693  namespace RIFF { Line 1111  namespace RIFF {
1111          return result;          return result;
1112      }      }
1113    
1114        /** @brief Creates a new sub chunk.
1115         *
1116         * Creates and adds a new sub chunk to this list chunk. Note that the
1117         * chunk's body size given by \a uiBodySize must be greater than zero.
1118         * You have to call File::Save() to make this change persistent to the
1119         * actual file and <b>before</b> performing any data write operations
1120         * on the new chunk!
1121         *
1122         * @param uiChunkID  - chunk ID of the new chunk
1123         * @param uiBodySize - size of the new chunk's body, that is its actual
1124         *                     data size (without header)
1125         * @throws RIFF::Exception if \a uiBodySize equals zero
1126         */
1127        Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1128            if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1129            if (!pSubChunks) LoadSubChunks();
1130            Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1131            pSubChunks->push_back(pNewChunk);
1132            (*pSubChunksMap)[uiChunkID] = pNewChunk;
1133            pNewChunk->Resize(uiBodySize);
1134            return pNewChunk;
1135        }
1136    
1137        /** @brief Creates a new list sub chunk.
1138         *
1139         * Creates and adds a new list sub chunk to this list chunk. Note that
1140         * you have to add sub chunks / sub list chunks to the new created chunk
1141         * <b>before</b> trying to make this change persisten to the actual
1142         * file with File::Save()!
1143         *
1144         * @param uiListType - list ID of the new list chunk
1145         */
1146        List* List::AddSubList(uint32_t uiListType) {
1147            if (!pSubChunks) LoadSubChunks();
1148            List* pNewListChunk = new List(pFile, this, uiListType);
1149            pSubChunks->push_back(pNewListChunk);
1150            (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1151            return pNewListChunk;
1152        }
1153    
1154        /** @brief Removes a sub chunk.
1155         *
1156         * Removes the sub chunk given by \a pSubChunk from this list and frees
1157         * it completely from RAM. The given chunk can either be a normal sub
1158         * chunk or a list sub chunk. You should call File::Save() to make this
1159         * change persistent at any time.
1160         *
1161         * @param pSubChunk - sub chunk or sub list chunk to be removed
1162         */
1163        void List::DeleteSubChunk(Chunk* pSubChunk) {
1164            if (!pSubChunks) LoadSubChunks();
1165            pSubChunks->remove(pSubChunk);
1166            if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1167                pSubChunksMap->erase(pSubChunk->GetChunkID());
1168                // try to find another chunk of the same chunk ID
1169                ChunkList::iterator iter = pSubChunks->begin();
1170                ChunkList::iterator end  = pSubChunks->end();
1171                for (; iter != end; ++iter) {
1172                    if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1173                        (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1174                        break; // we're done, stop search
1175                    }
1176                }
1177            }
1178            delete pSubChunk;
1179        }
1180    
1181      void List::ReadHeader(unsigned long fPos) {      void List::ReadHeader(unsigned long fPos) {
1182        #if DEBUG        #if DEBUG
1183        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1184        #endif // DEBUG        #endif // DEBUG
1185          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1186          ChunkSize -= 4;          NewChunkSize = CurrentChunkSize -= 4;
1187          #if POSIX          #if POSIX
1188          lseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1189          read(hFile, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1190            #elif defined(WIN32)
1191            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1192            DWORD dwBytesRead;
1193            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1194          #else          #else
1195          fseek(hFile, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1196          fread(&ListType, 4, 1, hFile);          fread(&ListType, 4, 1, pFile->hFileRead);
1197          #endif // POSIX          #endif // POSIX
1198        #if DEBUG        #if DEBUG
1199        std::cout << "listType=" << convertToString(ListType) << std::endl;        std::cout << "listType=" << convertToString(ListType) << std::endl;
1200        #endif // DEBUG        #endif // DEBUG
1201          if (!bEndianNative) {          if (!pFile->bEndianNative) {
1202              //swapBytes_32(&ListType);              //swapBytes_32(&ListType);
1203          }          }
1204      }      }
1205    
1206        void List::WriteHeader(unsigned long fPos) {
1207            // the four list type bytes officially belong the chunk's body in the RIFF format
1208            NewChunkSize += 4;
1209            Chunk::WriteHeader(fPos);
1210            NewChunkSize -= 4; // just revert the +4 incrementation
1211            #if POSIX
1212            lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1213            write(pFile->hFileWrite, &ListType, 4);
1214            #elif defined(WIN32)
1215            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1216            DWORD dwBytesWritten;
1217            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1218            #else
1219            fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1220            fwrite(&ListType, 4, 1, pFile->hFileWrite);
1221            #endif // POSIX
1222        }
1223    
1224      void List::LoadSubChunks() {      void List::LoadSubChunks() {
1225         #if DEBUG         #if DEBUG
1226         std::cout << "List::LoadSubChunks()";         std::cout << "List::LoadSubChunks()";
# Line 721  namespace RIFF { Line 1228  namespace RIFF {
1228          if (!pSubChunks) {          if (!pSubChunks) {
1229              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1230              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1231                if (!pFile->hFileRead) return;
1232                unsigned long uiOriginalPos = GetPos();
1233                SetPos(0); // jump to beginning of list chunk body
1234              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
1235                  Chunk* ck;                  Chunk* ck;
1236                  uint32_t ckid;                  uint32_t ckid;
# Line 729  namespace RIFF { Line 1239  namespace RIFF {
1239         std::cout << " ckid=" << convertToString(ckid) << std::endl;         std::cout << " ckid=" << convertToString(ckid) << std::endl;
1240         #endif // DEBUG         #endif // DEBUG
1241                  if (ckid == CHUNK_ID_LIST) {                  if (ckid == CHUNK_ID_LIST) {
1242                      ck = new RIFF::List(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);
1243                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);
1244                  }                  }
1245                  else { // simple chunk                  else { // simple chunk
1246                      ck = new RIFF::Chunk(hFile, ulStartPos + ulPos - 4, bEndianNative, this);                      ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);
1247                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);                      SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);
1248                  }                  }
1249                  pSubChunks->push_back(ck);                  pSubChunks->push_back(ck);
1250                  (*pSubChunksMap)[ckid] = ck;                  (*pSubChunksMap)[ckid] = ck;
1251                  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
1252              }              }
1253                SetPos(uiOriginalPos); // restore position before this call
1254            }
1255        }
1256    
1257        void List::LoadSubChunksRecursively() {
1258            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1259                pList->LoadSubChunksRecursively();
1260        }
1261    
1262        /** @brief Write list chunk persistently e.g. to disk.
1263         *
1264         * Stores the list chunk persistently to its actual "physical" file. All
1265         * subchunks (including sub list chunks) will be stored recursively as
1266         * well.
1267         *
1268         * @param ulWritePos - position within the "physical" file where this
1269         *                     list chunk should be written to
1270         * @param ulCurrentDataOffset - offset of current (old) data within
1271         *                              the file
1272         * @returns new write position in the "physical" file, that is
1273         *          \a ulWritePos incremented by this list chunk's new size
1274         *          (including its header size of course)
1275         */
1276        unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1277            const unsigned long ulOriginalPos = ulWritePos;
1278            ulWritePos += LIST_HEADER_SIZE;
1279    
1280            if (pFile->Mode != stream_mode_read_write)
1281                throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1282    
1283            // write all subchunks (including sub list chunks) recursively
1284            if (pSubChunks) {
1285                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1286                    ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);
1287                }
1288            }
1289    
1290            // update this list chunk's header
1291            CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1292            WriteHeader(ulOriginalPos);
1293    
1294            // offset of this list chunk in new written file may have changed
1295            ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1296    
1297            return ulWritePos;
1298        }
1299    
1300        void List::__resetPos() {
1301            Chunk::__resetPos();
1302            if (pSubChunks) {
1303                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1304                    (*iter)->__resetPos();
1305                }
1306          }          }
1307      }      }
1308    
# Line 755  namespace RIFF { Line 1318  namespace RIFF {
1318  // *************** File ***************  // *************** File ***************
1319  // *  // *
1320    
1321      File::File(const String& path) : List() {      /** @brief Create new RIFF file.
1322         *
1323         * Use this constructor if you want to create a new RIFF file completely
1324         * "from scratch". Note: there must be no empty chunks or empty list
1325         * chunks when trying to make the new RIFF file persistent with Save()!
1326         *
1327         * @param FileType - four-byte identifier of the RIFF file type
1328         * @see AddSubChunk(), AddSubList()
1329         */
1330        File::File(uint32_t FileType) : List(this) {
1331            #if defined(WIN32)
1332            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1333            #else
1334            hFileRead = hFileWrite = 0;
1335            #endif
1336            Mode = stream_mode_closed;
1337            bEndianNative = true;
1338            ulStartPos = RIFF_HEADER_SIZE;
1339            ListType = FileType;
1340        }
1341    
1342        /** @brief Load existing RIFF file.
1343         *
1344         * Loads an existing RIFF file with all its chunks.
1345         *
1346         * @param path - path and file name of the RIFF file to open
1347         * @throws RIFF::Exception if error occured while trying to load the
1348         *                         given RIFF file
1349         */
1350        File::File(const String& path) : List(this), Filename(path) {
1351        #if DEBUG        #if DEBUG
1352        std::cout << "File::File("<<path<<")" << std::endl;        std::cout << "File::File("<<path<<")" << std::endl;
1353        #endif // DEBUG        #endif // DEBUG
1354          bEndianNative = true;          bEndianNative = true;
1355          #if POSIX          #if POSIX
1356          hFile = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1357          if (hFile <= 0) {          if (hFileRead <= 0) {
1358              hFile = 0;              hFileRead = hFileWrite = 0;
1359                throw RIFF::Exception("Can't open \"" + path + "\"");
1360            }
1361            #elif defined(WIN32)
1362            hFileRead = hFileWrite = CreateFile(
1363                                         path.c_str(), GENERIC_READ,
1364                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1365                                         NULL, OPEN_EXISTING,
1366                                         FILE_ATTRIBUTE_NORMAL, NULL
1367                                     );
1368            if (hFileRead == INVALID_HANDLE_VALUE) {
1369                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1370              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1371          }          }
1372          #else          #else
1373          hFile = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1374          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1375          #endif // POSIX          #endif // POSIX
1376            Mode = stream_mode_read;
1377          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
1378          ReadHeader(0);          ReadHeader(0);
1379          if (ChunkID != CHUNK_ID_RIFF) {          if (ChunkID != CHUNK_ID_RIFF) {
# Line 777  namespace RIFF { Line 1381  namespace RIFF {
1381          }          }
1382      }      }
1383    
1384        String File::GetFileName() {
1385            return Filename;
1386        }
1387    
1388        stream_mode_t File::GetMode() {
1389            return Mode;
1390        }
1391    
1392        /** @brief Change file access mode.
1393         *
1394         * Changes files access mode either to read-only mode or to read/write
1395         * mode.
1396         *
1397         * @param NewMode - new file access mode
1398         * @returns true if mode was changed, false if current mode already
1399         *          equals new mode
1400         * @throws RIFF::Exception if new file access mode is unknown
1401         */
1402        bool File::SetMode(stream_mode_t NewMode) {
1403            if (NewMode != Mode) {
1404                switch (NewMode) {
1405                    case stream_mode_read:
1406                        #if POSIX
1407                        if (hFileRead) close(hFileRead);
1408                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1409                        if (hFileRead < 0) {
1410                            hFileRead = hFileWrite = 0;
1411                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1412                        }
1413                        #elif defined(WIN32)
1414                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1415                        hFileRead = hFileWrite = CreateFile(
1416                                                     Filename.c_str(), GENERIC_READ,
1417                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1418                                                     NULL, OPEN_EXISTING,
1419                                                     FILE_ATTRIBUTE_NORMAL, NULL
1420                                                 );
1421                        if (hFileRead == INVALID_HANDLE_VALUE) {
1422                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1423                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1424                        }
1425                        #else
1426                        if (hFileRead) fclose(hFileRead);
1427                        hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1428                        if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1429                        #endif
1430                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1431                        break;
1432                    case stream_mode_read_write:
1433                        #if POSIX
1434                        if (hFileRead) close(hFileRead);
1435                        hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1436                        if (hFileRead < 0) {
1437                            hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1438                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1439                        }
1440                        #elif defined(WIN32)
1441                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1442                        hFileRead = hFileWrite = CreateFile(
1443                                                     Filename.c_str(),
1444                                                     GENERIC_READ | GENERIC_WRITE,
1445                                                     FILE_SHARE_READ,
1446                                                     NULL, OPEN_ALWAYS,
1447                                                     FILE_ATTRIBUTE_NORMAL, NULL
1448                                                 );
1449                        if (hFileRead == INVALID_HANDLE_VALUE) {
1450                            hFileRead = hFileWrite = CreateFile(
1451                                                         Filename.c_str(), GENERIC_READ,
1452                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1453                                                         NULL, OPEN_EXISTING,
1454                                                         FILE_ATTRIBUTE_NORMAL, NULL
1455                                                     );
1456                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1457                        }
1458                        #else
1459                        if (hFileRead) fclose(hFileRead);
1460                        hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1461                        if (!hFileRead) {
1462                            hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1463                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1464                        }
1465                        #endif
1466                        __resetPos(); // reset read/write position of ALL 'Chunk' objects
1467                        break;
1468                    case stream_mode_closed:
1469                        #if POSIX
1470                        if (hFileRead)  close(hFileRead);
1471                        if (hFileWrite) close(hFileWrite);
1472                        #elif defined(WIN32)
1473                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1474                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1475                        #else
1476                        if (hFileRead)  fclose(hFileRead);
1477                        if (hFileWrite) fclose(hFileWrite);
1478                        #endif
1479                        hFileRead = hFileWrite = 0;
1480                        break;
1481                    default:
1482                        throw Exception("Unknown file access mode");
1483                }
1484                Mode = NewMode;
1485                return true;
1486            }
1487            return false;
1488        }
1489    
1490        /** @brief Save changes to same file.
1491         *
1492         * Make all changes of all chunks persistent by writing them to the
1493         * actual (same) file. The file might temporarily grow to a higher size
1494         * than it will have at the end of the saving process, in case chunks
1495         * were grown.
1496         *
1497         * @throws RIFF::Exception if there is an empty chunk or empty list
1498         *                         chunk or any kind of IO error occured
1499         */
1500        void File::Save() {
1501            // make sure the RIFF tree is built (from the original file)
1502            LoadSubChunksRecursively();
1503    
1504            // reopen file in write mode
1505            SetMode(stream_mode_read_write);
1506    
1507            // to be able to save the whole file without loading everything into
1508            // RAM and without having to store the data in a temporary file, we
1509            // enlarge the file with the sum of all _positive_ chunk size
1510            // changes, move current data towards the end of the file with the
1511            // calculated sum and finally update / rewrite the file by copying
1512            // the old data back to the right position at the beginning of the file
1513    
1514            // first we sum up all positive chunk size changes (and skip all negative ones)
1515            unsigned long ulPositiveSizeDiff = 0;
1516            for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1517                if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)");
1518                if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {
1519                    unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte
1520                    ulPositiveSizeDiff += ulDiff;
1521                }
1522            }
1523    
1524            unsigned long ulWorkingFileSize = GetFileSize();
1525    
1526            // if there are positive size changes...
1527            if (ulPositiveSizeDiff > 0) {
1528                // ... we enlarge this file first ...
1529                ulWorkingFileSize += ulPositiveSizeDiff;
1530                ResizeFile(ulWorkingFileSize);
1531                // ... and move current data by the same amount towards end of file.
1532                int8_t* pCopyBuffer = new int8_t[4096];
1533                const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1534                #if defined(WIN32)
1535                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1536                #else
1537                int iBytesMoved = 1;
1538                #endif
1539                for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {
1540                    const unsigned long ulToMove = ulFileSize - ulPos;
1541                    iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
1542                    #if POSIX
1543                    lseek(hFileRead, ulPos, SEEK_SET);
1544                    iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1545                    lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1546                    iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1547                    #elif defined(WIN32)
1548                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1549                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1550                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1551                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1552                    #else
1553                    fseek(hFileRead, ulPos, SEEK_SET);
1554                    iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1555                    fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1556                    iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1557                    #endif
1558                }
1559                delete[] pCopyBuffer;
1560                if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1561            }
1562    
1563            // rebuild / rewrite complete RIFF tree
1564            unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);
1565            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1566    
1567            // resize file to the final size
1568            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1569    
1570            // forget all resized chunks
1571            ResizedChunks.clear();
1572        }
1573    
1574        /** @brief Save changes to another file.
1575         *
1576         * Make all changes of all chunks persistent by writing them to another
1577         * file. <b>Caution:</b> this method is optimized for writing to
1578         * <b>another</b> file, do not use it to save the changes to the same
1579         * file! Use File::Save() in that case instead! Ignoring this might
1580         * result in a corrupted file, especially in case chunks were resized!
1581         *
1582         * After calling this method, this File object will be associated with
1583         * the new file (given by \a path) afterwards.
1584         *
1585         * @param path - path and file name where everything should be written to
1586         */
1587        void File::Save(const String& path) {
1588            //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
1589    
1590            // make sure the RIFF tree is built (from the original file)
1591            LoadSubChunksRecursively();
1592    
1593            if (Filename.length() > 0) SetMode(stream_mode_read);
1594            // open the other (new) file for writing and truncate it to zero size
1595            #if POSIX
1596            hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1597            if (hFileWrite < 0) {
1598                hFileWrite = hFileRead;
1599                throw Exception("Could not open file \"" + path + "\" for writing");
1600            }
1601            #elif defined(WIN32)
1602            hFileWrite = CreateFile(
1603                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1604                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL
1605                         );
1606            if (hFileWrite == INVALID_HANDLE_VALUE) {
1607                hFileWrite = hFileRead;
1608                throw Exception("Could not open file \"" + path + "\" for writing");
1609            }
1610            #else
1611            hFileWrite = fopen(path.c_str(), "w+b");
1612            if (!hFileWrite) {
1613                hFileWrite = hFileRead;
1614                throw Exception("Could not open file \"" + path + "\" for writing");
1615            }
1616            #endif // POSIX
1617            Mode = stream_mode_read_write;
1618    
1619            // write complete RIFF tree to the other (new) file
1620            unsigned long ulTotalSize  = WriteChunk(0, 0);
1621            unsigned long ulActualSize = __GetFileSize(hFileWrite);
1622    
1623            // resize file to the final size (if the file was originally larger)
1624            if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1625    
1626            // forget all resized chunks
1627            ResizedChunks.clear();
1628    
1629            if (Filename.length() > 0) {
1630                #if POSIX
1631                close(hFileWrite);
1632                #elif defined(WIN32)
1633                CloseHandle(hFileWrite);
1634                #else
1635                fclose(hFileWrite);
1636                #endif
1637                hFileWrite = hFileRead;
1638            }
1639    
1640            // associate new file with this File object from now on
1641            Filename = path;
1642            Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1643            SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
1644        }
1645    
1646        void File::ResizeFile(unsigned long ulNewSize) {
1647            #if POSIX
1648            if (ftruncate(hFileWrite, ulNewSize) < 0)
1649                throw Exception("Could not resize file \"" + Filename + "\"");
1650            #elif defined(WIN32)
1651            if (
1652                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1653                !SetEndOfFile(hFileWrite)
1654            ) throw Exception("Could not resize file \"" + Filename + "\"");
1655            #else
1656            # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1657            # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1658            #endif
1659        }
1660    
1661      File::~File() {      File::~File() {
1662         #if DEBUG         #if DEBUG
1663         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
1664         #endif // DEBUG         #endif // DEBUG
1665          #if POSIX          #if POSIX
1666          if (hFile) close(hFile);          if (hFileRead) close(hFileRead);
1667            #elif defined(WIN32)
1668            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1669          #else          #else
1670          if (hFile) fclose(hFile);          if (hFileRead) fclose(hFileRead);
1671          #endif // POSIX          #endif // POSIX
1672      }      }
1673    
1674        void File::LogAsResized(Chunk* pResizedChunk) {
1675            ResizedChunks.push_back(pResizedChunk);
1676        }
1677    
1678      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
1679          #if POSIX          return __GetFileSize(hFileRead);
1680        }
1681    
1682        #if POSIX
1683        unsigned long File::__GetFileSize(int hFile) {
1684          struct stat filestat;          struct stat filestat;
1685          fstat(hFile, &filestat);          fstat(hFile, &filestat);
1686          long size = filestat.st_size;          long size = filestat.st_size;
1687          #else // standard C functions          return size;
1688        }
1689        #elif defined(WIN32)
1690        unsigned long File::__GetFileSize(HANDLE hFile) {
1691            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1692            if (dwSize == INVALID_FILE_SIZE)
1693                throw Exception("Windows FS error: could not determine file size");
1694            return dwSize;
1695        }
1696        #else // standard C functions
1697        unsigned long File::__GetFileSize(FILE* hFile) {
1698          long curpos = ftell(hFile);          long curpos = ftell(hFile);
1699          fseek(hFile, 0, SEEK_END);          fseek(hFile, 0, SEEK_END);
1700          long size = ftell(hFile);          long size = ftell(hFile);
1701          fseek(hFile, curpos, SEEK_SET);          fseek(hFile, curpos, SEEK_SET);
         #endif // POSIX  
1702          return size;          return size;
1703      }      }
1704        #endif
1705    
1706    
1707  // *************** Exception ***************  // *************** Exception ***************
# Line 811  namespace RIFF { Line 1711  namespace RIFF {
1711          std::cout << "RIFF::Exception: " << Message << std::endl;          std::cout << "RIFF::Exception: " << Message << std::endl;
1712      }      }
1713    
1714    
1715    // *************** functions ***************
1716    // *
1717    
1718        /**
1719         * Returns the name of this C++ library. This is usually "libgig" of
1720         * course. This call is equivalent to DLS::libraryName() and
1721         * gig::libraryName().
1722         */
1723        String libraryName() {
1724            return PACKAGE;
1725        }
1726    
1727        /**
1728         * Returns version of this C++ library. This call is equivalent to
1729         * DLS::libraryVersion() and gig::libraryVersion().
1730         */
1731        String libraryVersion() {
1732            return VERSION;
1733        }
1734    
1735  } // namespace RIFF  } // namespace RIFF
 #endif  

Legend:
Removed from v.24  
changed lines
  Added in v.1063

  ViewVC Help
Powered by ViewVC