/[svn]/libgig/trunk/src/RIFF.cpp
ViewVC logotype

Annotation of /libgig/trunk/src/RIFF.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1863 - (hide annotations) (download)
Fri Mar 13 10:57:24 2009 UTC (15 years, 1 month ago) by schoenebeck
File size: 75420 byte(s)
* src/RIFF.cpp :
    - bugfix: undefined behavior (e.g. endless loop) when opening zero
      length files, now throws a RIFF::Exception instead (fixes bug #121)

1 schoenebeck 2 /***************************************************************************
2     * *
3 schoenebeck 933 * libgig - C++ cross-platform Gigasampler format file access library *
4 schoenebeck 2 * *
5 schoenebeck 1851 * Copyright (C) 2003-2009 by Christian Schoenebeck *
6 schoenebeck 384 * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
8     * 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 *
10     * the Free Software Foundation; either version 2 of the License, or *
11     * (at your option) any later version. *
12     * *
13     * This library is distributed in the hope that it will be useful, *
14     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16     * GNU General Public License for more details. *
17     * *
18     * You should have received a copy of the GNU General Public License *
19     * along with this library; if not, write to the Free Software *
20     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
21     * MA 02111-1307 USA *
22     ***************************************************************************/
23 schoenebeck 780
24 persson 1713 #include <algorithm>
25 schoenebeck 780 #include <string.h>
26    
27 schoenebeck 2 #include "RIFF.h"
28    
29 schoenebeck 800 #include "helper.h"
30    
31 schoenebeck 2 namespace RIFF {
32    
33 schoenebeck 1105 // *************** Internal functions **************
34     // *
35    
36     /// Returns a human readable path of the given chunk.
37 schoenebeck 1383 static String __resolveChunkPath(Chunk* pCk) {
38 schoenebeck 1105 String sPath;
39     for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
40     if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
41     List* pList = (List*) pChunk;
42     sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
43     } else {
44     sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
45     }
46     }
47     return sPath;
48     }
49    
50    
51    
52 schoenebeck 2 // *************** Chunk **************
53     // *
54    
55 schoenebeck 780 Chunk::Chunk(File* pFile) {
56 schoenebeck 2 #if DEBUG
57 schoenebeck 780 std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
58 schoenebeck 2 #endif // DEBUG
59     ulPos = 0;
60     pParent = NULL;
61     pChunkData = NULL;
62 schoenebeck 1863 CurrentChunkSize = 0;
63     NewChunkSize = 0;
64 schoenebeck 800 ulChunkDataSize = 0;
65 schoenebeck 798 ChunkID = CHUNK_ID_RIFF;
66 schoenebeck 780 this->pFile = pFile;
67 schoenebeck 2 }
68    
69 schoenebeck 780 Chunk::Chunk(File* pFile, unsigned long StartPos, List* Parent) {
70 schoenebeck 2 #if DEBUG
71 schoenebeck 780 std::cout << "Chunk::Chunk(File*,ulong,bool,List*),StartPos=" << StartPos << std::endl;
72 schoenebeck 2 #endif // DEBUG
73 schoenebeck 780 this->pFile = pFile;
74 schoenebeck 2 ulStartPos = StartPos + CHUNK_HEADER_SIZE;
75     pParent = Parent;
76     ulPos = 0;
77     pChunkData = NULL;
78 schoenebeck 1863 CurrentChunkSize = 0;
79     NewChunkSize = 0;
80 schoenebeck 800 ulChunkDataSize = 0;
81 schoenebeck 2 ReadHeader(StartPos);
82     }
83    
84 schoenebeck 780 Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, uint uiBodySize) {
85     this->pFile = pFile;
86     ulStartPos = 0; // arbitrary usually, since it will be updated when we write the chunk
87     this->pParent = pParent;
88     ulPos = 0;
89     pChunkData = NULL;
90 schoenebeck 1863 ChunkID = uiChunkID;
91 schoenebeck 800 ulChunkDataSize = 0;
92 schoenebeck 780 CurrentChunkSize = 0;
93     NewChunkSize = uiBodySize;
94     }
95    
96 schoenebeck 2 Chunk::~Chunk() {
97 persson 1678 pFile->UnlogResized(this);
98 schoenebeck 2 if (pChunkData) delete[] pChunkData;
99     }
100    
101     void Chunk::ReadHeader(unsigned long fPos) {
102     #if DEBUG
103     std::cout << "Chunk::Readheader(" << fPos << ") ";
104     #endif // DEBUG
105 schoenebeck 1863 ChunkID = 0;
106     NewChunkSize = CurrentChunkSize = 0;
107 schoenebeck 2 #if POSIX
108 schoenebeck 780 if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
109     read(pFile->hFileRead, &ChunkID, 4);
110     read(pFile->hFileRead, &CurrentChunkSize, 4);
111 schoenebeck 1050 #elif defined(WIN32)
112     if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
113     DWORD dwBytesRead;
114     ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
115     ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
116 schoenebeck 2 #else
117 schoenebeck 780 if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
118     fread(&ChunkID, 4, 1, pFile->hFileRead);
119     fread(&CurrentChunkSize, 4, 1, pFile->hFileRead);
120 schoenebeck 2 #endif // POSIX
121     #if WORDS_BIGENDIAN
122     if (ChunkID == CHUNK_ID_RIFF) {
123 schoenebeck 808 pFile->bEndianNative = false;
124 schoenebeck 2 }
125     #else // little endian
126     if (ChunkID == CHUNK_ID_RIFX) {
127 schoenebeck 780 pFile->bEndianNative = false;
128 schoenebeck 2 ChunkID = CHUNK_ID_RIFF;
129     }
130     #endif // WORDS_BIGENDIAN
131 schoenebeck 780 if (!pFile->bEndianNative) {
132 schoenebeck 11 //swapBytes_32(&ChunkID);
133 schoenebeck 780 swapBytes_32(&CurrentChunkSize);
134 schoenebeck 2 }
135 schoenebeck 11 #if DEBUG
136     std::cout << "ckID=" << convertToString(ChunkID) << " ";
137 schoenebeck 1863 std::cout << "ckSize=" << CurrentChunkSize << " ";
138     std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
139 schoenebeck 11 #endif // DEBUG
140 schoenebeck 780 NewChunkSize = CurrentChunkSize;
141 schoenebeck 2 }
142     }
143    
144 schoenebeck 780 void Chunk::WriteHeader(unsigned long fPos) {
145     uint32_t uiNewChunkID = ChunkID;
146     if (ChunkID == CHUNK_ID_RIFF) {
147     #if WORDS_BIGENDIAN
148     if (pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
149     #else // little endian
150     if (!pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
151     #endif // WORDS_BIGENDIAN
152     }
153    
154     uint32_t uiNewChunkSize = NewChunkSize;
155     if (!pFile->bEndianNative) {
156     swapBytes_32(&uiNewChunkSize);
157     }
158    
159     #if POSIX
160     if (lseek(pFile->hFileWrite, fPos, SEEK_SET) != -1) {
161     write(pFile->hFileWrite, &uiNewChunkID, 4);
162     write(pFile->hFileWrite, &uiNewChunkSize, 4);
163     }
164 schoenebeck 1050 #elif defined(WIN32)
165     if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
166     DWORD dwBytesWritten;
167     WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
168     WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
169     }
170 schoenebeck 780 #else
171     if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
172     fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
173     fwrite(&uiNewChunkSize, 4, 1, pFile->hFileWrite);
174     }
175     #endif // POSIX
176     }
177    
178 schoenebeck 11 /**
179     * Returns the String representation of the chunk's ID (e.g. "RIFF",
180     * "LIST").
181     */
182 schoenebeck 2 String Chunk::GetChunkIDString() {
183     return convertToString(ChunkID);
184     }
185    
186 schoenebeck 11 /**
187     * Sets the position within the chunk body, thus within the data portion
188     * of the chunk (in bytes).
189     *
190 schoenebeck 780 * <b>Caution:</b> the position will be reset to zero whenever
191     * File::Save() was called.
192     *
193 schoenebeck 11 * @param Where - position offset (in bytes)
194     * @param Whence - optional: defines to what <i>\a Where</i> relates to,
195     * if omitted \a Where relates to beginning of the chunk
196     * data
197     */
198 schoenebeck 2 unsigned long Chunk::SetPos(unsigned long Where, stream_whence_t Whence) {
199     #if DEBUG
200     std::cout << "Chunk::SetPos(ulong)" << std::endl;
201     #endif // DEBUG
202     switch (Whence) {
203     case stream_curpos:
204     ulPos += Where;
205     break;
206     case stream_end:
207 schoenebeck 780 ulPos = CurrentChunkSize - 1 - Where;
208 schoenebeck 2 break;
209     case stream_backward:
210     ulPos -= Where;
211     break;
212     case stream_start: default:
213     ulPos = Where;
214     break;
215     }
216 schoenebeck 780 if (ulPos > CurrentChunkSize) ulPos = CurrentChunkSize;
217 schoenebeck 2 return ulPos;
218     }
219    
220 schoenebeck 11 /**
221     * Returns the number of bytes left to read in the chunk body.
222     * When reading data from the chunk using the Read*() Methods, the
223     * position within the chunk data (that is the chunk body) will be
224     * incremented by the number of read bytes and RemainingBytes() returns
225     * how much data is left to read from the current position to the end
226     * of the chunk data.
227     *
228     * @returns number of bytes left to read
229     */
230 schoenebeck 2 unsigned long Chunk::RemainingBytes() {
231     #if DEBUG
232 schoenebeck 780 std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;
233 schoenebeck 2 #endif // DEBUG
234 schoenebeck 1863 return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;
235 schoenebeck 2 }
236    
237 schoenebeck 11 /**
238     * Returns the current state of the chunk object.
239     * Following values are possible:
240     * - RIFF::stream_ready :
241     * chunk data can be read (this is the usual case)
242     * - RIFF::stream_closed :
243     * the data stream was closed somehow, no more reading possible
244     * - RIFF::stream_end_reached :
245 schoenebeck 1383 * already reached the end of the chunk data, no more reading
246 schoenebeck 11 * possible without SetPos()
247     */
248 schoenebeck 2 stream_state_t Chunk::GetState() {
249     #if DEBUG
250     std::cout << "Chunk::GetState()" << std::endl;
251     #endif // DEBUG
252     #if POSIX
253 schoenebeck 1050 if (pFile->hFileRead == 0) return stream_closed;
254     #elif defined (WIN32)
255     if (pFile->hFileRead == INVALID_HANDLE_VALUE)
256     return stream_closed;
257 schoenebeck 2 #else
258 schoenebeck 780 if (pFile->hFileRead == NULL) return stream_closed;
259 schoenebeck 2 #endif // POSIX
260 schoenebeck 780 if (ulPos < CurrentChunkSize) return stream_ready;
261     else return stream_end_reached;
262 schoenebeck 2 }
263    
264     /**
265     * Reads \a WordCount number of data words with given \a WordSize and
266     * copies it into a buffer pointed by \a pData. The buffer has to be
267     * allocated and be sure to provide the correct \a WordSize, as this
268     * will be important and taken into account for eventual endian
269     * correction (swapping of bytes due to different native byte order of
270     * a system). The position within the chunk will automatically be
271     * incremented.
272     *
273     * @param pData destination buffer
274     * @param WordCount number of data words to read
275     * @param WordSize size of each data word to read
276     * @returns number of successfully read data words or 0 if end
277     * of file reached or error occured
278     */
279     unsigned long Chunk::Read(void* pData, unsigned long WordCount, unsigned long WordSize) {
280     #if DEBUG
281     std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
282     #endif // DEBUG
283 schoenebeck 1851 if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
284 schoenebeck 780 if (ulPos >= CurrentChunkSize) return 0;
285     if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
286 schoenebeck 2 #if POSIX
287 schoenebeck 780 if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;
288     unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
289 schoenebeck 2 if (readWords < 1) return 0;
290     readWords /= WordSize;
291 schoenebeck 1050 #elif defined(WIN32)
292     if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
293     DWORD readWords;
294     ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
295     if (readWords < 1) return 0;
296     readWords /= WordSize;
297 schoenebeck 2 #else // standard C functions
298 schoenebeck 780 if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
299     unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
300 schoenebeck 2 #endif // POSIX
301 schoenebeck 780 if (!pFile->bEndianNative && WordSize != 1) {
302 schoenebeck 2 switch (WordSize) {
303     case 2:
304     for (unsigned long iWord = 0; iWord < readWords; iWord++)
305     swapBytes_16((uint16_t*) pData + iWord);
306     break;
307     case 4:
308     for (unsigned long iWord = 0; iWord < readWords; iWord++)
309     swapBytes_32((uint32_t*) pData + iWord);
310     break;
311     default:
312     for (unsigned long iWord = 0; iWord < readWords; iWord++)
313     swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
314     break;
315     }
316     }
317     SetPos(readWords * WordSize, stream_curpos);
318     return readWords;
319     }
320    
321 schoenebeck 780 /**
322     * Writes \a WordCount number of data words with given \a WordSize from
323     * the buffer pointed by \a pData. Be sure to provide the correct
324     * \a WordSize, as this will be important and taken into account for
325     * eventual endian correction (swapping of bytes due to different
326     * native byte order of a system). The position within the chunk will
327     * automatically be incremented.
328     *
329     * @param pData source buffer (containing the data)
330     * @param WordCount number of data words to write
331     * @param WordSize size of each data word to write
332     * @returns number of successfully written data words
333     * @throws RIFF::Exception if write operation would exceed current
334     * chunk size or any IO error occured
335     * @see Resize()
336     */
337     unsigned long Chunk::Write(void* pData, unsigned long WordCount, unsigned long WordSize) {
338 schoenebeck 798 if (pFile->Mode != stream_mode_read_write)
339     throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
340     if (ulPos >= CurrentChunkSize || ulPos + WordCount * WordSize > CurrentChunkSize)
341 schoenebeck 780 throw Exception("End of chunk reached while trying to write data");
342     if (!pFile->bEndianNative && WordSize != 1) {
343     switch (WordSize) {
344     case 2:
345     for (unsigned long iWord = 0; iWord < WordCount; iWord++)
346     swapBytes_16((uint16_t*) pData + iWord);
347     break;
348     case 4:
349     for (unsigned long iWord = 0; iWord < WordCount; iWord++)
350     swapBytes_32((uint32_t*) pData + iWord);
351     break;
352     default:
353     for (unsigned long iWord = 0; iWord < WordCount; iWord++)
354     swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
355     break;
356     }
357     }
358     #if POSIX
359     if (lseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET) < 0) {
360     throw Exception("Could not seek to position " + ToString(ulPos) +
361     " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
362     }
363     unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
364     if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
365     writtenWords /= WordSize;
366 schoenebeck 1050 #elif defined(WIN32)
367     if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
368     throw Exception("Could not seek to position " + ToString(ulPos) +
369 schoenebeck 1459 " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
370 schoenebeck 1050 }
371     DWORD writtenWords;
372     WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
373     if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
374     writtenWords /= WordSize;
375 schoenebeck 780 #else // standard C functions
376     if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
377     throw Exception("Could not seek to position " + ToString(ulPos) +
378     " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
379     }
380     unsigned long writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
381     #endif // POSIX
382     SetPos(writtenWords * WordSize, stream_curpos);
383     return writtenWords;
384     }
385    
386 schoenebeck 2 /** Just an internal wrapper for the main <i>Read()</i> method with additional Exception throwing on errors. */
387     unsigned long Chunk::ReadSceptical(void* pData, unsigned long WordCount, unsigned long WordSize) {
388     unsigned long readWords = Read(pData, WordCount, WordSize);
389     if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");
390     return readWords;
391     }
392    
393     /**
394     * Reads \a WordCount number of 8 Bit signed integer words and copies it
395     * into the buffer pointed by \a pData. The buffer has to be allocated.
396     * The position within the chunk will automatically be incremented.
397     *
398     * @param pData destination buffer
399     * @param WordCount number of 8 Bit signed integers to read
400     * @returns number of read integers
401     * @throws RIFF::Exception if an error occured or less than
402     * \a WordCount integers could be read!
403     */
404     unsigned long Chunk::ReadInt8(int8_t* pData, unsigned long WordCount) {
405     #if DEBUG
406     std::cout << "Chunk::ReadInt8(int8_t*,ulong)" << std::endl;
407     #endif // DEBUG
408     return ReadSceptical(pData, WordCount, 1);
409     }
410    
411     /**
412 schoenebeck 780 * Writes \a WordCount number of 8 Bit signed integer words from the
413     * buffer pointed by \a pData to the chunk's body, directly to the
414     * actual "physical" file. The position within the chunk will
415     * automatically be incremented. Note: you cannot write beyond the
416     * boundaries of the chunk, to append data to the chunk call Resize()
417     * before.
418     *
419     * @param pData source buffer (containing the data)
420     * @param WordCount number of 8 Bit signed integers to write
421     * @returns number of written integers
422     * @throws RIFF::Exception if an IO error occured
423     * @see Resize()
424     */
425     unsigned long Chunk::WriteInt8(int8_t* pData, unsigned long WordCount) {
426     return Write(pData, WordCount, 1);
427     }
428    
429     /**
430 schoenebeck 2 * Reads \a WordCount number of 8 Bit unsigned integer words and copies
431     * it into the buffer pointed by \a pData. The buffer has to be
432     * allocated. The position within the chunk will automatically be
433     * incremented.
434     *
435     * @param pData destination buffer
436     * @param WordCount number of 8 Bit unsigned integers to read
437     * @returns number of read integers
438     * @throws RIFF::Exception if an error occured or less than
439     * \a WordCount integers could be read!
440     */
441     unsigned long Chunk::ReadUint8(uint8_t* pData, unsigned long WordCount) {
442     #if DEBUG
443     std::cout << "Chunk::ReadUint8(uint8_t*,ulong)" << std::endl;
444     #endif // DEBUG
445     return ReadSceptical(pData, WordCount, 1);
446     }
447    
448     /**
449 schoenebeck 780 * Writes \a WordCount number of 8 Bit unsigned integer words from the
450     * buffer pointed by \a pData to the chunk's body, directly to the
451     * actual "physical" file. The position within the chunk will
452     * automatically be incremented. Note: you cannot write beyond the
453     * boundaries of the chunk, to append data to the chunk call Resize()
454     * before.
455     *
456     * @param pData source buffer (containing the data)
457     * @param WordCount number of 8 Bit unsigned integers to write
458     * @returns number of written integers
459     * @throws RIFF::Exception if an IO error occured
460     * @see Resize()
461     */
462     unsigned long Chunk::WriteUint8(uint8_t* pData, unsigned long WordCount) {
463     return Write(pData, WordCount, 1);
464     }
465    
466     /**
467 schoenebeck 2 * Reads \a WordCount number of 16 Bit signed integer words and copies
468     * it into the buffer pointed by \a pData. The buffer has to be
469     * allocated. Endian correction will automatically be done if needed.
470     * The position within the chunk will automatically be incremented.
471     *
472     * @param pData destination buffer
473     * @param WordCount number of 16 Bit signed integers to read
474     * @returns number of read integers
475     * @throws RIFF::Exception if an error occured or less than
476     * \a WordCount integers could be read!
477     */
478     unsigned long Chunk::ReadInt16(int16_t* pData, unsigned long WordCount) {
479     #if DEBUG
480     std::cout << "Chunk::ReadInt16(int16_t*,ulong)" << std::endl;
481     #endif // DEBUG
482     return ReadSceptical(pData, WordCount, 2);
483     }
484    
485     /**
486 schoenebeck 780 * Writes \a WordCount number of 16 Bit signed integer words from the
487     * buffer pointed by \a pData to the chunk's body, directly to the
488     * actual "physical" file. The position within the chunk will
489     * automatically be incremented. Note: you cannot write beyond the
490     * boundaries of the chunk, to append data to the chunk call Resize()
491     * before.
492     *
493     * @param pData source buffer (containing the data)
494     * @param WordCount number of 16 Bit signed integers to write
495     * @returns number of written integers
496     * @throws RIFF::Exception if an IO error occured
497     * @see Resize()
498     */
499     unsigned long Chunk::WriteInt16(int16_t* pData, unsigned long WordCount) {
500     return Write(pData, WordCount, 2);
501     }
502    
503     /**
504 schoenebeck 2 * Reads \a WordCount number of 16 Bit unsigned integer words and copies
505     * it into the buffer pointed by \a pData. The buffer has to be
506     * allocated. Endian correction will automatically be done if needed.
507     * The position within the chunk will automatically be incremented.
508     *
509     * @param pData destination buffer
510     * @param WordCount number of 8 Bit unsigned integers to read
511     * @returns number of read integers
512     * @throws RIFF::Exception if an error occured or less than
513     * \a WordCount integers could be read!
514     */
515     unsigned long Chunk::ReadUint16(uint16_t* pData, unsigned long WordCount) {
516     #if DEBUG
517     std::cout << "Chunk::ReadUint16(uint16_t*,ulong)" << std::endl;
518     #endif // DEBUG
519     return ReadSceptical(pData, WordCount, 2);
520     }
521    
522     /**
523 schoenebeck 780 * Writes \a WordCount number of 16 Bit unsigned integer words from the
524     * buffer pointed by \a pData to the chunk's body, directly to the
525     * actual "physical" file. The position within the chunk will
526     * automatically be incremented. Note: you cannot write beyond the
527     * boundaries of the chunk, to append data to the chunk call Resize()
528     * before.
529     *
530     * @param pData source buffer (containing the data)
531     * @param WordCount number of 16 Bit unsigned integers to write
532     * @returns number of written integers
533     * @throws RIFF::Exception if an IO error occured
534     * @see Resize()
535     */
536     unsigned long Chunk::WriteUint16(uint16_t* pData, unsigned long WordCount) {
537     return Write(pData, WordCount, 2);
538     }
539    
540     /**
541 schoenebeck 2 * Reads \a WordCount number of 32 Bit signed integer words and copies
542     * it into the buffer pointed by \a pData. The buffer has to be
543     * allocated. Endian correction will automatically be done if needed.
544     * The position within the chunk will automatically be incremented.
545     *
546     * @param pData destination buffer
547     * @param WordCount number of 32 Bit signed integers to read
548     * @returns number of read integers
549     * @throws RIFF::Exception if an error occured or less than
550     * \a WordCount integers could be read!
551     */
552     unsigned long Chunk::ReadInt32(int32_t* pData, unsigned long WordCount) {
553     #if DEBUG
554     std::cout << "Chunk::ReadInt32(int32_t*,ulong)" << std::endl;
555     #endif // DEBUG
556     return ReadSceptical(pData, WordCount, 4);
557     }
558    
559     /**
560 schoenebeck 780 * Writes \a WordCount number of 32 Bit signed integer words from the
561     * buffer pointed by \a pData to the chunk's body, directly to the
562     * actual "physical" file. The position within the chunk will
563     * automatically be incremented. Note: you cannot write beyond the
564     * boundaries of the chunk, to append data to the chunk call Resize()
565     * before.
566     *
567     * @param pData source buffer (containing the data)
568     * @param WordCount number of 32 Bit signed integers to write
569     * @returns number of written integers
570     * @throws RIFF::Exception if an IO error occured
571     * @see Resize()
572     */
573     unsigned long Chunk::WriteInt32(int32_t* pData, unsigned long WordCount) {
574     return Write(pData, WordCount, 4);
575     }
576    
577     /**
578 schoenebeck 2 * Reads \a WordCount number of 32 Bit unsigned integer words and copies
579     * it into the buffer pointed by \a pData. The buffer has to be
580     * allocated. Endian correction will automatically be done if needed.
581     * The position within the chunk will automatically be incremented.
582     *
583     * @param pData destination buffer
584     * @param WordCount number of 32 Bit unsigned integers to read
585     * @returns number of read integers
586     * @throws RIFF::Exception if an error occured or less than
587     * \a WordCount integers could be read!
588     */
589     unsigned long Chunk::ReadUint32(uint32_t* pData, unsigned long WordCount) {
590     #if DEBUG
591     std::cout << "Chunk::ReadUint32(uint32_t*,ulong)" << std::endl;
592     #endif // DEBUG
593     return ReadSceptical(pData, WordCount, 4);
594     }
595    
596     /**
597 schoenebeck 780 * Writes \a WordCount number of 32 Bit unsigned integer words from the
598     * buffer pointed by \a pData to the chunk's body, directly to the
599     * actual "physical" file. The position within the chunk will
600     * automatically be incremented. Note: you cannot write beyond the
601     * boundaries of the chunk, to append data to the chunk call Resize()
602     * before.
603     *
604     * @param pData source buffer (containing the data)
605     * @param WordCount number of 32 Bit unsigned integers to write
606     * @returns number of written integers
607     * @throws RIFF::Exception if an IO error occured
608     * @see Resize()
609     */
610     unsigned long Chunk::WriteUint32(uint32_t* pData, unsigned long WordCount) {
611     return Write(pData, WordCount, 4);
612     }
613    
614     /**
615 schoenebeck 2 * Reads one 8 Bit signed integer word and increments the position within
616     * the chunk.
617     *
618     * @returns read integer word
619     * @throws RIFF::Exception if an error occured
620     */
621     int8_t Chunk::ReadInt8() {
622     #if DEBUG
623     std::cout << "Chunk::ReadInt8()" << std::endl;
624     #endif // DEBUG
625     int8_t word;
626     ReadSceptical(&word,1,1);
627     return word;
628     }
629    
630     /**
631     * Reads one 8 Bit unsigned integer word and increments the position
632     * within the chunk.
633     *
634     * @returns read integer word
635     * @throws RIFF::Exception if an error occured
636     */
637     uint8_t Chunk::ReadUint8() {
638     #if DEBUG
639     std::cout << "Chunk::ReadUint8()" << std::endl;
640     #endif // DEBUG
641     uint8_t word;
642     ReadSceptical(&word,1,1);
643     return word;
644     }
645    
646     /**
647     * Reads one 16 Bit signed integer word and increments the position
648     * within the chunk. Endian correction will automatically be done if
649     * needed.
650     *
651     * @returns read integer word
652     * @throws RIFF::Exception if an error occured
653     */
654     int16_t Chunk::ReadInt16() {
655     #if DEBUG
656     std::cout << "Chunk::ReadInt16()" << std::endl;
657     #endif // DEBUG
658     int16_t word;
659     ReadSceptical(&word,1,2);
660     return word;
661     }
662    
663     /**
664     * Reads one 16 Bit unsigned integer word and increments the position
665     * within the chunk. Endian correction will automatically be done if
666     * needed.
667     *
668     * @returns read integer word
669     * @throws RIFF::Exception if an error occured
670     */
671     uint16_t Chunk::ReadUint16() {
672     #if DEBUG
673     std::cout << "Chunk::ReadUint16()" << std::endl;
674     #endif // DEBUG
675     uint16_t word;
676     ReadSceptical(&word,1,2);
677     return word;
678     }
679    
680     /**
681     * Reads one 32 Bit signed integer word and increments the position
682     * within the chunk. Endian correction will automatically be done if
683     * needed.
684     *
685     * @returns read integer word
686     * @throws RIFF::Exception if an error occured
687     */
688     int32_t Chunk::ReadInt32() {
689     #if DEBUG
690     std::cout << "Chunk::ReadInt32()" << std::endl;
691     #endif // DEBUG
692     int32_t word;
693     ReadSceptical(&word,1,4);
694     return word;
695     }
696    
697     /**
698     * Reads one 32 Bit unsigned integer word and increments the position
699     * within the chunk. Endian correction will automatically be done if
700     * needed.
701     *
702     * @returns read integer word
703     * @throws RIFF::Exception if an error occured
704     */
705     uint32_t Chunk::ReadUint32() {
706     #if DEBUG
707     std::cout << "Chunk::ReadUint32()" << std::endl;
708     #endif // DEBUG
709     uint32_t word;
710     ReadSceptical(&word,1,4);
711     return word;
712     }
713    
714 schoenebeck 780 /** @brief Load chunk body into RAM.
715     *
716     * Loads the whole chunk body into memory. You can modify the data in
717     * RAM and save the data by calling File::Save() afterwards.
718     *
719     * <b>Caution:</b> the buffer pointer will be invalidated once
720     * File::Save() was called. You have to call LoadChunkData() again to
721 schoenebeck 800 * get a new, valid pointer whenever File::Save() was called.
722 schoenebeck 780 *
723 schoenebeck 800 * You can call LoadChunkData() again if you previously scheduled to
724     * enlarge this chunk with a Resize() call. In that case the buffer will
725     * be enlarged to the new, scheduled chunk size and you can already
726     * place the new chunk data to the buffer and finally call File::Save()
727     * to enlarge the chunk physically and write the new data in one rush.
728     * This approach is definitely recommended if you have to enlarge and
729     * write new data to a lot of chunks.
730     *
731 schoenebeck 780 * @returns a pointer to the data in RAM on success, NULL otherwise
732 schoenebeck 800 * @throws Exception if data buffer could not be enlarged
733 schoenebeck 780 * @see ReleaseChunkData()
734     */
735 schoenebeck 2 void* Chunk::LoadChunkData() {
736 schoenebeck 1851 if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {
737 schoenebeck 2 #if POSIX
738 schoenebeck 780 if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
739 schoenebeck 1050 #elif defined(WIN32)
740     if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;
741 schoenebeck 800 #else
742     if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
743     #endif // POSIX
744     unsigned long ulBufferSize = (CurrentChunkSize > NewChunkSize) ? CurrentChunkSize : NewChunkSize;
745     pChunkData = new uint8_t[ulBufferSize];
746 schoenebeck 2 if (!pChunkData) return NULL;
747 schoenebeck 800 memset(pChunkData, 0, ulBufferSize);
748     #if POSIX
749 schoenebeck 780 unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
750 schoenebeck 1050 #elif defined(WIN32)
751     DWORD readWords;
752     ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
753 schoenebeck 2 #else
754 schoenebeck 780 unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
755 schoenebeck 2 #endif // POSIX
756     if (readWords != GetSize()) {
757     delete[] pChunkData;
758     return (pChunkData = NULL);
759     }
760 schoenebeck 800 ulChunkDataSize = ulBufferSize;
761     } else if (NewChunkSize > ulChunkDataSize) {
762     uint8_t* pNewBuffer = new uint8_t[NewChunkSize];
763     if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(NewChunkSize) + " bytes");
764     memset(pNewBuffer, 0 , NewChunkSize);
765     memcpy(pNewBuffer, pChunkData, ulChunkDataSize);
766     delete[] pChunkData;
767     pChunkData = pNewBuffer;
768     ulChunkDataSize = NewChunkSize;
769 schoenebeck 2 }
770     return pChunkData;
771     }
772    
773 schoenebeck 780 /** @brief Free loaded chunk body from RAM.
774     *
775     * Frees loaded chunk body data from memory (RAM). You should call
776     * File::Save() before calling this method if you modified the data to
777     * make the changes persistent.
778     */
779 schoenebeck 2 void Chunk::ReleaseChunkData() {
780     if (pChunkData) {
781     delete[] pChunkData;
782     pChunkData = NULL;
783     }
784     }
785    
786 schoenebeck 780 /** @brief Resize chunk.
787     *
788     * Resizes this chunk's body, that is the actual size of data possible
789     * to be written to this chunk. This call will return immediately and
790     * just schedule the resize operation. You should call File::Save() to
791     * actually perform the resize operation(s) "physically" to the file.
792     * As this can take a while on large files, it is recommended to call
793     * Resize() first on all chunks which have to be resized and finally to
794     * call File::Save() to perform all those resize operations in one rush.
795     *
796     * <b>Caution:</b> You cannot directly write to enlarged chunks before
797     * calling File::Save() as this might exceed the current chunk's body
798 schoenebeck 800 * boundary!
799 schoenebeck 780 *
800     * @param iNewSize - new chunk body size in bytes (must be greater than zero)
801     * @throws RIFF::Exception if \a iNewSize is less than 1
802     * @see File::Save()
803     */
804     void Chunk::Resize(int iNewSize) {
805 schoenebeck 1105 if (iNewSize <= 0)
806     throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
807 schoenebeck 800 if (NewChunkSize == iNewSize) return;
808 schoenebeck 780 NewChunkSize = iNewSize;
809     pFile->LogAsResized(this);
810     }
811 schoenebeck 2
812 schoenebeck 780 /** @brief Write chunk persistently e.g. to disk.
813     *
814     * Stores the chunk persistently to its actual "physical" file.
815     *
816     * @param ulWritePos - position within the "physical" file where this
817     * chunk should be written to
818     * @param ulCurrentDataOffset - offset of current (old) data within
819     * the file
820     * @returns new write position in the "physical" file, that is
821     * \a ulWritePos incremented by this chunk's new size
822     * (including its header size of course)
823     */
824     unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
825 schoenebeck 798 const unsigned long ulOriginalPos = ulWritePos;
826 schoenebeck 780 ulWritePos += CHUNK_HEADER_SIZE;
827 schoenebeck 2
828 schoenebeck 798 if (pFile->Mode != stream_mode_read_write)
829     throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
830    
831 schoenebeck 780 // if the whole chunk body was loaded into RAM
832     if (pChunkData) {
833 schoenebeck 800 // make sure chunk data buffer in RAM is at least as large as the new chunk size
834     LoadChunkData();
835 schoenebeck 780 // write chunk data from RAM persistently to the file
836     #if POSIX
837     lseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
838     if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
839     throw Exception("Writing Chunk data (from RAM) failed");
840     }
841 schoenebeck 1050 #elif defined(WIN32)
842     SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
843     DWORD dwBytesWritten;
844     WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
845     if (dwBytesWritten != NewChunkSize) {
846     throw Exception("Writing Chunk data (from RAM) failed");
847     }
848 schoenebeck 780 #else
849     fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
850     if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
851     throw Exception("Writing Chunk data (from RAM) failed");
852     }
853     #endif // POSIX
854     } else {
855     // move chunk data from the end of the file to the appropriate position
856     int8_t* pCopyBuffer = new int8_t[4096];
857     unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
858 schoenebeck 1050 #if defined(WIN32)
859     DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
860     #else
861 schoenebeck 780 int iBytesMoved = 1;
862 schoenebeck 1050 #endif
863 schoenebeck 780 for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
864     iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
865     #if POSIX
866     lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
867     iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
868     lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
869     iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
870 schoenebeck 1050 #elif defined(WIN32)
871     SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
872     ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
873     SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
874     WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
875 schoenebeck 780 #else
876     fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
877     iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
878     fseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
879     iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
880     #endif
881     }
882     delete[] pCopyBuffer;
883     if (iBytesMoved < 0) throw Exception("Writing Chunk data (from file) failed");
884     }
885    
886     // update this chunk's header
887     CurrentChunkSize = NewChunkSize;
888     WriteHeader(ulOriginalPos);
889    
890     // update chunk's position pointers
891     ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;
892     ulPos = 0;
893    
894     // add pad byte if needed
895     if ((ulStartPos + NewChunkSize) % 2 != 0) {
896 schoenebeck 798 const char cPadByte = 0;
897 schoenebeck 780 #if POSIX
898 schoenebeck 798 lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
899 schoenebeck 780 write(pFile->hFileWrite, &cPadByte, 1);
900 schoenebeck 1050 #elif defined(WIN32)
901     SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
902     DWORD dwBytesWritten;
903     WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
904 schoenebeck 780 #else
905 schoenebeck 798 fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
906 schoenebeck 780 fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
907     #endif
908     return ulStartPos + NewChunkSize + 1;
909     }
910    
911     return ulStartPos + NewChunkSize;
912     }
913    
914     void Chunk::__resetPos() {
915     ulPos = 0;
916     }
917    
918    
919    
920 schoenebeck 2 // *************** List ***************
921     // *
922    
923 schoenebeck 780 List::List(File* pFile) : Chunk(pFile) {
924 schoenebeck 2 #if DEBUG
925 schoenebeck 780 std::cout << "List::List(File* pFile)" << std::endl;
926 schoenebeck 2 #endif // DEBUG
927     pSubChunks = NULL;
928     pSubChunksMap = NULL;
929     }
930    
931 schoenebeck 780 List::List(File* pFile, unsigned long StartPos, List* Parent)
932     : Chunk(pFile, StartPos, Parent) {
933 schoenebeck 2 #if DEBUG
934 schoenebeck 780 std::cout << "List::List(File*,ulong,bool,List*)" << std::endl;
935 schoenebeck 2 #endif // DEBUG
936     pSubChunks = NULL;
937     pSubChunksMap = NULL;
938     ReadHeader(StartPos);
939     ulStartPos = StartPos + LIST_HEADER_SIZE;
940     }
941    
942 schoenebeck 780 List::List(File* pFile, List* pParent, uint32_t uiListID)
943     : Chunk(pFile, pParent, CHUNK_ID_LIST, 0) {
944     pSubChunks = NULL;
945     pSubChunksMap = NULL;
946     ListType = uiListID;
947     }
948    
949 schoenebeck 2 List::~List() {
950     #if DEBUG
951     std::cout << "List::~List()" << std::endl;
952     #endif // DEBUG
953     if (pSubChunks) {
954     ChunkList::iterator iter = pSubChunks->begin();
955     ChunkList::iterator end = pSubChunks->end();
956     while (iter != end) {
957     delete *iter;
958     iter++;
959     }
960     delete pSubChunks;
961     }
962     if (pSubChunksMap) delete pSubChunksMap;
963     }
964    
965 schoenebeck 11 /**
966     * Returns subchunk with chunk ID <i>\a ChunkID</i> within this chunk
967     * list. Use this method if you expect only one subchunk of that type in
968     * the list. It there are more than one, it's undetermined which one of
969     * them will be returned! If there are no subchunks with that desired
970     * chunk ID, NULL will be returned.
971     *
972     * @param ChunkID - chunk ID of the sought subchunk
973     * @returns pointer to the subchunk or NULL if there is none of
974     * that ID
975     */
976 schoenebeck 2 Chunk* List::GetSubChunk(uint32_t ChunkID) {
977     #if DEBUG
978     std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
979     #endif // DEBUG
980     if (!pSubChunksMap) LoadSubChunks();
981     return (*pSubChunksMap)[ChunkID];
982     }
983    
984 schoenebeck 11 /**
985     * Returns sublist chunk with list type <i>\a ListType</i> within this
986     * chunk list. Use this method if you expect only one sublist chunk of
987     * that type in the list. It there are more than one, it's undetermined
988     * which one of them will be returned! If there are no sublists with
989     * that desired list type, NULL will be returned.
990     *
991     * @param ListType - list type of the sought sublist
992     * @returns pointer to the sublist or NULL if there is none of
993     * that type
994     */
995 schoenebeck 2 List* List::GetSubList(uint32_t ListType) {
996     #if DEBUG
997     std::cout << "List::GetSubList(uint32_t)" << std::endl;
998     #endif // DEBUG
999     if (!pSubChunks) LoadSubChunks();
1000     ChunkList::iterator iter = pSubChunks->begin();
1001     ChunkList::iterator end = pSubChunks->end();
1002     while (iter != end) {
1003     if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1004     List* l = (List*) *iter;
1005     if (l->GetListType() == ListType) return l;
1006     }
1007     iter++;
1008     }
1009     return NULL;
1010     }
1011    
1012 schoenebeck 11 /**
1013     * Returns the first subchunk within the list. You have to call this
1014     * method before you can call GetNextSubChunk(). Recall it when you want
1015     * to start from the beginning of the list again.
1016     *
1017     * @returns pointer to the first subchunk within the list, NULL
1018     * otherwise
1019     */
1020 schoenebeck 2 Chunk* List::GetFirstSubChunk() {
1021     #if DEBUG
1022     std::cout << "List::GetFirstSubChunk()" << std::endl;
1023     #endif // DEBUG
1024     if (!pSubChunks) LoadSubChunks();
1025     ChunksIterator = pSubChunks->begin();
1026     return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1027     }
1028    
1029 schoenebeck 11 /**
1030     * Returns the next subchunk within the list. You have to call
1031     * GetFirstSubChunk() before you can use this method!
1032     *
1033     * @returns pointer to the next subchunk within the list or NULL if
1034     * end of list is reached
1035     */
1036 schoenebeck 2 Chunk* List::GetNextSubChunk() {
1037     #if DEBUG
1038     std::cout << "List::GetNextSubChunk()" << std::endl;
1039     #endif // DEBUG
1040     if (!pSubChunks) return NULL;
1041     ChunksIterator++;
1042     return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1043     }
1044    
1045 schoenebeck 11 /**
1046     * Returns the first sublist within the list (that is a subchunk with
1047     * chunk ID "LIST"). You have to call this method before you can call
1048     * GetNextSubList(). Recall it when you want to start from the beginning
1049     * of the list again.
1050     *
1051     * @returns pointer to the first sublist within the list, NULL
1052     * otherwise
1053     */
1054 schoenebeck 2 List* List::GetFirstSubList() {
1055     #if DEBUG
1056     std::cout << "List::GetFirstSubList()" << std::endl;
1057     #endif // DEBUG
1058     if (!pSubChunks) LoadSubChunks();
1059     ListIterator = pSubChunks->begin();
1060     ChunkList::iterator end = pSubChunks->end();
1061     while (ListIterator != end) {
1062     if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1063     ListIterator++;
1064     }
1065     return NULL;
1066     }
1067    
1068 schoenebeck 11 /**
1069     * Returns the next sublist (that is a subchunk with chunk ID "LIST")
1070     * within the list. You have to call GetFirstSubList() before you can
1071     * use this method!
1072     *
1073     * @returns pointer to the next sublist within the list, NULL if
1074     * end of list is reached
1075     */
1076 schoenebeck 2 List* List::GetNextSubList() {
1077     #if DEBUG
1078     std::cout << "List::GetNextSubList()" << std::endl;
1079     #endif // DEBUG
1080     if (!pSubChunks) return NULL;
1081     if (ListIterator == pSubChunks->end()) return NULL;
1082     ListIterator++;
1083     ChunkList::iterator end = pSubChunks->end();
1084     while (ListIterator != end) {
1085     if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1086     ListIterator++;
1087     }
1088     return NULL;
1089     }
1090    
1091 schoenebeck 11 /**
1092 schoenebeck 515 * Returns number of subchunks within the list.
1093 schoenebeck 11 */
1094 schoenebeck 2 unsigned int List::CountSubChunks() {
1095     if (!pSubChunks) LoadSubChunks();
1096     return pSubChunks->size();
1097     }
1098    
1099 schoenebeck 11 /**
1100     * Returns number of subchunks within the list with chunk ID
1101     * <i>\a ChunkId</i>.
1102     */
1103 schoenebeck 2 unsigned int List::CountSubChunks(uint32_t ChunkID) {
1104     unsigned int result = 0;
1105     if (!pSubChunks) LoadSubChunks();
1106     ChunkList::iterator iter = pSubChunks->begin();
1107     ChunkList::iterator end = pSubChunks->end();
1108     while (iter != end) {
1109     if ((*iter)->GetChunkID() == ChunkID) {
1110     result++;
1111     }
1112     iter++;
1113     }
1114     return result;
1115     }
1116    
1117 schoenebeck 11 /**
1118     * Returns number of sublists within the list.
1119     */
1120 schoenebeck 2 unsigned int List::CountSubLists() {
1121     return CountSubChunks(CHUNK_ID_LIST);
1122     }
1123    
1124 schoenebeck 11 /**
1125     * Returns number of sublists within the list with list type
1126     * <i>\a ListType</i>
1127     */
1128 schoenebeck 2 unsigned int List::CountSubLists(uint32_t ListType) {
1129     unsigned int result = 0;
1130     if (!pSubChunks) LoadSubChunks();
1131     ChunkList::iterator iter = pSubChunks->begin();
1132     ChunkList::iterator end = pSubChunks->end();
1133     while (iter != end) {
1134     if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1135     List* l = (List*) *iter;
1136     if (l->GetListType() == ListType) result++;
1137     }
1138     iter++;
1139     }
1140     return result;
1141     }
1142    
1143 schoenebeck 780 /** @brief Creates a new sub chunk.
1144     *
1145     * Creates and adds a new sub chunk to this list chunk. Note that the
1146     * chunk's body size given by \a uiBodySize must be greater than zero.
1147     * You have to call File::Save() to make this change persistent to the
1148     * actual file and <b>before</b> performing any data write operations
1149     * on the new chunk!
1150     *
1151     * @param uiChunkID - chunk ID of the new chunk
1152     * @param uiBodySize - size of the new chunk's body, that is its actual
1153     * data size (without header)
1154     * @throws RIFF::Exception if \a uiBodySize equals zero
1155     */
1156     Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1157     if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1158     if (!pSubChunks) LoadSubChunks();
1159 schoenebeck 798 Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1160 schoenebeck 780 pSubChunks->push_back(pNewChunk);
1161     (*pSubChunksMap)[uiChunkID] = pNewChunk;
1162 schoenebeck 798 pNewChunk->Resize(uiBodySize);
1163 persson 1678 NewChunkSize += CHUNK_HEADER_SIZE;
1164     pFile->LogAsResized(this);
1165 schoenebeck 780 return pNewChunk;
1166     }
1167    
1168 persson 1102 /** @brief Moves a sub chunk.
1169     *
1170     * Moves a sub chunk from one position in a list to another
1171     * position in the same list. The pSrc chunk is placed before the
1172     * pDst chunk.
1173     *
1174     * @param pSrc - sub chunk to be moved
1175     * @param pDst - the position to move to. pSrc will be placed
1176     * before pDst. If pDst is 0, pSrc will be placed
1177     * last in list.
1178     */
1179     void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1180     if (!pSubChunks) LoadSubChunks();
1181     pSubChunks->remove(pSrc);
1182     ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1183     pSubChunks->insert(iter, pSrc);
1184     }
1185    
1186 schoenebeck 780 /** @brief Creates a new list sub chunk.
1187     *
1188     * Creates and adds a new list sub chunk to this list chunk. Note that
1189     * you have to add sub chunks / sub list chunks to the new created chunk
1190     * <b>before</b> trying to make this change persisten to the actual
1191     * file with File::Save()!
1192     *
1193     * @param uiListType - list ID of the new list chunk
1194     */
1195     List* List::AddSubList(uint32_t uiListType) {
1196     if (!pSubChunks) LoadSubChunks();
1197     List* pNewListChunk = new List(pFile, this, uiListType);
1198     pSubChunks->push_back(pNewListChunk);
1199     (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1200 persson 1678 NewChunkSize += LIST_HEADER_SIZE;
1201     pFile->LogAsResized(this);
1202 schoenebeck 780 return pNewListChunk;
1203     }
1204    
1205     /** @brief Removes a sub chunk.
1206     *
1207     * Removes the sub chunk given by \a pSubChunk from this list and frees
1208     * it completely from RAM. The given chunk can either be a normal sub
1209 schoenebeck 1093 * chunk or a list sub chunk. In case the given chunk is a list chunk,
1210     * all its subchunks (if any) will be removed recursively as well. You
1211     * should call File::Save() to make this change persistent at any time.
1212 schoenebeck 780 *
1213     * @param pSubChunk - sub chunk or sub list chunk to be removed
1214     */
1215     void List::DeleteSubChunk(Chunk* pSubChunk) {
1216     if (!pSubChunks) LoadSubChunks();
1217     pSubChunks->remove(pSubChunk);
1218     if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1219     pSubChunksMap->erase(pSubChunk->GetChunkID());
1220     // try to find another chunk of the same chunk ID
1221     ChunkList::iterator iter = pSubChunks->begin();
1222     ChunkList::iterator end = pSubChunks->end();
1223     for (; iter != end; ++iter) {
1224     if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1225     (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1226     break; // we're done, stop search
1227     }
1228     }
1229     }
1230     delete pSubChunk;
1231     }
1232    
1233 schoenebeck 2 void List::ReadHeader(unsigned long fPos) {
1234     #if DEBUG
1235     std::cout << "List::Readheader(ulong) ";
1236     #endif // DEBUG
1237     Chunk::ReadHeader(fPos);
1238 schoenebeck 1863 if (CurrentChunkSize < 8) return;
1239 schoenebeck 780 NewChunkSize = CurrentChunkSize -= 4;
1240 schoenebeck 2 #if POSIX
1241 schoenebeck 780 lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1242     read(pFile->hFileRead, &ListType, 4);
1243 schoenebeck 1050 #elif defined(WIN32)
1244     SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1245     DWORD dwBytesRead;
1246     ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1247 schoenebeck 2 #else
1248 schoenebeck 780 fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1249     fread(&ListType, 4, 1, pFile->hFileRead);
1250 schoenebeck 2 #endif // POSIX
1251     #if DEBUG
1252     std::cout << "listType=" << convertToString(ListType) << std::endl;
1253     #endif // DEBUG
1254 schoenebeck 780 if (!pFile->bEndianNative) {
1255 schoenebeck 11 //swapBytes_32(&ListType);
1256 schoenebeck 2 }
1257     }
1258    
1259 schoenebeck 780 void List::WriteHeader(unsigned long fPos) {
1260     // the four list type bytes officially belong the chunk's body in the RIFF format
1261     NewChunkSize += 4;
1262     Chunk::WriteHeader(fPos);
1263     NewChunkSize -= 4; // just revert the +4 incrementation
1264     #if POSIX
1265     lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1266     write(pFile->hFileWrite, &ListType, 4);
1267 schoenebeck 1050 #elif defined(WIN32)
1268     SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1269     DWORD dwBytesWritten;
1270     WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1271 schoenebeck 780 #else
1272     fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1273     fwrite(&ListType, 4, 1, pFile->hFileWrite);
1274     #endif // POSIX
1275     }
1276    
1277 schoenebeck 2 void List::LoadSubChunks() {
1278     #if DEBUG
1279     std::cout << "List::LoadSubChunks()";
1280     #endif // DEBUG
1281     if (!pSubChunks) {
1282     pSubChunks = new ChunkList();
1283     pSubChunksMap = new ChunkMap();
1284 persson 1301 #if defined(WIN32)
1285     if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1286     #else
1287 schoenebeck 780 if (!pFile->hFileRead) return;
1288 persson 1301 #endif
1289 schoenebeck 515 unsigned long uiOriginalPos = GetPos();
1290     SetPos(0); // jump to beginning of list chunk body
1291 schoenebeck 2 while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
1292     Chunk* ck;
1293 schoenebeck 11 uint32_t ckid;
1294     Read(&ckid, 4, 1);
1295 schoenebeck 2 #if DEBUG
1296     std::cout << " ckid=" << convertToString(ckid) << std::endl;
1297     #endif // DEBUG
1298     if (ckid == CHUNK_ID_LIST) {
1299 schoenebeck 780 ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);
1300 schoenebeck 2 SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);
1301     }
1302     else { // simple chunk
1303 schoenebeck 780 ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);
1304 schoenebeck 2 SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);
1305     }
1306     pSubChunks->push_back(ck);
1307     (*pSubChunksMap)[ckid] = ck;
1308     if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte
1309     }
1310 schoenebeck 515 SetPos(uiOriginalPos); // restore position before this call
1311 schoenebeck 2 }
1312     }
1313    
1314 schoenebeck 833 void List::LoadSubChunksRecursively() {
1315     for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1316     pList->LoadSubChunksRecursively();
1317     }
1318    
1319 schoenebeck 780 /** @brief Write list chunk persistently e.g. to disk.
1320     *
1321     * Stores the list chunk persistently to its actual "physical" file. All
1322     * subchunks (including sub list chunks) will be stored recursively as
1323     * well.
1324     *
1325     * @param ulWritePos - position within the "physical" file where this
1326     * list chunk should be written to
1327     * @param ulCurrentDataOffset - offset of current (old) data within
1328     * the file
1329     * @returns new write position in the "physical" file, that is
1330     * \a ulWritePos incremented by this list chunk's new size
1331     * (including its header size of course)
1332     */
1333     unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1334 schoenebeck 798 const unsigned long ulOriginalPos = ulWritePos;
1335 schoenebeck 780 ulWritePos += LIST_HEADER_SIZE;
1336    
1337 schoenebeck 798 if (pFile->Mode != stream_mode_read_write)
1338     throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1339    
1340 schoenebeck 780 // write all subchunks (including sub list chunks) recursively
1341     if (pSubChunks) {
1342     for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1343     ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);
1344     }
1345     }
1346    
1347     // update this list chunk's header
1348     CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1349     WriteHeader(ulOriginalPos);
1350    
1351 schoenebeck 798 // offset of this list chunk in new written file may have changed
1352     ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1353    
1354 schoenebeck 780 return ulWritePos;
1355     }
1356    
1357     void List::__resetPos() {
1358     Chunk::__resetPos();
1359     if (pSubChunks) {
1360     for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1361     (*iter)->__resetPos();
1362     }
1363     }
1364     }
1365    
1366 schoenebeck 11 /**
1367     * Returns string representation of the lists's id
1368     */
1369 schoenebeck 2 String List::GetListTypeString() {
1370     return convertToString(ListType);
1371     }
1372    
1373    
1374    
1375     // *************** File ***************
1376     // *
1377    
1378 schoenebeck 780 /** @brief Create new RIFF file.
1379     *
1380     * Use this constructor if you want to create a new RIFF file completely
1381     * "from scratch". Note: there must be no empty chunks or empty list
1382     * chunks when trying to make the new RIFF file persistent with Save()!
1383     *
1384 persson 1207 * Note: by default, the RIFF file will be saved in native endian
1385     * format; that is, as a RIFF file on little-endian machines and
1386     * as a RIFX file on big-endian. To change this behaviour, call
1387     * SetByteOrder() before calling Save().
1388     *
1389 schoenebeck 798 * @param FileType - four-byte identifier of the RIFF file type
1390 persson 1207 * @see AddSubChunk(), AddSubList(), SetByteOrder()
1391 schoenebeck 780 */
1392 schoenebeck 798 File::File(uint32_t FileType) : List(this) {
1393 schoenebeck 1050 #if defined(WIN32)
1394     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1395     #else
1396 schoenebeck 780 hFileRead = hFileWrite = 0;
1397 schoenebeck 1050 #endif
1398 schoenebeck 798 Mode = stream_mode_closed;
1399 schoenebeck 780 bEndianNative = true;
1400     ulStartPos = RIFF_HEADER_SIZE;
1401 schoenebeck 798 ListType = FileType;
1402 schoenebeck 780 }
1403    
1404     /** @brief Load existing RIFF file.
1405     *
1406     * Loads an existing RIFF file with all its chunks.
1407     *
1408     * @param path - path and file name of the RIFF file to open
1409     * @throws RIFF::Exception if error occured while trying to load the
1410     * given RIFF file
1411     */
1412     File::File(const String& path) : List(this), Filename(path) {
1413 schoenebeck 2 #if DEBUG
1414     std::cout << "File::File("<<path<<")" << std::endl;
1415     #endif // DEBUG
1416     bEndianNative = true;
1417     #if POSIX
1418 schoenebeck 780 hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1419     if (hFileRead <= 0) {
1420     hFileRead = hFileWrite = 0;
1421 schoenebeck 2 throw RIFF::Exception("Can't open \"" + path + "\"");
1422     }
1423 schoenebeck 1050 #elif defined(WIN32)
1424     hFileRead = hFileWrite = CreateFile(
1425     path.c_str(), GENERIC_READ,
1426     FILE_SHARE_READ | FILE_SHARE_WRITE,
1427     NULL, OPEN_EXISTING,
1428 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1429     FILE_FLAG_RANDOM_ACCESS, NULL
1430 schoenebeck 1050 );
1431     if (hFileRead == INVALID_HANDLE_VALUE) {
1432     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1433     throw RIFF::Exception("Can't open \"" + path + "\"");
1434     }
1435 schoenebeck 2 #else
1436 schoenebeck 780 hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1437 schoenebeck 1050 if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1438 schoenebeck 2 #endif // POSIX
1439 schoenebeck 798 Mode = stream_mode_read;
1440 schoenebeck 2 ulStartPos = RIFF_HEADER_SIZE;
1441     ReadHeader(0);
1442 schoenebeck 1863 if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1443 schoenebeck 2 throw RIFF::Exception("Not a RIFF file");
1444     }
1445     }
1446    
1447 schoenebeck 780 String File::GetFileName() {
1448     return Filename;
1449     }
1450    
1451     stream_mode_t File::GetMode() {
1452     return Mode;
1453     }
1454    
1455     /** @brief Change file access mode.
1456     *
1457     * Changes files access mode either to read-only mode or to read/write
1458     * mode.
1459     *
1460     * @param NewMode - new file access mode
1461     * @returns true if mode was changed, false if current mode already
1462     * equals new mode
1463     * @throws RIFF::Exception if new file access mode is unknown
1464     */
1465     bool File::SetMode(stream_mode_t NewMode) {
1466     if (NewMode != Mode) {
1467     switch (NewMode) {
1468     case stream_mode_read:
1469     #if POSIX
1470     if (hFileRead) close(hFileRead);
1471     hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1472     if (hFileRead < 0) {
1473     hFileRead = hFileWrite = 0;
1474     throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1475     }
1476 schoenebeck 1050 #elif defined(WIN32)
1477     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1478     hFileRead = hFileWrite = CreateFile(
1479     Filename.c_str(), GENERIC_READ,
1480     FILE_SHARE_READ | FILE_SHARE_WRITE,
1481     NULL, OPEN_EXISTING,
1482 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1483     FILE_FLAG_RANDOM_ACCESS,
1484     NULL
1485 schoenebeck 1050 );
1486     if (hFileRead == INVALID_HANDLE_VALUE) {
1487     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1488     throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1489     }
1490 schoenebeck 780 #else
1491     if (hFileRead) fclose(hFileRead);
1492 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1493 schoenebeck 780 if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1494     #endif
1495     __resetPos(); // reset read/write position of ALL 'Chunk' objects
1496 schoenebeck 798 break;
1497 schoenebeck 780 case stream_mode_read_write:
1498     #if POSIX
1499     if (hFileRead) close(hFileRead);
1500     hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1501     if (hFileRead < 0) {
1502     hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1503     throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1504     }
1505 schoenebeck 1050 #elif defined(WIN32)
1506     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1507     hFileRead = hFileWrite = CreateFile(
1508     Filename.c_str(),
1509     GENERIC_READ | GENERIC_WRITE,
1510     FILE_SHARE_READ,
1511     NULL, OPEN_ALWAYS,
1512 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1513     FILE_FLAG_RANDOM_ACCESS,
1514     NULL
1515 schoenebeck 1050 );
1516     if (hFileRead == INVALID_HANDLE_VALUE) {
1517     hFileRead = hFileWrite = CreateFile(
1518     Filename.c_str(), GENERIC_READ,
1519     FILE_SHARE_READ | FILE_SHARE_WRITE,
1520     NULL, OPEN_EXISTING,
1521 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1522     FILE_FLAG_RANDOM_ACCESS,
1523     NULL
1524 schoenebeck 1050 );
1525 persson 1301 throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1526 schoenebeck 1050 }
1527 schoenebeck 780 #else
1528     if (hFileRead) fclose(hFileRead);
1529 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1530 schoenebeck 780 if (!hFileRead) {
1531 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1532 schoenebeck 780 throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1533     }
1534     #endif
1535     __resetPos(); // reset read/write position of ALL 'Chunk' objects
1536 schoenebeck 798 break;
1537     case stream_mode_closed:
1538     #if POSIX
1539     if (hFileRead) close(hFileRead);
1540     if (hFileWrite) close(hFileWrite);
1541 schoenebeck 1050 #elif defined(WIN32)
1542     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1543     if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1544 schoenebeck 798 #else
1545     if (hFileRead) fclose(hFileRead);
1546     if (hFileWrite) fclose(hFileWrite);
1547     #endif
1548     hFileRead = hFileWrite = 0;
1549     break;
1550 schoenebeck 780 default:
1551     throw Exception("Unknown file access mode");
1552     }
1553 schoenebeck 798 Mode = NewMode;
1554     return true;
1555 schoenebeck 780 }
1556     return false;
1557     }
1558    
1559 persson 1184 /** @brief Set the byte order to be used when saving.
1560     *
1561     * Set the byte order to be used in the file. A value of
1562     * endian_little will create a RIFF file, endian_big a RIFX file
1563     * and endian_native will create a RIFF file on little-endian
1564     * machines and RIFX on big-endian machines.
1565     *
1566     * @param Endian - endianess to use when file is saved.
1567     */
1568     void File::SetByteOrder(endian_t Endian) {
1569     #if WORDS_BIGENDIAN
1570     bEndianNative = Endian != endian_little;
1571     #else
1572     bEndianNative = Endian != endian_big;
1573     #endif
1574     }
1575    
1576 schoenebeck 780 /** @brief Save changes to same file.
1577     *
1578     * Make all changes of all chunks persistent by writing them to the
1579     * actual (same) file. The file might temporarily grow to a higher size
1580     * than it will have at the end of the saving process, in case chunks
1581     * were grown.
1582     *
1583     * @throws RIFF::Exception if there is an empty chunk or empty list
1584     * chunk or any kind of IO error occured
1585     */
1586     void File::Save() {
1587 schoenebeck 833 // make sure the RIFF tree is built (from the original file)
1588     LoadSubChunksRecursively();
1589    
1590 schoenebeck 780 // reopen file in write mode
1591 schoenebeck 798 SetMode(stream_mode_read_write);
1592 schoenebeck 780
1593     // to be able to save the whole file without loading everything into
1594     // RAM and without having to store the data in a temporary file, we
1595     // enlarge the file with the sum of all _positive_ chunk size
1596     // changes, move current data towards the end of the file with the
1597     // calculated sum and finally update / rewrite the file by copying
1598     // the old data back to the right position at the beginning of the file
1599    
1600     // first we sum up all positive chunk size changes (and skip all negative ones)
1601     unsigned long ulPositiveSizeDiff = 0;
1602 persson 1678 for (std::set<Chunk*>::const_iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1603 schoenebeck 1095 if ((*iter)->GetNewSize() == 0) {
1604 schoenebeck 1105 throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
1605 schoenebeck 1095 }
1606 persson 1859 unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1607     unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1608     if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1609 schoenebeck 780 }
1610    
1611     unsigned long ulWorkingFileSize = GetFileSize();
1612    
1613     // if there are positive size changes...
1614     if (ulPositiveSizeDiff > 0) {
1615     // ... we enlarge this file first ...
1616     ulWorkingFileSize += ulPositiveSizeDiff;
1617     ResizeFile(ulWorkingFileSize);
1618     // ... and move current data by the same amount towards end of file.
1619     int8_t* pCopyBuffer = new int8_t[4096];
1620     const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1621 schoenebeck 1050 #if defined(WIN32)
1622     DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1623     #else
1624 schoenebeck 1459 int iBytesMoved = 1;
1625 schoenebeck 1050 #endif
1626 persson 1678 for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1627     iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1628     ulPos -= iBytesMoved;
1629 schoenebeck 780 #if POSIX
1630     lseek(hFileRead, ulPos, SEEK_SET);
1631     iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1632     lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1633     iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1634 schoenebeck 1050 #elif defined(WIN32)
1635     SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1636     ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1637     SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1638     WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1639 schoenebeck 780 #else
1640     fseek(hFileRead, ulPos, SEEK_SET);
1641     iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1642     fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1643     iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1644     #endif
1645     }
1646     delete[] pCopyBuffer;
1647     if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1648     }
1649    
1650     // rebuild / rewrite complete RIFF tree
1651 schoenebeck 798 unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff);
1652     unsigned long ulActualSize = __GetFileSize(hFileWrite);
1653 schoenebeck 780
1654     // resize file to the final size
1655 schoenebeck 798 if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1656 schoenebeck 780
1657     // forget all resized chunks
1658     ResizedChunks.clear();
1659     }
1660    
1661     /** @brief Save changes to another file.
1662     *
1663     * Make all changes of all chunks persistent by writing them to another
1664     * file. <b>Caution:</b> this method is optimized for writing to
1665     * <b>another</b> file, do not use it to save the changes to the same
1666 schoenebeck 798 * file! Use File::Save() in that case instead! Ignoring this might
1667     * result in a corrupted file, especially in case chunks were resized!
1668 schoenebeck 780 *
1669     * After calling this method, this File object will be associated with
1670     * the new file (given by \a path) afterwards.
1671     *
1672     * @param path - path and file name where everything should be written to
1673     */
1674     void File::Save(const String& path) {
1675 schoenebeck 798 //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
1676    
1677 schoenebeck 833 // make sure the RIFF tree is built (from the original file)
1678     LoadSubChunksRecursively();
1679    
1680 schoenebeck 798 if (Filename.length() > 0) SetMode(stream_mode_read);
1681 schoenebeck 780 // open the other (new) file for writing and truncate it to zero size
1682     #if POSIX
1683 schoenebeck 798 hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1684 schoenebeck 780 if (hFileWrite < 0) {
1685     hFileWrite = hFileRead;
1686     throw Exception("Could not open file \"" + path + "\" for writing");
1687     }
1688 schoenebeck 1050 #elif defined(WIN32)
1689     hFileWrite = CreateFile(
1690     path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1691 schoenebeck 1459 NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1692     FILE_FLAG_RANDOM_ACCESS, NULL
1693 schoenebeck 1050 );
1694     if (hFileWrite == INVALID_HANDLE_VALUE) {
1695     hFileWrite = hFileRead;
1696     throw Exception("Could not open file \"" + path + "\" for writing");
1697     }
1698 schoenebeck 780 #else
1699     hFileWrite = fopen(path.c_str(), "w+b");
1700     if (!hFileWrite) {
1701     hFileWrite = hFileRead;
1702     throw Exception("Could not open file \"" + path + "\" for writing");
1703     }
1704     #endif // POSIX
1705 schoenebeck 798 Mode = stream_mode_read_write;
1706 schoenebeck 780
1707     // write complete RIFF tree to the other (new) file
1708 schoenebeck 798 unsigned long ulTotalSize = WriteChunk(0, 0);
1709     unsigned long ulActualSize = __GetFileSize(hFileWrite);
1710 schoenebeck 780
1711 schoenebeck 798 // resize file to the final size (if the file was originally larger)
1712     if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1713    
1714 schoenebeck 780 // forget all resized chunks
1715     ResizedChunks.clear();
1716    
1717 persson 1301 #if POSIX
1718     if (hFileWrite) close(hFileWrite);
1719     #elif defined(WIN32)
1720     if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1721     #else
1722     if (hFileWrite) fclose(hFileWrite);
1723     #endif
1724     hFileWrite = hFileRead;
1725 schoenebeck 798
1726 schoenebeck 780 // associate new file with this File object from now on
1727     Filename = path;
1728 schoenebeck 798 Mode = (stream_mode_t) -1; // Just set it to an undefined mode ...
1729     SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
1730 schoenebeck 780 }
1731    
1732     void File::ResizeFile(unsigned long ulNewSize) {
1733     #if POSIX
1734     if (ftruncate(hFileWrite, ulNewSize) < 0)
1735     throw Exception("Could not resize file \"" + Filename + "\"");
1736 schoenebeck 1050 #elif defined(WIN32)
1737     if (
1738     SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1739     !SetEndOfFile(hFileWrite)
1740     ) throw Exception("Could not resize file \"" + Filename + "\"");
1741 schoenebeck 780 #else
1742 schoenebeck 1050 # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1743 schoenebeck 798 # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1744 schoenebeck 780 #endif
1745     }
1746    
1747 schoenebeck 2 File::~File() {
1748     #if DEBUG
1749     std::cout << "File::~File()" << std::endl;
1750     #endif // DEBUG
1751     #if POSIX
1752 schoenebeck 780 if (hFileRead) close(hFileRead);
1753 schoenebeck 1050 #elif defined(WIN32)
1754     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1755 schoenebeck 2 #else
1756 schoenebeck 780 if (hFileRead) fclose(hFileRead);
1757 schoenebeck 2 #endif // POSIX
1758     }
1759    
1760 schoenebeck 780 void File::LogAsResized(Chunk* pResizedChunk) {
1761 persson 1678 ResizedChunks.insert(pResizedChunk);
1762 schoenebeck 780 }
1763    
1764 schoenebeck 1095 void File::UnlogResized(Chunk* pResizedChunk) {
1765 persson 1678 ResizedChunks.erase(pResizedChunk);
1766 schoenebeck 1095 }
1767    
1768 schoenebeck 2 unsigned long File::GetFileSize() {
1769 schoenebeck 798 return __GetFileSize(hFileRead);
1770     }
1771    
1772     #if POSIX
1773     unsigned long File::__GetFileSize(int hFile) {
1774 schoenebeck 2 struct stat filestat;
1775 schoenebeck 798 fstat(hFile, &filestat);
1776 schoenebeck 2 long size = filestat.st_size;
1777     return size;
1778     }
1779 schoenebeck 1050 #elif defined(WIN32)
1780     unsigned long File::__GetFileSize(HANDLE hFile) {
1781 schoenebeck 1063 DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1782     if (dwSize == INVALID_FILE_SIZE)
1783     throw Exception("Windows FS error: could not determine file size");
1784     return dwSize;
1785 schoenebeck 1050 }
1786 schoenebeck 798 #else // standard C functions
1787     unsigned long File::__GetFileSize(FILE* hFile) {
1788     long curpos = ftell(hFile);
1789     fseek(hFile, 0, SEEK_END);
1790     long size = ftell(hFile);
1791     fseek(hFile, curpos, SEEK_SET);
1792     return size;
1793     }
1794     #endif
1795 schoenebeck 2
1796    
1797     // *************** Exception ***************
1798     // *
1799    
1800     void Exception::PrintMessage() {
1801     std::cout << "RIFF::Exception: " << Message << std::endl;
1802     }
1803    
1804 schoenebeck 518
1805     // *************** functions ***************
1806     // *
1807    
1808     /**
1809     * Returns the name of this C++ library. This is usually "libgig" of
1810     * course. This call is equivalent to DLS::libraryName() and
1811     * gig::libraryName().
1812     */
1813     String libraryName() {
1814     return PACKAGE;
1815     }
1816    
1817     /**
1818     * Returns version of this C++ library. This call is equivalent to
1819     * DLS::libraryVersion() and gig::libraryVersion().
1820     */
1821     String libraryVersion() {
1822     return VERSION;
1823     }
1824    
1825 schoenebeck 2 } // namespace RIFF

  ViewVC Help
Powered by ViewVC