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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2120 - (hide annotations) (download)
Sun Aug 29 11:10:36 2010 UTC (13 years, 7 months ago) by persson
File size: 76412 byte(s)
* bugfix: avoid calling read() with count 0 when writing a file, as
  this may hang on some systems

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

  ViewVC Help
Powered by ViewVC