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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1869 - (hide annotations) (download)
Sun Mar 22 11:13:25 2009 UTC (15 years, 1 month ago) by persson
File size: 75638 byte(s)
* bugfix: destructor for base class RIFF::Chunk accessed members of
  derived class RIFF::File, which is bad, and caused crashes when
  using Visual C++
* bugfix: EG3 depth parameter was not saved correctly
* fixes for building with Visual C++

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 1869 if (pFile) 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 persson 1869 DeleteChunkList();
954     }
955    
956     void List::DeleteChunkList() {
957 schoenebeck 2 if (pSubChunks) {
958     ChunkList::iterator iter = pSubChunks->begin();
959     ChunkList::iterator end = pSubChunks->end();
960     while (iter != end) {
961     delete *iter;
962     iter++;
963     }
964     delete pSubChunks;
965 persson 1869 pSubChunks = NULL;
966 schoenebeck 2 }
967 persson 1869 if (pSubChunksMap) {
968     delete pSubChunksMap;
969     pSubChunksMap = NULL;
970     }
971 schoenebeck 2 }
972    
973 schoenebeck 11 /**
974     * Returns subchunk with chunk ID <i>\a ChunkID</i> within this chunk
975     * list. Use this method if you expect only one subchunk of that type in
976     * the list. It there are more than one, it's undetermined which one of
977     * them will be returned! If there are no subchunks with that desired
978     * chunk ID, NULL will be returned.
979     *
980     * @param ChunkID - chunk ID of the sought subchunk
981     * @returns pointer to the subchunk or NULL if there is none of
982     * that ID
983     */
984 schoenebeck 2 Chunk* List::GetSubChunk(uint32_t ChunkID) {
985     #if DEBUG
986     std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
987     #endif // DEBUG
988     if (!pSubChunksMap) LoadSubChunks();
989     return (*pSubChunksMap)[ChunkID];
990     }
991    
992 schoenebeck 11 /**
993     * Returns sublist chunk with list type <i>\a ListType</i> within this
994     * chunk list. Use this method if you expect only one sublist chunk of
995     * that type in the list. It there are more than one, it's undetermined
996     * which one of them will be returned! If there are no sublists with
997     * that desired list type, NULL will be returned.
998     *
999     * @param ListType - list type of the sought sublist
1000     * @returns pointer to the sublist or NULL if there is none of
1001     * that type
1002     */
1003 schoenebeck 2 List* List::GetSubList(uint32_t ListType) {
1004     #if DEBUG
1005     std::cout << "List::GetSubList(uint32_t)" << std::endl;
1006     #endif // DEBUG
1007     if (!pSubChunks) LoadSubChunks();
1008     ChunkList::iterator iter = pSubChunks->begin();
1009     ChunkList::iterator end = pSubChunks->end();
1010     while (iter != end) {
1011     if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1012     List* l = (List*) *iter;
1013     if (l->GetListType() == ListType) return l;
1014     }
1015     iter++;
1016     }
1017     return NULL;
1018     }
1019    
1020 schoenebeck 11 /**
1021     * Returns the first subchunk within the list. You have to call this
1022     * method before you can call GetNextSubChunk(). Recall it when you want
1023     * to start from the beginning of the list again.
1024     *
1025     * @returns pointer to the first subchunk within the list, NULL
1026     * otherwise
1027     */
1028 schoenebeck 2 Chunk* List::GetFirstSubChunk() {
1029     #if DEBUG
1030     std::cout << "List::GetFirstSubChunk()" << std::endl;
1031     #endif // DEBUG
1032     if (!pSubChunks) LoadSubChunks();
1033     ChunksIterator = pSubChunks->begin();
1034     return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1035     }
1036    
1037 schoenebeck 11 /**
1038     * Returns the next subchunk within the list. You have to call
1039     * GetFirstSubChunk() before you can use this method!
1040     *
1041     * @returns pointer to the next subchunk within the list or NULL if
1042     * end of list is reached
1043     */
1044 schoenebeck 2 Chunk* List::GetNextSubChunk() {
1045     #if DEBUG
1046     std::cout << "List::GetNextSubChunk()" << std::endl;
1047     #endif // DEBUG
1048     if (!pSubChunks) return NULL;
1049     ChunksIterator++;
1050     return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1051     }
1052    
1053 schoenebeck 11 /**
1054     * Returns the first sublist within the list (that is a subchunk with
1055     * chunk ID "LIST"). You have to call this method before you can call
1056     * GetNextSubList(). Recall it when you want to start from the beginning
1057     * of the list again.
1058     *
1059     * @returns pointer to the first sublist within the list, NULL
1060     * otherwise
1061     */
1062 schoenebeck 2 List* List::GetFirstSubList() {
1063     #if DEBUG
1064     std::cout << "List::GetFirstSubList()" << std::endl;
1065     #endif // DEBUG
1066     if (!pSubChunks) LoadSubChunks();
1067     ListIterator = pSubChunks->begin();
1068     ChunkList::iterator end = pSubChunks->end();
1069     while (ListIterator != end) {
1070     if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1071     ListIterator++;
1072     }
1073     return NULL;
1074     }
1075    
1076 schoenebeck 11 /**
1077     * Returns the next sublist (that is a subchunk with chunk ID "LIST")
1078     * within the list. You have to call GetFirstSubList() before you can
1079     * use this method!
1080     *
1081     * @returns pointer to the next sublist within the list, NULL if
1082     * end of list is reached
1083     */
1084 schoenebeck 2 List* List::GetNextSubList() {
1085     #if DEBUG
1086     std::cout << "List::GetNextSubList()" << std::endl;
1087     #endif // DEBUG
1088     if (!pSubChunks) return NULL;
1089     if (ListIterator == pSubChunks->end()) return NULL;
1090     ListIterator++;
1091     ChunkList::iterator end = pSubChunks->end();
1092     while (ListIterator != end) {
1093     if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1094     ListIterator++;
1095     }
1096     return NULL;
1097     }
1098    
1099 schoenebeck 11 /**
1100 schoenebeck 515 * Returns number of subchunks within the list.
1101 schoenebeck 11 */
1102 schoenebeck 2 unsigned int List::CountSubChunks() {
1103     if (!pSubChunks) LoadSubChunks();
1104     return pSubChunks->size();
1105     }
1106    
1107 schoenebeck 11 /**
1108     * Returns number of subchunks within the list with chunk ID
1109     * <i>\a ChunkId</i>.
1110     */
1111 schoenebeck 2 unsigned int List::CountSubChunks(uint32_t ChunkID) {
1112     unsigned int result = 0;
1113     if (!pSubChunks) LoadSubChunks();
1114     ChunkList::iterator iter = pSubChunks->begin();
1115     ChunkList::iterator end = pSubChunks->end();
1116     while (iter != end) {
1117     if ((*iter)->GetChunkID() == ChunkID) {
1118     result++;
1119     }
1120     iter++;
1121     }
1122     return result;
1123     }
1124    
1125 schoenebeck 11 /**
1126     * Returns number of sublists within the list.
1127     */
1128 schoenebeck 2 unsigned int List::CountSubLists() {
1129     return CountSubChunks(CHUNK_ID_LIST);
1130     }
1131    
1132 schoenebeck 11 /**
1133     * Returns number of sublists within the list with list type
1134     * <i>\a ListType</i>
1135     */
1136 schoenebeck 2 unsigned int List::CountSubLists(uint32_t ListType) {
1137     unsigned int result = 0;
1138     if (!pSubChunks) LoadSubChunks();
1139     ChunkList::iterator iter = pSubChunks->begin();
1140     ChunkList::iterator end = pSubChunks->end();
1141     while (iter != end) {
1142     if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1143     List* l = (List*) *iter;
1144     if (l->GetListType() == ListType) result++;
1145     }
1146     iter++;
1147     }
1148     return result;
1149     }
1150    
1151 schoenebeck 780 /** @brief Creates a new sub chunk.
1152     *
1153     * Creates and adds a new sub chunk to this list chunk. Note that the
1154     * chunk's body size given by \a uiBodySize must be greater than zero.
1155     * You have to call File::Save() to make this change persistent to the
1156     * actual file and <b>before</b> performing any data write operations
1157     * on the new chunk!
1158     *
1159     * @param uiChunkID - chunk ID of the new chunk
1160     * @param uiBodySize - size of the new chunk's body, that is its actual
1161     * data size (without header)
1162     * @throws RIFF::Exception if \a uiBodySize equals zero
1163     */
1164     Chunk* List::AddSubChunk(uint32_t uiChunkID, uint uiBodySize) {
1165     if (uiBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1166     if (!pSubChunks) LoadSubChunks();
1167 schoenebeck 798 Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1168 schoenebeck 780 pSubChunks->push_back(pNewChunk);
1169     (*pSubChunksMap)[uiChunkID] = pNewChunk;
1170 schoenebeck 798 pNewChunk->Resize(uiBodySize);
1171 persson 1678 NewChunkSize += CHUNK_HEADER_SIZE;
1172     pFile->LogAsResized(this);
1173 schoenebeck 780 return pNewChunk;
1174     }
1175    
1176 persson 1102 /** @brief Moves a sub chunk.
1177     *
1178     * Moves a sub chunk from one position in a list to another
1179     * position in the same list. The pSrc chunk is placed before the
1180     * pDst chunk.
1181     *
1182     * @param pSrc - sub chunk to be moved
1183     * @param pDst - the position to move to. pSrc will be placed
1184     * before pDst. If pDst is 0, pSrc will be placed
1185     * last in list.
1186     */
1187     void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1188     if (!pSubChunks) LoadSubChunks();
1189     pSubChunks->remove(pSrc);
1190     ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1191     pSubChunks->insert(iter, pSrc);
1192     }
1193    
1194 schoenebeck 780 /** @brief Creates a new list sub chunk.
1195     *
1196     * Creates and adds a new list sub chunk to this list chunk. Note that
1197     * you have to add sub chunks / sub list chunks to the new created chunk
1198     * <b>before</b> trying to make this change persisten to the actual
1199     * file with File::Save()!
1200     *
1201     * @param uiListType - list ID of the new list chunk
1202     */
1203     List* List::AddSubList(uint32_t uiListType) {
1204     if (!pSubChunks) LoadSubChunks();
1205     List* pNewListChunk = new List(pFile, this, uiListType);
1206     pSubChunks->push_back(pNewListChunk);
1207     (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1208 persson 1678 NewChunkSize += LIST_HEADER_SIZE;
1209     pFile->LogAsResized(this);
1210 schoenebeck 780 return pNewListChunk;
1211     }
1212    
1213     /** @brief Removes a sub chunk.
1214     *
1215     * Removes the sub chunk given by \a pSubChunk from this list and frees
1216     * it completely from RAM. The given chunk can either be a normal sub
1217 schoenebeck 1093 * chunk or a list sub chunk. In case the given chunk is a list chunk,
1218     * all its subchunks (if any) will be removed recursively as well. You
1219     * should call File::Save() to make this change persistent at any time.
1220 schoenebeck 780 *
1221     * @param pSubChunk - sub chunk or sub list chunk to be removed
1222     */
1223     void List::DeleteSubChunk(Chunk* pSubChunk) {
1224     if (!pSubChunks) LoadSubChunks();
1225     pSubChunks->remove(pSubChunk);
1226     if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1227     pSubChunksMap->erase(pSubChunk->GetChunkID());
1228     // try to find another chunk of the same chunk ID
1229     ChunkList::iterator iter = pSubChunks->begin();
1230     ChunkList::iterator end = pSubChunks->end();
1231     for (; iter != end; ++iter) {
1232     if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1233     (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1234     break; // we're done, stop search
1235     }
1236     }
1237     }
1238     delete pSubChunk;
1239     }
1240    
1241 schoenebeck 2 void List::ReadHeader(unsigned long fPos) {
1242     #if DEBUG
1243     std::cout << "List::Readheader(ulong) ";
1244     #endif // DEBUG
1245     Chunk::ReadHeader(fPos);
1246 schoenebeck 1863 if (CurrentChunkSize < 8) return;
1247 schoenebeck 780 NewChunkSize = CurrentChunkSize -= 4;
1248 schoenebeck 2 #if POSIX
1249 schoenebeck 780 lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1250     read(pFile->hFileRead, &ListType, 4);
1251 schoenebeck 1050 #elif defined(WIN32)
1252     SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1253     DWORD dwBytesRead;
1254     ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1255 schoenebeck 2 #else
1256 schoenebeck 780 fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1257     fread(&ListType, 4, 1, pFile->hFileRead);
1258 schoenebeck 2 #endif // POSIX
1259     #if DEBUG
1260     std::cout << "listType=" << convertToString(ListType) << std::endl;
1261     #endif // DEBUG
1262 schoenebeck 780 if (!pFile->bEndianNative) {
1263 schoenebeck 11 //swapBytes_32(&ListType);
1264 schoenebeck 2 }
1265     }
1266    
1267 schoenebeck 780 void List::WriteHeader(unsigned long fPos) {
1268     // the four list type bytes officially belong the chunk's body in the RIFF format
1269     NewChunkSize += 4;
1270     Chunk::WriteHeader(fPos);
1271     NewChunkSize -= 4; // just revert the +4 incrementation
1272     #if POSIX
1273     lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1274     write(pFile->hFileWrite, &ListType, 4);
1275 schoenebeck 1050 #elif defined(WIN32)
1276     SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1277     DWORD dwBytesWritten;
1278     WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1279 schoenebeck 780 #else
1280     fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1281     fwrite(&ListType, 4, 1, pFile->hFileWrite);
1282     #endif // POSIX
1283     }
1284    
1285 schoenebeck 2 void List::LoadSubChunks() {
1286     #if DEBUG
1287     std::cout << "List::LoadSubChunks()";
1288     #endif // DEBUG
1289     if (!pSubChunks) {
1290     pSubChunks = new ChunkList();
1291     pSubChunksMap = new ChunkMap();
1292 persson 1301 #if defined(WIN32)
1293     if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1294     #else
1295 schoenebeck 780 if (!pFile->hFileRead) return;
1296 persson 1301 #endif
1297 schoenebeck 515 unsigned long uiOriginalPos = GetPos();
1298     SetPos(0); // jump to beginning of list chunk body
1299 schoenebeck 2 while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
1300     Chunk* ck;
1301 schoenebeck 11 uint32_t ckid;
1302     Read(&ckid, 4, 1);
1303 schoenebeck 2 #if DEBUG
1304     std::cout << " ckid=" << convertToString(ckid) << std::endl;
1305     #endif // DEBUG
1306     if (ckid == CHUNK_ID_LIST) {
1307 schoenebeck 780 ck = new RIFF::List(pFile, ulStartPos + ulPos - 4, this);
1308 schoenebeck 2 SetPos(ck->GetSize() + LIST_HEADER_SIZE - 4, RIFF::stream_curpos);
1309     }
1310     else { // simple chunk
1311 schoenebeck 780 ck = new RIFF::Chunk(pFile, ulStartPos + ulPos - 4, this);
1312 schoenebeck 2 SetPos(ck->GetSize() + CHUNK_HEADER_SIZE - 4, RIFF::stream_curpos);
1313     }
1314     pSubChunks->push_back(ck);
1315     (*pSubChunksMap)[ckid] = ck;
1316     if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte
1317     }
1318 schoenebeck 515 SetPos(uiOriginalPos); // restore position before this call
1319 schoenebeck 2 }
1320     }
1321    
1322 schoenebeck 833 void List::LoadSubChunksRecursively() {
1323     for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1324     pList->LoadSubChunksRecursively();
1325     }
1326    
1327 schoenebeck 780 /** @brief Write list chunk persistently e.g. to disk.
1328     *
1329     * Stores the list chunk persistently to its actual "physical" file. All
1330     * subchunks (including sub list chunks) will be stored recursively as
1331     * well.
1332     *
1333     * @param ulWritePos - position within the "physical" file where this
1334     * list chunk should be written to
1335     * @param ulCurrentDataOffset - offset of current (old) data within
1336     * the file
1337     * @returns new write position in the "physical" file, that is
1338     * \a ulWritePos incremented by this list chunk's new size
1339     * (including its header size of course)
1340     */
1341     unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {
1342 schoenebeck 798 const unsigned long ulOriginalPos = ulWritePos;
1343 schoenebeck 780 ulWritePos += LIST_HEADER_SIZE;
1344    
1345 schoenebeck 798 if (pFile->Mode != stream_mode_read_write)
1346     throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1347    
1348 schoenebeck 780 // write all subchunks (including sub list chunks) recursively
1349     if (pSubChunks) {
1350     for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1351     ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);
1352     }
1353     }
1354    
1355     // update this list chunk's header
1356     CurrentChunkSize = NewChunkSize = ulWritePos - ulOriginalPos - LIST_HEADER_SIZE;
1357     WriteHeader(ulOriginalPos);
1358    
1359 schoenebeck 798 // offset of this list chunk in new written file may have changed
1360     ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1361    
1362 schoenebeck 780 return ulWritePos;
1363     }
1364    
1365     void List::__resetPos() {
1366     Chunk::__resetPos();
1367     if (pSubChunks) {
1368     for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1369     (*iter)->__resetPos();
1370     }
1371     }
1372     }
1373    
1374 schoenebeck 11 /**
1375     * Returns string representation of the lists's id
1376     */
1377 schoenebeck 2 String List::GetListTypeString() {
1378     return convertToString(ListType);
1379     }
1380    
1381    
1382    
1383     // *************** File ***************
1384     // *
1385    
1386 schoenebeck 780 /** @brief Create new RIFF file.
1387     *
1388     * Use this constructor if you want to create a new RIFF file completely
1389     * "from scratch". Note: there must be no empty chunks or empty list
1390     * chunks when trying to make the new RIFF file persistent with Save()!
1391     *
1392 persson 1207 * Note: by default, the RIFF file will be saved in native endian
1393     * format; that is, as a RIFF file on little-endian machines and
1394     * as a RIFX file on big-endian. To change this behaviour, call
1395     * SetByteOrder() before calling Save().
1396     *
1397 schoenebeck 798 * @param FileType - four-byte identifier of the RIFF file type
1398 persson 1207 * @see AddSubChunk(), AddSubList(), SetByteOrder()
1399 schoenebeck 780 */
1400 schoenebeck 798 File::File(uint32_t FileType) : List(this) {
1401 schoenebeck 1050 #if defined(WIN32)
1402     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1403     #else
1404 schoenebeck 780 hFileRead = hFileWrite = 0;
1405 schoenebeck 1050 #endif
1406 schoenebeck 798 Mode = stream_mode_closed;
1407 schoenebeck 780 bEndianNative = true;
1408     ulStartPos = RIFF_HEADER_SIZE;
1409 schoenebeck 798 ListType = FileType;
1410 schoenebeck 780 }
1411    
1412     /** @brief Load existing RIFF file.
1413     *
1414     * Loads an existing RIFF file with all its chunks.
1415     *
1416     * @param path - path and file name of the RIFF file to open
1417     * @throws RIFF::Exception if error occured while trying to load the
1418     * given RIFF file
1419     */
1420     File::File(const String& path) : List(this), Filename(path) {
1421 schoenebeck 2 #if DEBUG
1422     std::cout << "File::File("<<path<<")" << std::endl;
1423     #endif // DEBUG
1424     bEndianNative = true;
1425     #if POSIX
1426 schoenebeck 780 hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1427     if (hFileRead <= 0) {
1428     hFileRead = hFileWrite = 0;
1429 schoenebeck 2 throw RIFF::Exception("Can't open \"" + path + "\"");
1430     }
1431 schoenebeck 1050 #elif defined(WIN32)
1432     hFileRead = hFileWrite = CreateFile(
1433     path.c_str(), GENERIC_READ,
1434     FILE_SHARE_READ | FILE_SHARE_WRITE,
1435     NULL, OPEN_EXISTING,
1436 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1437     FILE_FLAG_RANDOM_ACCESS, NULL
1438 schoenebeck 1050 );
1439     if (hFileRead == INVALID_HANDLE_VALUE) {
1440     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1441     throw RIFF::Exception("Can't open \"" + path + "\"");
1442     }
1443 schoenebeck 2 #else
1444 schoenebeck 780 hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1445 schoenebeck 1050 if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1446 schoenebeck 2 #endif // POSIX
1447 schoenebeck 798 Mode = stream_mode_read;
1448 schoenebeck 2 ulStartPos = RIFF_HEADER_SIZE;
1449     ReadHeader(0);
1450 schoenebeck 1863 if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1451 schoenebeck 2 throw RIFF::Exception("Not a RIFF file");
1452     }
1453     }
1454    
1455 schoenebeck 780 String File::GetFileName() {
1456     return Filename;
1457     }
1458    
1459     stream_mode_t File::GetMode() {
1460     return Mode;
1461     }
1462    
1463     /** @brief Change file access mode.
1464     *
1465     * Changes files access mode either to read-only mode or to read/write
1466     * mode.
1467     *
1468     * @param NewMode - new file access mode
1469     * @returns true if mode was changed, false if current mode already
1470     * equals new mode
1471     * @throws RIFF::Exception if new file access mode is unknown
1472     */
1473     bool File::SetMode(stream_mode_t NewMode) {
1474     if (NewMode != Mode) {
1475     switch (NewMode) {
1476     case stream_mode_read:
1477     #if POSIX
1478     if (hFileRead) close(hFileRead);
1479     hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1480     if (hFileRead < 0) {
1481     hFileRead = hFileWrite = 0;
1482     throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1483     }
1484 schoenebeck 1050 #elif defined(WIN32)
1485     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1486     hFileRead = hFileWrite = CreateFile(
1487     Filename.c_str(), GENERIC_READ,
1488     FILE_SHARE_READ | FILE_SHARE_WRITE,
1489     NULL, OPEN_EXISTING,
1490 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1491     FILE_FLAG_RANDOM_ACCESS,
1492     NULL
1493 schoenebeck 1050 );
1494     if (hFileRead == INVALID_HANDLE_VALUE) {
1495     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1496     throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1497     }
1498 schoenebeck 780 #else
1499     if (hFileRead) fclose(hFileRead);
1500 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1501 schoenebeck 780 if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1502     #endif
1503     __resetPos(); // reset read/write position of ALL 'Chunk' objects
1504 schoenebeck 798 break;
1505 schoenebeck 780 case stream_mode_read_write:
1506     #if POSIX
1507     if (hFileRead) close(hFileRead);
1508     hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1509     if (hFileRead < 0) {
1510     hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1511     throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1512     }
1513 schoenebeck 1050 #elif defined(WIN32)
1514     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1515     hFileRead = hFileWrite = CreateFile(
1516     Filename.c_str(),
1517     GENERIC_READ | GENERIC_WRITE,
1518     FILE_SHARE_READ,
1519     NULL, OPEN_ALWAYS,
1520 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1521     FILE_FLAG_RANDOM_ACCESS,
1522     NULL
1523 schoenebeck 1050 );
1524     if (hFileRead == INVALID_HANDLE_VALUE) {
1525     hFileRead = hFileWrite = CreateFile(
1526     Filename.c_str(), GENERIC_READ,
1527     FILE_SHARE_READ | FILE_SHARE_WRITE,
1528     NULL, OPEN_EXISTING,
1529 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1530     FILE_FLAG_RANDOM_ACCESS,
1531     NULL
1532 schoenebeck 1050 );
1533 persson 1301 throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1534 schoenebeck 1050 }
1535 schoenebeck 780 #else
1536     if (hFileRead) fclose(hFileRead);
1537 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1538 schoenebeck 780 if (!hFileRead) {
1539 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1540 schoenebeck 780 throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1541     }
1542     #endif
1543     __resetPos(); // reset read/write position of ALL 'Chunk' objects
1544 schoenebeck 798 break;
1545     case stream_mode_closed:
1546     #if POSIX
1547     if (hFileRead) close(hFileRead);
1548     if (hFileWrite) close(hFileWrite);
1549 schoenebeck 1050 #elif defined(WIN32)
1550     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1551     if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1552 schoenebeck 798 #else
1553     if (hFileRead) fclose(hFileRead);
1554     if (hFileWrite) fclose(hFileWrite);
1555     #endif
1556     hFileRead = hFileWrite = 0;
1557     break;
1558 schoenebeck 780 default:
1559     throw Exception("Unknown file access mode");
1560     }
1561 schoenebeck 798 Mode = NewMode;
1562     return true;
1563 schoenebeck 780 }
1564     return false;
1565     }
1566    
1567 persson 1184 /** @brief Set the byte order to be used when saving.
1568     *
1569     * Set the byte order to be used in the file. A value of
1570     * endian_little will create a RIFF file, endian_big a RIFX file
1571     * and endian_native will create a RIFF file on little-endian
1572     * machines and RIFX on big-endian machines.
1573     *
1574     * @param Endian - endianess to use when file is saved.
1575     */
1576     void File::SetByteOrder(endian_t Endian) {
1577     #if WORDS_BIGENDIAN
1578     bEndianNative = Endian != endian_little;
1579     #else
1580     bEndianNative = Endian != endian_big;
1581     #endif
1582     }
1583    
1584 schoenebeck 780 /** @brief Save changes to same file.
1585     *
1586     * Make all changes of all chunks persistent by writing them to the
1587     * actual (same) file. The file might temporarily grow to a higher size
1588     * than it will have at the end of the saving process, in case chunks
1589     * were grown.
1590     *
1591     * @throws RIFF::Exception if there is an empty chunk or empty list
1592     * chunk or any kind of IO error occured
1593     */
1594     void File::Save() {
1595 schoenebeck 833 // make sure the RIFF tree is built (from the original file)
1596     LoadSubChunksRecursively();
1597    
1598 schoenebeck 780 // reopen file in write mode
1599 schoenebeck 798 SetMode(stream_mode_read_write);
1600 schoenebeck 780
1601     // to be able to save the whole file without loading everything into
1602     // RAM and without having to store the data in a temporary file, we
1603     // enlarge the file with the sum of all _positive_ chunk size
1604     // changes, move current data towards the end of the file with the
1605     // calculated sum and finally update / rewrite the file by copying
1606     // the old data back to the right position at the beginning of the file
1607    
1608     // first we sum up all positive chunk size changes (and skip all negative ones)
1609     unsigned long ulPositiveSizeDiff = 0;
1610 persson 1678 for (std::set<Chunk*>::const_iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1611 schoenebeck 1095 if ((*iter)->GetNewSize() == 0) {
1612 schoenebeck 1105 throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
1613 schoenebeck 1095 }
1614 persson 1859 unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1615     unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1616     if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
1617 schoenebeck 780 }
1618    
1619     unsigned long ulWorkingFileSize = GetFileSize();
1620    
1621     // if there are positive size changes...
1622     if (ulPositiveSizeDiff > 0) {
1623     // ... we enlarge this file first ...
1624     ulWorkingFileSize += ulPositiveSizeDiff;
1625     ResizeFile(ulWorkingFileSize);
1626     // ... and move current data by the same amount towards end of file.
1627     int8_t* pCopyBuffer = new int8_t[4096];
1628     const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1629 schoenebeck 1050 #if defined(WIN32)
1630     DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1631     #else
1632 schoenebeck 1459 int iBytesMoved = 1;
1633 schoenebeck 1050 #endif
1634 persson 1678 for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1635     iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1636     ulPos -= iBytesMoved;
1637 schoenebeck 780 #if POSIX
1638     lseek(hFileRead, ulPos, SEEK_SET);
1639     iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1640     lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1641     iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1642 schoenebeck 1050 #elif defined(WIN32)
1643     SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1644     ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1645     SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1646     WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1647 schoenebeck 780 #else
1648     fseek(hFileRead, ulPos, SEEK_SET);
1649     iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1650     fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1651     iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1652     #endif
1653     }
1654     delete[] pCopyBuffer;
1655     if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1656     }
1657    
1658     // rebuild / rewrite complete RIFF tree
1659 schoenebeck 798 unsigned long ulTotalSize = WriteChunk(0, ulPositiveSizeDiff);
1660     unsigned long ulActualSize = __GetFileSize(hFileWrite);
1661 schoenebeck 780
1662     // resize file to the final size
1663 schoenebeck 798 if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1664 schoenebeck 780
1665     // forget all resized chunks
1666     ResizedChunks.clear();
1667     }
1668    
1669     /** @brief Save changes to another file.
1670     *
1671     * Make all changes of all chunks persistent by writing them to another
1672     * file. <b>Caution:</b> this method is optimized for writing to
1673     * <b>another</b> file, do not use it to save the changes to the same
1674 schoenebeck 798 * file! Use File::Save() in that case instead! Ignoring this might
1675     * result in a corrupted file, especially in case chunks were resized!
1676 schoenebeck 780 *
1677     * After calling this method, this File object will be associated with
1678     * the new file (given by \a path) afterwards.
1679     *
1680     * @param path - path and file name where everything should be written to
1681     */
1682     void File::Save(const String& path) {
1683 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
1684    
1685 schoenebeck 833 // make sure the RIFF tree is built (from the original file)
1686     LoadSubChunksRecursively();
1687    
1688 schoenebeck 798 if (Filename.length() > 0) SetMode(stream_mode_read);
1689 schoenebeck 780 // open the other (new) file for writing and truncate it to zero size
1690     #if POSIX
1691 schoenebeck 798 hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1692 schoenebeck 780 if (hFileWrite < 0) {
1693     hFileWrite = hFileRead;
1694     throw Exception("Could not open file \"" + path + "\" for writing");
1695     }
1696 schoenebeck 1050 #elif defined(WIN32)
1697     hFileWrite = CreateFile(
1698     path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1699 schoenebeck 1459 NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1700     FILE_FLAG_RANDOM_ACCESS, NULL
1701 schoenebeck 1050 );
1702     if (hFileWrite == INVALID_HANDLE_VALUE) {
1703     hFileWrite = hFileRead;
1704     throw Exception("Could not open file \"" + path + "\" for writing");
1705     }
1706 schoenebeck 780 #else
1707     hFileWrite = fopen(path.c_str(), "w+b");
1708     if (!hFileWrite) {
1709     hFileWrite = hFileRead;
1710     throw Exception("Could not open file \"" + path + "\" for writing");
1711     }
1712     #endif // POSIX
1713 schoenebeck 798 Mode = stream_mode_read_write;
1714 schoenebeck 780
1715     // write complete RIFF tree to the other (new) file
1716 schoenebeck 798 unsigned long ulTotalSize = WriteChunk(0, 0);
1717     unsigned long ulActualSize = __GetFileSize(hFileWrite);
1718 schoenebeck 780
1719 schoenebeck 798 // resize file to the final size (if the file was originally larger)
1720     if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1721    
1722 schoenebeck 780 // forget all resized chunks
1723     ResizedChunks.clear();
1724    
1725 persson 1301 #if POSIX
1726     if (hFileWrite) close(hFileWrite);
1727     #elif defined(WIN32)
1728     if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1729     #else
1730     if (hFileWrite) fclose(hFileWrite);
1731     #endif
1732     hFileWrite = hFileRead;
1733 schoenebeck 798
1734 schoenebeck 780 // associate new file with this File object from now on
1735     Filename = path;
1736 schoenebeck 798 Mode = (stream_mode_t) -1; // Just set it to an undefined mode ...
1737     SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
1738 schoenebeck 780 }
1739    
1740     void File::ResizeFile(unsigned long ulNewSize) {
1741     #if POSIX
1742     if (ftruncate(hFileWrite, ulNewSize) < 0)
1743     throw Exception("Could not resize file \"" + Filename + "\"");
1744 schoenebeck 1050 #elif defined(WIN32)
1745     if (
1746     SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1747     !SetEndOfFile(hFileWrite)
1748     ) throw Exception("Could not resize file \"" + Filename + "\"");
1749 schoenebeck 780 #else
1750 schoenebeck 1050 # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1751 schoenebeck 798 # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1752 schoenebeck 780 #endif
1753     }
1754    
1755 schoenebeck 2 File::~File() {
1756     #if DEBUG
1757     std::cout << "File::~File()" << std::endl;
1758     #endif // DEBUG
1759     #if POSIX
1760 schoenebeck 780 if (hFileRead) close(hFileRead);
1761 schoenebeck 1050 #elif defined(WIN32)
1762     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1763 schoenebeck 2 #else
1764 schoenebeck 780 if (hFileRead) fclose(hFileRead);
1765 schoenebeck 2 #endif // POSIX
1766 persson 1869 DeleteChunkList();
1767     pFile = NULL;
1768 schoenebeck 2 }
1769    
1770 schoenebeck 780 void File::LogAsResized(Chunk* pResizedChunk) {
1771 persson 1678 ResizedChunks.insert(pResizedChunk);
1772 schoenebeck 780 }
1773    
1774 schoenebeck 1095 void File::UnlogResized(Chunk* pResizedChunk) {
1775 persson 1678 ResizedChunks.erase(pResizedChunk);
1776 schoenebeck 1095 }
1777    
1778 schoenebeck 2 unsigned long File::GetFileSize() {
1779 schoenebeck 798 return __GetFileSize(hFileRead);
1780     }
1781    
1782     #if POSIX
1783     unsigned long File::__GetFileSize(int hFile) {
1784 schoenebeck 2 struct stat filestat;
1785 schoenebeck 798 fstat(hFile, &filestat);
1786 schoenebeck 2 long size = filestat.st_size;
1787     return size;
1788     }
1789 schoenebeck 1050 #elif defined(WIN32)
1790     unsigned long File::__GetFileSize(HANDLE hFile) {
1791 schoenebeck 1063 DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1792     if (dwSize == INVALID_FILE_SIZE)
1793     throw Exception("Windows FS error: could not determine file size");
1794     return dwSize;
1795 schoenebeck 1050 }
1796 schoenebeck 798 #else // standard C functions
1797     unsigned long File::__GetFileSize(FILE* hFile) {
1798     long curpos = ftell(hFile);
1799     fseek(hFile, 0, SEEK_END);
1800     long size = ftell(hFile);
1801     fseek(hFile, curpos, SEEK_SET);
1802     return size;
1803     }
1804     #endif
1805 schoenebeck 2
1806    
1807     // *************** Exception ***************
1808     // *
1809    
1810     void Exception::PrintMessage() {
1811     std::cout << "RIFF::Exception: " << Message << std::endl;
1812     }
1813    
1814 schoenebeck 518
1815     // *************** functions ***************
1816     // *
1817    
1818     /**
1819     * Returns the name of this C++ library. This is usually "libgig" of
1820     * course. This call is equivalent to DLS::libraryName() and
1821     * gig::libraryName().
1822     */
1823     String libraryName() {
1824     return PACKAGE;
1825     }
1826    
1827     /**
1828     * Returns version of this C++ library. This call is equivalent to
1829     * DLS::libraryVersion() and gig::libraryVersion().
1830     */
1831     String libraryVersion() {
1832     return VERSION;
1833     }
1834    
1835 schoenebeck 2 } // namespace RIFF

  ViewVC Help
Powered by ViewVC