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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2912 - (hide annotations) (download)
Tue May 17 14:30:10 2016 UTC (7 years, 11 months ago) by schoenebeck
File size: 94849 byte(s)
* gig.cpp/.h: GIG FORMAT EXTENSION: Added support for saving gig file
  larger than 4 GB as one single monolithic gig file. A new custom RIFF
  chunk "FFmt" was added to distinguish such monolithic large .gig files
  from old ones which were splitted over several (.gx01, .gx02, ...)
  "extension" files before.
* DLS.cpp/.h: Sample class: wave pool offsets are now 64 bits (to allow
  support for files larger than 4 GB).
* RIFF.cpp/.h: Addded support for RIFF files larger than 4 GB, by default
  the required internal RIFF file offset size is automatically detected
  (that is RIFF files < 4 GB automatically use 32 bit offsets while
  files >= 4 GB automatically use 64 bit offsets), a particular offset
  size can be forced with a new option added to the RIFF File constructor
  though.
* RIFF.cpp/.h: When saving a modified, grown RIFF file, the temporary file
  size during Save() operation will no longer be larger than the final
  grown file size.
* Automake: Set environment variable GCC_COLORS=auto to allow GCC to auto
  detect whether it (sh/c)ould output its messages in color.
* Bumped version (4.0.0.svn3).

1 schoenebeck 2 /***************************************************************************
2     * *
3 schoenebeck 933 * libgig - C++ cross-platform Gigasampler format file access library *
4 schoenebeck 2 * *
5 schoenebeck 2912 * Copyright (C) 2003-2016 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 2675 #if POSIX
33     # include <errno.h>
34     #endif
35    
36 schoenebeck 2 namespace RIFF {
37    
38 schoenebeck 1105 // *************** Internal functions **************
39     // *
40    
41     /// Returns a human readable path of the given chunk.
42 schoenebeck 1383 static String __resolveChunkPath(Chunk* pCk) {
43 schoenebeck 1105 String sPath;
44     for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
45     if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
46     List* pList = (List*) pChunk;
47     sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
48     } else {
49     sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
50     }
51     }
52     return sPath;
53     }
54    
55    
56    
57 schoenebeck 2682 // *************** progress_t ***************
58     // *
59    
60     progress_t::progress_t() {
61     callback = NULL;
62     custom = NULL;
63     __range_min = 0.0f;
64     __range_max = 1.0f;
65     }
66    
67    
68    
69 schoenebeck 2 // *************** Chunk **************
70     // *
71    
72 schoenebeck 780 Chunk::Chunk(File* pFile) {
73 schoenebeck 2 #if DEBUG
74 schoenebeck 780 std::cout << "Chunk::Chunk(File* pFile)" << std::endl;
75 schoenebeck 2 #endif // DEBUG
76 schoenebeck 2912 ullPos = 0;
77 schoenebeck 2 pParent = NULL;
78     pChunkData = NULL;
79 schoenebeck 2912 ullCurrentChunkSize = 0;
80     ullNewChunkSize = 0;
81     ullChunkDataSize = 0;
82 schoenebeck 798 ChunkID = CHUNK_ID_RIFF;
83 schoenebeck 780 this->pFile = pFile;
84 schoenebeck 2 }
85    
86 schoenebeck 2912 Chunk::Chunk(File* pFile, file_offset_t StartPos, List* Parent) {
87 schoenebeck 2 #if DEBUG
88 schoenebeck 2912 std::cout << "Chunk::Chunk(File*,file_offset_t,List*),StartPos=" << StartPos << std::endl;
89 schoenebeck 2 #endif // DEBUG
90 schoenebeck 780 this->pFile = pFile;
91 schoenebeck 2912 ullStartPos = StartPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
92 schoenebeck 2 pParent = Parent;
93 schoenebeck 2912 ullPos = 0;
94 schoenebeck 2 pChunkData = NULL;
95 schoenebeck 2912 ullCurrentChunkSize = 0;
96     ullNewChunkSize = 0;
97     ullChunkDataSize = 0;
98 schoenebeck 2 ReadHeader(StartPos);
99     }
100    
101 schoenebeck 2912 Chunk::Chunk(File* pFile, List* pParent, uint32_t uiChunkID, file_offset_t ullBodySize) {
102 schoenebeck 780 this->pFile = pFile;
103 schoenebeck 2912 ullStartPos = 0; // arbitrary usually, since it will be updated when we write the chunk
104 schoenebeck 780 this->pParent = pParent;
105 schoenebeck 2912 ullPos = 0;
106 schoenebeck 780 pChunkData = NULL;
107 schoenebeck 1863 ChunkID = uiChunkID;
108 schoenebeck 2912 ullChunkDataSize = 0;
109     ullCurrentChunkSize = 0;
110     ullNewChunkSize = ullBodySize;
111 schoenebeck 780 }
112    
113 schoenebeck 2 Chunk::~Chunk() {
114     if (pChunkData) delete[] pChunkData;
115     }
116    
117 schoenebeck 2912 void Chunk::ReadHeader(file_offset_t filePos) {
118 schoenebeck 2 #if DEBUG
119 schoenebeck 2912 std::cout << "Chunk::Readheader(" << filePos << ") ";
120 schoenebeck 2 #endif // DEBUG
121 schoenebeck 1863 ChunkID = 0;
122 schoenebeck 2912 ullNewChunkSize = ullCurrentChunkSize = 0;
123 schoenebeck 2 #if POSIX
124 schoenebeck 2912 if (lseek(pFile->hFileRead, filePos, SEEK_SET) != -1) {
125 schoenebeck 780 read(pFile->hFileRead, &ChunkID, 4);
126 schoenebeck 2912 read(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize);
127 schoenebeck 1050 #elif defined(WIN32)
128 schoenebeck 2912 if (SetFilePointerEx(pFile->hFileRead, filePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
129 schoenebeck 1050 DWORD dwBytesRead;
130     ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
131 schoenebeck 2912 ReadFile(pFile->hFileRead, &ullCurrentChunkSize, pFile->FileOffsetSize, &dwBytesRead, NULL);
132 schoenebeck 2 #else
133 schoenebeck 2912 if (!fseeko(pFile->hFileRead, filePos, SEEK_SET)) {
134 schoenebeck 780 fread(&ChunkID, 4, 1, pFile->hFileRead);
135 schoenebeck 2912 fread(&ullCurrentChunkSize, pFile->FileOffsetSize, 1, pFile->hFileRead);
136 schoenebeck 2 #endif // POSIX
137     #if WORDS_BIGENDIAN
138     if (ChunkID == CHUNK_ID_RIFF) {
139 schoenebeck 808 pFile->bEndianNative = false;
140 schoenebeck 2 }
141     #else // little endian
142     if (ChunkID == CHUNK_ID_RIFX) {
143 schoenebeck 780 pFile->bEndianNative = false;
144 schoenebeck 2 ChunkID = CHUNK_ID_RIFF;
145     }
146     #endif // WORDS_BIGENDIAN
147 schoenebeck 780 if (!pFile->bEndianNative) {
148 schoenebeck 11 //swapBytes_32(&ChunkID);
149 schoenebeck 2912 if (pFile->FileOffsetSize == 4)
150     swapBytes_32(&ullCurrentChunkSize);
151     else
152     swapBytes_64(&ullCurrentChunkSize);
153 schoenebeck 2 }
154 schoenebeck 11 #if DEBUG
155     std::cout << "ckID=" << convertToString(ChunkID) << " ";
156 schoenebeck 2912 std::cout << "ckSize=" << ullCurrentChunkSize << " ";
157 schoenebeck 1863 std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
158 schoenebeck 11 #endif // DEBUG
159 schoenebeck 2912 ullNewChunkSize = ullCurrentChunkSize;
160 schoenebeck 2 }
161     }
162    
163 schoenebeck 2912 void Chunk::WriteHeader(file_offset_t filePos) {
164 schoenebeck 780 uint32_t uiNewChunkID = ChunkID;
165     if (ChunkID == CHUNK_ID_RIFF) {
166     #if WORDS_BIGENDIAN
167     if (pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
168     #else // little endian
169     if (!pFile->bEndianNative) uiNewChunkID = CHUNK_ID_RIFX;
170     #endif // WORDS_BIGENDIAN
171     }
172    
173 schoenebeck 2912 uint64_t ullNewChunkSize = this->ullNewChunkSize;
174 schoenebeck 780 if (!pFile->bEndianNative) {
175 schoenebeck 2912 if (pFile->FileOffsetSize == 4)
176     swapBytes_32(&ullNewChunkSize);
177     else
178     swapBytes_64(&ullNewChunkSize);
179 schoenebeck 780 }
180    
181     #if POSIX
182 schoenebeck 2912 if (lseek(pFile->hFileWrite, filePos, SEEK_SET) != -1) {
183 schoenebeck 780 write(pFile->hFileWrite, &uiNewChunkID, 4);
184 schoenebeck 2912 write(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize);
185 schoenebeck 780 }
186 schoenebeck 1050 #elif defined(WIN32)
187 schoenebeck 2912 if (SetFilePointerEx(pFile->hFileWrite, filePos, NULL/*new pos pointer*/, FILE_BEGIN)) {
188 schoenebeck 1050 DWORD dwBytesWritten;
189     WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
190 schoenebeck 2912 WriteFile(pFile->hFileWrite, &ullNewChunkSize, pFile->FileOffsetSize, &dwBytesWritten, NULL);
191 schoenebeck 1050 }
192 schoenebeck 780 #else
193 schoenebeck 2912 if (!fseeko(pFile->hFileWrite, filePos, SEEK_SET)) {
194 schoenebeck 780 fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
195 schoenebeck 2912 fwrite(&ullNewChunkSize, pFile->FileOffsetSize, 1, pFile->hFileWrite);
196 schoenebeck 780 }
197     #endif // POSIX
198     }
199    
200 schoenebeck 11 /**
201     * Returns the String representation of the chunk's ID (e.g. "RIFF",
202     * "LIST").
203     */
204 schoenebeck 2912 String Chunk::GetChunkIDString() const {
205 schoenebeck 2 return convertToString(ChunkID);
206     }
207    
208 schoenebeck 11 /**
209     * Sets the position within the chunk body, thus within the data portion
210     * of the chunk (in bytes).
211     *
212 schoenebeck 780 * <b>Caution:</b> the position will be reset to zero whenever
213     * File::Save() was called.
214     *
215 schoenebeck 11 * @param Where - position offset (in bytes)
216     * @param Whence - optional: defines to what <i>\a Where</i> relates to,
217     * if omitted \a Where relates to beginning of the chunk
218     * data
219     */
220 schoenebeck 2912 file_offset_t Chunk::SetPos(file_offset_t Where, stream_whence_t Whence) {
221     #if DEBUG
222     std::cout << "Chunk::SetPos(file_offset_t,stream_whence_t)" << std::endl;
223     #endif // DEBUG
224 schoenebeck 2 switch (Whence) {
225     case stream_curpos:
226 schoenebeck 2912 ullPos += Where;
227 schoenebeck 2 break;
228     case stream_end:
229 schoenebeck 2912 ullPos = ullCurrentChunkSize - 1 - Where;
230 schoenebeck 2 break;
231     case stream_backward:
232 schoenebeck 2912 ullPos -= Where;
233 schoenebeck 2 break;
234     case stream_start: default:
235 schoenebeck 2912 ullPos = Where;
236 schoenebeck 2 break;
237     }
238 schoenebeck 2912 if (ullPos > ullCurrentChunkSize) ullPos = ullCurrentChunkSize;
239     return ullPos;
240 schoenebeck 2 }
241    
242 schoenebeck 11 /**
243     * Returns the number of bytes left to read in the chunk body.
244     * When reading data from the chunk using the Read*() Methods, the
245     * position within the chunk data (that is the chunk body) will be
246     * incremented by the number of read bytes and RemainingBytes() returns
247     * how much data is left to read from the current position to the end
248     * of the chunk data.
249     *
250     * @returns number of bytes left to read
251     */
252 schoenebeck 2912 file_offset_t Chunk::RemainingBytes() const {
253     #if DEBUG
254     std::cout << "Chunk::Remainingbytes()=" << ullCurrentChunkSize - ullPos << std::endl;
255     #endif // DEBUG
256     return (ullCurrentChunkSize > ullPos) ? ullCurrentChunkSize - ullPos : 0;
257 schoenebeck 2 }
258    
259 schoenebeck 11 /**
260 schoenebeck 2912 * Returns the actual total size in bytes (including header) of this Chunk
261     * if being stored to a file.
262     *
263     * @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
264     * being saved to a file
265     */
266     file_offset_t Chunk::RequiredPhysicalSize(int fileOffsetSize) {
267     return CHUNK_HEADER_SIZE(fileOffsetSize) + // RIFF chunk header
268     ullNewChunkSize + // chunks's actual data body
269     ullNewChunkSize % 2; // optional pad byte
270     }
271    
272     /**
273 schoenebeck 11 * Returns the current state of the chunk object.
274     * Following values are possible:
275     * - RIFF::stream_ready :
276     * chunk data can be read (this is the usual case)
277     * - RIFF::stream_closed :
278     * the data stream was closed somehow, no more reading possible
279     * - RIFF::stream_end_reached :
280 schoenebeck 1383 * already reached the end of the chunk data, no more reading
281 schoenebeck 11 * possible without SetPos()
282     */
283 schoenebeck 2912 stream_state_t Chunk::GetState() const {
284     #if DEBUG
285     std::cout << "Chunk::GetState()" << std::endl;
286     #endif // DEBUG
287 schoenebeck 2 #if POSIX
288 schoenebeck 1050 if (pFile->hFileRead == 0) return stream_closed;
289     #elif defined (WIN32)
290     if (pFile->hFileRead == INVALID_HANDLE_VALUE)
291     return stream_closed;
292 schoenebeck 2 #else
293 schoenebeck 780 if (pFile->hFileRead == NULL) return stream_closed;
294 schoenebeck 2 #endif // POSIX
295 schoenebeck 2912 if (ullPos < ullCurrentChunkSize) return stream_ready;
296     else return stream_end_reached;
297 schoenebeck 2 }
298    
299     /**
300     * Reads \a WordCount number of data words with given \a WordSize and
301     * copies it into a buffer pointed by \a pData. The buffer has to be
302     * allocated and be sure to provide the correct \a WordSize, as this
303     * will be important and taken into account for eventual endian
304     * correction (swapping of bytes due to different native byte order of
305     * a system). The position within the chunk will automatically be
306     * incremented.
307     *
308     * @param pData destination buffer
309     * @param WordCount number of data words to read
310     * @param WordSize size of each data word to read
311     * @returns number of successfully read data words or 0 if end
312     * of file reached or error occured
313     */
314 schoenebeck 2912 file_offset_t Chunk::Read(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
315     #if DEBUG
316     std::cout << "Chunk::Read(void*,file_offset_t,file_offset_t)" << std::endl;
317     #endif // DEBUG
318 schoenebeck 2543 //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
319 schoenebeck 2912 if (ullPos >= ullCurrentChunkSize) return 0;
320     if (ullPos + WordCount * WordSize >= ullCurrentChunkSize) WordCount = (ullCurrentChunkSize - ullPos) / WordSize;
321 schoenebeck 2 #if POSIX
322 schoenebeck 2912 if (lseek(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET) < 0) return 0;
323 schoenebeck 2685 ssize_t readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
324     if (readWords < 1) {
325     #if DEBUG
326     std::cerr << "POSIX read() failed: " << strerror(errno) << std::endl << std::flush;
327     #endif // DEBUG
328     return 0;
329     }
330 schoenebeck 2 readWords /= WordSize;
331 schoenebeck 1050 #elif defined(WIN32)
332 schoenebeck 2912 if (!SetFilePointerEx(pFile->hFileRead, ullStartPos + ullPos, NULL/*new pos pointer*/, FILE_BEGIN))
333     return 0;
334 schoenebeck 1050 DWORD readWords;
335 schoenebeck 2912 ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL); //FIXME: does not work for reading buffers larger than 2GB (even though this should rarely be the case in practice)
336 schoenebeck 1050 if (readWords < 1) return 0;
337     readWords /= WordSize;
338 schoenebeck 2 #else // standard C functions
339 schoenebeck 2912 if (fseeko(pFile->hFileRead, ullStartPos + ullPos, SEEK_SET)) return 0;
340     file_offset_t readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
341 schoenebeck 2 #endif // POSIX
342 schoenebeck 780 if (!pFile->bEndianNative && WordSize != 1) {
343 schoenebeck 2 switch (WordSize) {
344     case 2:
345 schoenebeck 2912 for (file_offset_t iWord = 0; iWord < readWords; iWord++)
346 schoenebeck 2 swapBytes_16((uint16_t*) pData + iWord);
347     break;
348     case 4:
349 schoenebeck 2912 for (file_offset_t iWord = 0; iWord < readWords; iWord++)
350 schoenebeck 2 swapBytes_32((uint32_t*) pData + iWord);
351     break;
352 schoenebeck 2912 case 8:
353     for (file_offset_t iWord = 0; iWord < readWords; iWord++)
354     swapBytes_64((uint64_t*) pData + iWord);
355     break;
356 schoenebeck 2 default:
357 schoenebeck 2912 for (file_offset_t iWord = 0; iWord < readWords; iWord++)
358 schoenebeck 2 swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
359     break;
360     }
361     }
362     SetPos(readWords * WordSize, stream_curpos);
363     return readWords;
364     }
365    
366 schoenebeck 780 /**
367     * Writes \a WordCount number of data words with given \a WordSize from
368     * the buffer pointed by \a pData. Be sure to provide the correct
369     * \a WordSize, as this will be important and taken into account for
370     * eventual endian correction (swapping of bytes due to different
371     * native byte order of a system). The position within the chunk will
372     * automatically be incremented.
373     *
374     * @param pData source buffer (containing the data)
375     * @param WordCount number of data words to write
376     * @param WordSize size of each data word to write
377     * @returns number of successfully written data words
378     * @throws RIFF::Exception if write operation would exceed current
379     * chunk size or any IO error occured
380     * @see Resize()
381     */
382 schoenebeck 2912 file_offset_t Chunk::Write(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
383 schoenebeck 798 if (pFile->Mode != stream_mode_read_write)
384     throw Exception("Cannot write data to chunk, file has to be opened in read+write mode first");
385 schoenebeck 2912 if (ullPos >= ullCurrentChunkSize || ullPos + WordCount * WordSize > ullCurrentChunkSize)
386 schoenebeck 780 throw Exception("End of chunk reached while trying to write data");
387     if (!pFile->bEndianNative && WordSize != 1) {
388     switch (WordSize) {
389     case 2:
390 schoenebeck 2912 for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
391 schoenebeck 780 swapBytes_16((uint16_t*) pData + iWord);
392     break;
393     case 4:
394 schoenebeck 2912 for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
395 schoenebeck 780 swapBytes_32((uint32_t*) pData + iWord);
396     break;
397 schoenebeck 2912 case 8:
398     for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
399     swapBytes_64((uint64_t*) pData + iWord);
400     break;
401 schoenebeck 780 default:
402 schoenebeck 2912 for (file_offset_t iWord = 0; iWord < WordCount; iWord++)
403 schoenebeck 780 swapBytes((uint8_t*) pData + iWord * WordSize, WordSize);
404     break;
405     }
406     }
407     #if POSIX
408 schoenebeck 2912 if (lseek(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET) < 0) {
409     throw Exception("Could not seek to position " + ToString(ullPos) +
410     " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
411 schoenebeck 780 }
412 schoenebeck 2912 ssize_t writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
413 schoenebeck 780 if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
414     writtenWords /= WordSize;
415 schoenebeck 1050 #elif defined(WIN32)
416 schoenebeck 2912 if (!SetFilePointerEx(pFile->hFileWrite, ullStartPos + ullPos, NULL/*new pos pointer*/, FILE_BEGIN)) {
417     throw Exception("Could not seek to position " + ToString(ullPos) +
418     " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
419 schoenebeck 1050 }
420     DWORD writtenWords;
421 schoenebeck 2912 WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL); //FIXME: does not work for writing buffers larger than 2GB (even though this should rarely be the case in practice)
422 schoenebeck 1050 if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
423     writtenWords /= WordSize;
424 schoenebeck 780 #else // standard C functions
425 schoenebeck 2912 if (fseeko(pFile->hFileWrite, ullStartPos + ullPos, SEEK_SET)) {
426     throw Exception("Could not seek to position " + ToString(ullPos) +
427     " in chunk (" + ToString(ullStartPos + ullPos) + " in file)");
428 schoenebeck 780 }
429 schoenebeck 2912 file_offset_t writtenWords = fwrite(pData, WordSize, WordCount, pFile->hFileWrite);
430 schoenebeck 780 #endif // POSIX
431     SetPos(writtenWords * WordSize, stream_curpos);
432     return writtenWords;
433     }
434    
435 schoenebeck 2 /** Just an internal wrapper for the main <i>Read()</i> method with additional Exception throwing on errors. */
436 schoenebeck 2912 file_offset_t Chunk::ReadSceptical(void* pData, file_offset_t WordCount, file_offset_t WordSize) {
437     file_offset_t readWords = Read(pData, WordCount, WordSize);
438 schoenebeck 2 if (readWords != WordCount) throw RIFF::Exception("End of chunk data reached.");
439     return readWords;
440     }
441    
442     /**
443     * Reads \a WordCount number of 8 Bit signed integer words and copies it
444     * into the buffer pointed by \a pData. The buffer has to be allocated.
445     * The position within the chunk will automatically be incremented.
446     *
447     * @param pData destination buffer
448     * @param WordCount number of 8 Bit signed integers to read
449     * @returns number of read integers
450     * @throws RIFF::Exception if an error occured or less than
451     * \a WordCount integers could be read!
452     */
453 schoenebeck 2912 file_offset_t Chunk::ReadInt8(int8_t* pData, file_offset_t WordCount) {
454     #if DEBUG
455     std::cout << "Chunk::ReadInt8(int8_t*,file_offset_t)" << std::endl;
456     #endif // DEBUG
457 schoenebeck 2 return ReadSceptical(pData, WordCount, 1);
458     }
459    
460     /**
461 schoenebeck 780 * Writes \a WordCount number of 8 Bit signed integer words from the
462     * buffer pointed by \a pData to the chunk's body, directly to the
463     * actual "physical" file. The position within the chunk will
464     * automatically be incremented. Note: you cannot write beyond the
465     * boundaries of the chunk, to append data to the chunk call Resize()
466     * before.
467     *
468     * @param pData source buffer (containing the data)
469     * @param WordCount number of 8 Bit signed integers to write
470     * @returns number of written integers
471     * @throws RIFF::Exception if an IO error occured
472     * @see Resize()
473     */
474 schoenebeck 2912 file_offset_t Chunk::WriteInt8(int8_t* pData, file_offset_t WordCount) {
475 schoenebeck 780 return Write(pData, WordCount, 1);
476     }
477    
478     /**
479 schoenebeck 2 * Reads \a WordCount number of 8 Bit unsigned integer words and copies
480     * it into the buffer pointed by \a pData. The buffer has to be
481     * allocated. The position within the chunk will automatically be
482     * incremented.
483     *
484     * @param pData destination buffer
485     * @param WordCount number of 8 Bit unsigned integers to read
486     * @returns number of read integers
487     * @throws RIFF::Exception if an error occured or less than
488     * \a WordCount integers could be read!
489     */
490 schoenebeck 2912 file_offset_t Chunk::ReadUint8(uint8_t* pData, file_offset_t WordCount) {
491     #if DEBUG
492     std::cout << "Chunk::ReadUint8(uint8_t*,file_offset_t)" << std::endl;
493     #endif // DEBUG
494 schoenebeck 2 return ReadSceptical(pData, WordCount, 1);
495     }
496    
497     /**
498 schoenebeck 780 * Writes \a WordCount number of 8 Bit unsigned integer words from the
499     * buffer pointed by \a pData to the chunk's body, directly to the
500     * actual "physical" file. The position within the chunk will
501     * automatically be incremented. Note: you cannot write beyond the
502     * boundaries of the chunk, to append data to the chunk call Resize()
503     * before.
504     *
505     * @param pData source buffer (containing the data)
506     * @param WordCount number of 8 Bit unsigned integers to write
507     * @returns number of written integers
508     * @throws RIFF::Exception if an IO error occured
509     * @see Resize()
510     */
511 schoenebeck 2912 file_offset_t Chunk::WriteUint8(uint8_t* pData, file_offset_t WordCount) {
512 schoenebeck 780 return Write(pData, WordCount, 1);
513     }
514    
515     /**
516 schoenebeck 2 * Reads \a WordCount number of 16 Bit signed integer words and copies
517     * it into the buffer pointed by \a pData. The buffer has to be
518     * allocated. Endian correction will automatically be done if needed.
519     * The position within the chunk will automatically be incremented.
520     *
521     * @param pData destination buffer
522     * @param WordCount number of 16 Bit signed integers to read
523     * @returns number of read integers
524     * @throws RIFF::Exception if an error occured or less than
525     * \a WordCount integers could be read!
526     */
527 schoenebeck 2912 file_offset_t Chunk::ReadInt16(int16_t* pData, file_offset_t WordCount) {
528     #if DEBUG
529     std::cout << "Chunk::ReadInt16(int16_t*,file_offset_t)" << std::endl;
530     #endif // DEBUG
531 schoenebeck 2 return ReadSceptical(pData, WordCount, 2);
532     }
533    
534     /**
535 schoenebeck 780 * Writes \a WordCount number of 16 Bit signed integer words from the
536     * buffer pointed by \a pData to the chunk's body, directly to the
537     * actual "physical" file. The position within the chunk will
538     * automatically be incremented. Note: you cannot write beyond the
539     * boundaries of the chunk, to append data to the chunk call Resize()
540     * before.
541     *
542     * @param pData source buffer (containing the data)
543     * @param WordCount number of 16 Bit signed integers to write
544     * @returns number of written integers
545     * @throws RIFF::Exception if an IO error occured
546     * @see Resize()
547     */
548 schoenebeck 2912 file_offset_t Chunk::WriteInt16(int16_t* pData, file_offset_t WordCount) {
549 schoenebeck 780 return Write(pData, WordCount, 2);
550     }
551    
552     /**
553 schoenebeck 2 * Reads \a WordCount number of 16 Bit unsigned integer words and copies
554     * it into the buffer pointed by \a pData. The buffer has to be
555     * allocated. Endian correction will automatically be done if needed.
556     * The position within the chunk will automatically be incremented.
557     *
558     * @param pData destination buffer
559     * @param WordCount number of 8 Bit unsigned integers to read
560     * @returns number of read integers
561     * @throws RIFF::Exception if an error occured or less than
562     * \a WordCount integers could be read!
563     */
564 schoenebeck 2912 file_offset_t Chunk::ReadUint16(uint16_t* pData, file_offset_t WordCount) {
565     #if DEBUG
566     std::cout << "Chunk::ReadUint16(uint16_t*,file_offset_t)" << std::endl;
567     #endif // DEBUG
568 schoenebeck 2 return ReadSceptical(pData, WordCount, 2);
569     }
570    
571     /**
572 schoenebeck 780 * Writes \a WordCount number of 16 Bit unsigned integer words from the
573     * buffer pointed by \a pData to the chunk's body, directly to the
574     * actual "physical" file. The position within the chunk will
575     * automatically be incremented. Note: you cannot write beyond the
576     * boundaries of the chunk, to append data to the chunk call Resize()
577     * before.
578     *
579     * @param pData source buffer (containing the data)
580     * @param WordCount number of 16 Bit unsigned integers to write
581     * @returns number of written integers
582     * @throws RIFF::Exception if an IO error occured
583     * @see Resize()
584     */
585 schoenebeck 2912 file_offset_t Chunk::WriteUint16(uint16_t* pData, file_offset_t WordCount) {
586 schoenebeck 780 return Write(pData, WordCount, 2);
587     }
588    
589     /**
590 schoenebeck 2 * Reads \a WordCount number of 32 Bit signed integer words and copies
591     * it into the buffer pointed by \a pData. The buffer has to be
592     * allocated. Endian correction will automatically be done if needed.
593     * The position within the chunk will automatically be incremented.
594     *
595     * @param pData destination buffer
596     * @param WordCount number of 32 Bit signed integers to read
597     * @returns number of read integers
598     * @throws RIFF::Exception if an error occured or less than
599     * \a WordCount integers could be read!
600     */
601 schoenebeck 2912 file_offset_t Chunk::ReadInt32(int32_t* pData, file_offset_t WordCount) {
602     #if DEBUG
603     std::cout << "Chunk::ReadInt32(int32_t*,file_offset_t)" << std::endl;
604     #endif // DEBUG
605 schoenebeck 2 return ReadSceptical(pData, WordCount, 4);
606     }
607    
608     /**
609 schoenebeck 780 * Writes \a WordCount number of 32 Bit signed integer words from the
610     * buffer pointed by \a pData to the chunk's body, directly to the
611     * actual "physical" file. The position within the chunk will
612     * automatically be incremented. Note: you cannot write beyond the
613     * boundaries of the chunk, to append data to the chunk call Resize()
614     * before.
615     *
616     * @param pData source buffer (containing the data)
617     * @param WordCount number of 32 Bit signed integers to write
618     * @returns number of written integers
619     * @throws RIFF::Exception if an IO error occured
620     * @see Resize()
621     */
622 schoenebeck 2912 file_offset_t Chunk::WriteInt32(int32_t* pData, file_offset_t WordCount) {
623 schoenebeck 780 return Write(pData, WordCount, 4);
624     }
625    
626     /**
627 schoenebeck 2 * Reads \a WordCount number of 32 Bit unsigned integer words and copies
628     * it into the buffer pointed by \a pData. The buffer has to be
629     * allocated. Endian correction will automatically be done if needed.
630     * The position within the chunk will automatically be incremented.
631     *
632     * @param pData destination buffer
633     * @param WordCount number of 32 Bit unsigned integers to read
634     * @returns number of read integers
635     * @throws RIFF::Exception if an error occured or less than
636     * \a WordCount integers could be read!
637     */
638 schoenebeck 2912 file_offset_t Chunk::ReadUint32(uint32_t* pData, file_offset_t WordCount) {
639     #if DEBUG
640     std::cout << "Chunk::ReadUint32(uint32_t*,file_offset_t)" << std::endl;
641     #endif // DEBUG
642 schoenebeck 2 return ReadSceptical(pData, WordCount, 4);
643     }
644    
645     /**
646 persson 2450 * Reads a null-padded string of size characters and copies it
647     * into the string \a s. The position within the chunk will
648     * automatically be incremented.
649     *
650     * @param s destination string
651     * @param size number of characters to read
652     * @throws RIFF::Exception if an error occured or less than
653     * \a size characters could be read!
654     */
655     void Chunk::ReadString(String& s, int size) {
656     char* buf = new char[size];
657     ReadSceptical(buf, 1, size);
658     s.assign(buf, std::find(buf, buf + size, '\0'));
659     delete[] buf;
660     }
661    
662     /**
663 schoenebeck 780 * Writes \a WordCount number of 32 Bit unsigned integer words from the
664     * buffer pointed by \a pData to the chunk's body, directly to the
665     * actual "physical" file. The position within the chunk will
666     * automatically be incremented. Note: you cannot write beyond the
667     * boundaries of the chunk, to append data to the chunk call Resize()
668     * before.
669     *
670     * @param pData source buffer (containing the data)
671     * @param WordCount number of 32 Bit unsigned integers to write
672     * @returns number of written integers
673     * @throws RIFF::Exception if an IO error occured
674     * @see Resize()
675     */
676 schoenebeck 2912 file_offset_t Chunk::WriteUint32(uint32_t* pData, file_offset_t WordCount) {
677 schoenebeck 780 return Write(pData, WordCount, 4);
678     }
679    
680     /**
681 schoenebeck 2 * Reads one 8 Bit signed integer word and increments the position within
682     * the chunk.
683     *
684     * @returns read integer word
685     * @throws RIFF::Exception if an error occured
686     */
687     int8_t Chunk::ReadInt8() {
688 schoenebeck 2912 #if DEBUG
689     std::cout << "Chunk::ReadInt8()" << std::endl;
690     #endif // DEBUG
691 schoenebeck 2 int8_t word;
692     ReadSceptical(&word,1,1);
693     return word;
694     }
695    
696     /**
697     * Reads one 8 Bit unsigned integer word and increments the position
698     * within the chunk.
699     *
700     * @returns read integer word
701     * @throws RIFF::Exception if an error occured
702     */
703     uint8_t Chunk::ReadUint8() {
704 schoenebeck 2912 #if DEBUG
705     std::cout << "Chunk::ReadUint8()" << std::endl;
706     #endif // DEBUG
707 schoenebeck 2 uint8_t word;
708     ReadSceptical(&word,1,1);
709     return word;
710     }
711    
712     /**
713     * Reads one 16 Bit signed integer word and increments the position
714     * within the chunk. Endian correction will automatically be done if
715     * needed.
716     *
717     * @returns read integer word
718     * @throws RIFF::Exception if an error occured
719     */
720     int16_t Chunk::ReadInt16() {
721 schoenebeck 2912 #if DEBUG
722     std::cout << "Chunk::ReadInt16()" << std::endl;
723     #endif // DEBUG
724 schoenebeck 2 int16_t word;
725     ReadSceptical(&word,1,2);
726     return word;
727     }
728    
729     /**
730     * Reads one 16 Bit unsigned integer word and increments the position
731     * within the chunk. Endian correction will automatically be done if
732     * needed.
733     *
734     * @returns read integer word
735     * @throws RIFF::Exception if an error occured
736     */
737     uint16_t Chunk::ReadUint16() {
738 schoenebeck 2912 #if DEBUG
739     std::cout << "Chunk::ReadUint16()" << std::endl;
740     #endif // DEBUG
741 schoenebeck 2 uint16_t word;
742     ReadSceptical(&word,1,2);
743     return word;
744     }
745    
746     /**
747     * Reads one 32 Bit signed integer word and increments the position
748     * within the chunk. Endian correction will automatically be done if
749     * needed.
750     *
751     * @returns read integer word
752     * @throws RIFF::Exception if an error occured
753     */
754     int32_t Chunk::ReadInt32() {
755 schoenebeck 2912 #if DEBUG
756     std::cout << "Chunk::ReadInt32()" << std::endl;
757     #endif // DEBUG
758 schoenebeck 2 int32_t word;
759     ReadSceptical(&word,1,4);
760     return word;
761     }
762    
763     /**
764     * Reads one 32 Bit unsigned integer word and increments the position
765     * within the chunk. Endian correction will automatically be done if
766     * needed.
767     *
768     * @returns read integer word
769     * @throws RIFF::Exception if an error occured
770     */
771     uint32_t Chunk::ReadUint32() {
772 schoenebeck 2912 #if DEBUG
773     std::cout << "Chunk::ReadUint32()" << std::endl;
774     #endif // DEBUG
775 schoenebeck 2 uint32_t word;
776     ReadSceptical(&word,1,4);
777     return word;
778     }
779    
780 schoenebeck 780 /** @brief Load chunk body into RAM.
781     *
782     * Loads the whole chunk body into memory. You can modify the data in
783     * RAM and save the data by calling File::Save() afterwards.
784     *
785     * <b>Caution:</b> the buffer pointer will be invalidated once
786     * File::Save() was called. You have to call LoadChunkData() again to
787 schoenebeck 800 * get a new, valid pointer whenever File::Save() was called.
788 schoenebeck 780 *
789 schoenebeck 800 * You can call LoadChunkData() again if you previously scheduled to
790     * enlarge this chunk with a Resize() call. In that case the buffer will
791     * be enlarged to the new, scheduled chunk size and you can already
792     * place the new chunk data to the buffer and finally call File::Save()
793     * to enlarge the chunk physically and write the new data in one rush.
794     * This approach is definitely recommended if you have to enlarge and
795     * write new data to a lot of chunks.
796     *
797 schoenebeck 780 * @returns a pointer to the data in RAM on success, NULL otherwise
798 schoenebeck 800 * @throws Exception if data buffer could not be enlarged
799 schoenebeck 780 * @see ReleaseChunkData()
800     */
801 schoenebeck 2 void* Chunk::LoadChunkData() {
802 schoenebeck 2543 if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
803 schoenebeck 2 #if POSIX
804 schoenebeck 2912 if (lseek(pFile->hFileRead, ullStartPos, SEEK_SET) == -1) return NULL;
805 schoenebeck 1050 #elif defined(WIN32)
806 schoenebeck 2912 if (!SetFilePointerEx(pFile->hFileRead, ullStartPos, NULL/*new pos pointer*/, FILE_BEGIN)) return NULL;
807 schoenebeck 800 #else
808 schoenebeck 2912 if (fseeko(pFile->hFileRead, ullStartPos, SEEK_SET)) return NULL;
809 schoenebeck 800 #endif // POSIX
810 schoenebeck 2912 file_offset_t ullBufferSize = (ullCurrentChunkSize > ullNewChunkSize) ? ullCurrentChunkSize : ullNewChunkSize;
811     pChunkData = new uint8_t[ullBufferSize];
812 schoenebeck 2 if (!pChunkData) return NULL;
813 schoenebeck 2912 memset(pChunkData, 0, ullBufferSize);
814 schoenebeck 800 #if POSIX
815 schoenebeck 2912 file_offset_t readWords = read(pFile->hFileRead, pChunkData, GetSize());
816 schoenebeck 1050 #elif defined(WIN32)
817     DWORD readWords;
818 schoenebeck 2912 ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL); //FIXME: won't load chunks larger than 2GB !
819 schoenebeck 2 #else
820 schoenebeck 2912 file_offset_t readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
821 schoenebeck 2 #endif // POSIX
822     if (readWords != GetSize()) {
823     delete[] pChunkData;
824     return (pChunkData = NULL);
825     }
826 schoenebeck 2912 ullChunkDataSize = ullBufferSize;
827     } else if (ullNewChunkSize > ullChunkDataSize) {
828     uint8_t* pNewBuffer = new uint8_t[ullNewChunkSize];
829     if (!pNewBuffer) throw Exception("Could not enlarge chunk data buffer to " + ToString(ullNewChunkSize) + " bytes");
830     memset(pNewBuffer, 0 , ullNewChunkSize);
831     memcpy(pNewBuffer, pChunkData, ullChunkDataSize);
832 schoenebeck 800 delete[] pChunkData;
833 schoenebeck 2912 pChunkData = pNewBuffer;
834     ullChunkDataSize = ullNewChunkSize;
835 schoenebeck 2 }
836     return pChunkData;
837     }
838    
839 schoenebeck 780 /** @brief Free loaded chunk body from RAM.
840     *
841     * Frees loaded chunk body data from memory (RAM). You should call
842     * File::Save() before calling this method if you modified the data to
843     * make the changes persistent.
844     */
845 schoenebeck 2 void Chunk::ReleaseChunkData() {
846     if (pChunkData) {
847     delete[] pChunkData;
848     pChunkData = NULL;
849     }
850     }
851    
852 schoenebeck 780 /** @brief Resize chunk.
853     *
854     * Resizes this chunk's body, that is the actual size of data possible
855     * to be written to this chunk. This call will return immediately and
856     * just schedule the resize operation. You should call File::Save() to
857     * actually perform the resize operation(s) "physically" to the file.
858     * As this can take a while on large files, it is recommended to call
859     * Resize() first on all chunks which have to be resized and finally to
860     * call File::Save() to perform all those resize operations in one rush.
861     *
862     * <b>Caution:</b> You cannot directly write to enlarged chunks before
863     * calling File::Save() as this might exceed the current chunk's body
864 schoenebeck 800 * boundary!
865 schoenebeck 780 *
866 schoenebeck 2912 * @param NewSize - new chunk body size in bytes (must be greater than zero)
867     * @throws RIFF::Exception if \a NewSize is less than 1 or Unrealistic large
868 schoenebeck 780 * @see File::Save()
869     */
870 schoenebeck 2912 void Chunk::Resize(file_offset_t NewSize) {
871     if (NewSize == 0)
872 schoenebeck 1105 throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
873 schoenebeck 2912 if ((NewSize >> 48) != 0)
874     throw Exception("Unrealistic high chunk size detected: " + __resolveChunkPath(this));
875     if (ullNewChunkSize == NewSize) return;
876     ullNewChunkSize = NewSize;
877 schoenebeck 780 }
878 schoenebeck 2
879 schoenebeck 780 /** @brief Write chunk persistently e.g. to disk.
880     *
881     * Stores the chunk persistently to its actual "physical" file.
882     *
883 schoenebeck 2912 * @param ullWritePos - position within the "physical" file where this
884 schoenebeck 780 * chunk should be written to
885 schoenebeck 2912 * @param ullCurrentDataOffset - offset of current (old) data within
886 schoenebeck 780 * the file
887 schoenebeck 2682 * @param pProgress - optional: callback function for progress notification
888 schoenebeck 780 * @returns new write position in the "physical" file, that is
889 schoenebeck 2912 * \a ullWritePos incremented by this chunk's new size
890 schoenebeck 780 * (including its header size of course)
891     */
892 schoenebeck 2912 file_offset_t Chunk::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
893     const file_offset_t ullOriginalPos = ullWritePos;
894     ullWritePos += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
895 schoenebeck 2
896 schoenebeck 798 if (pFile->Mode != stream_mode_read_write)
897     throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
898    
899 schoenebeck 780 // if the whole chunk body was loaded into RAM
900     if (pChunkData) {
901 schoenebeck 800 // make sure chunk data buffer in RAM is at least as large as the new chunk size
902     LoadChunkData();
903 schoenebeck 780 // write chunk data from RAM persistently to the file
904     #if POSIX
905 schoenebeck 2912 lseek(pFile->hFileWrite, ullWritePos, SEEK_SET);
906     if (write(pFile->hFileWrite, pChunkData, ullNewChunkSize) != ullNewChunkSize) {
907 schoenebeck 780 throw Exception("Writing Chunk data (from RAM) failed");
908     }
909 schoenebeck 1050 #elif defined(WIN32)
910 schoenebeck 2912 SetFilePointerEx(pFile->hFileWrite, ullWritePos, NULL/*new pos pointer*/, FILE_BEGIN);
911 schoenebeck 1050 DWORD dwBytesWritten;
912 schoenebeck 2912 WriteFile(pFile->hFileWrite, pChunkData, ullNewChunkSize, &dwBytesWritten, NULL); //FIXME: won't save chunks larger than 2GB !
913     if (dwBytesWritten != ullNewChunkSize) {
914 schoenebeck 1050 throw Exception("Writing Chunk data (from RAM) failed");
915     }
916 schoenebeck 780 #else
917 schoenebeck 2912 fseeko(pFile->hFileWrite, ullWritePos, SEEK_SET);
918     if (fwrite(pChunkData, 1, ullNewChunkSize, pFile->hFileWrite) != ullNewChunkSize) {
919 schoenebeck 780 throw Exception("Writing Chunk data (from RAM) failed");
920     }
921     #endif // POSIX
922     } else {
923     // move chunk data from the end of the file to the appropriate position
924     int8_t* pCopyBuffer = new int8_t[4096];
925 schoenebeck 2912 file_offset_t ullToMove = (ullNewChunkSize < ullCurrentChunkSize) ? ullNewChunkSize : ullCurrentChunkSize;
926 schoenebeck 1050 #if defined(WIN32)
927     DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
928     #else
929 schoenebeck 780 int iBytesMoved = 1;
930 schoenebeck 1050 #endif
931 schoenebeck 2912 for (file_offset_t ullOffset = 0; ullToMove > 0 && iBytesMoved > 0; ullOffset += iBytesMoved, ullToMove -= iBytesMoved) {
932     iBytesMoved = (ullToMove < 4096) ? ullToMove : 4096;
933 schoenebeck 780 #if POSIX
934 schoenebeck 2912 lseek(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
935 schoenebeck 780 iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
936 schoenebeck 2912 lseek(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
937 schoenebeck 780 iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
938 schoenebeck 1050 #elif defined(WIN32)
939 schoenebeck 2912 SetFilePointerEx(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, NULL/*new pos pointer*/, FILE_BEGIN);
940 schoenebeck 1050 ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
941 schoenebeck 2912 SetFilePointerEx(pFile->hFileWrite, ullWritePos + ullOffset, NULL/*new pos pointer*/, FILE_BEGIN);
942 schoenebeck 1050 WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
943 schoenebeck 780 #else
944 schoenebeck 2912 fseeko(pFile->hFileRead, ullStartPos + ullCurrentDataOffset + ullOffset, SEEK_SET);
945 schoenebeck 780 iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
946 schoenebeck 2912 fseeko(pFile->hFileWrite, ullWritePos + ullOffset, SEEK_SET);
947 schoenebeck 780 iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, pFile->hFileWrite);
948     #endif
949     }
950     delete[] pCopyBuffer;
951     if (iBytesMoved < 0) throw Exception("Writing Chunk data (from file) failed");
952     }
953    
954     // update this chunk's header
955 schoenebeck 2912 ullCurrentChunkSize = ullNewChunkSize;
956     WriteHeader(ullOriginalPos);
957 schoenebeck 780
958 schoenebeck 2682 __notify_progress(pProgress, 1.0); // notify done
959    
960 schoenebeck 780 // update chunk's position pointers
961 schoenebeck 2912 ullStartPos = ullOriginalPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
962     ullPos = 0;
963 schoenebeck 780
964     // add pad byte if needed
965 schoenebeck 2912 if ((ullStartPos + ullNewChunkSize) % 2 != 0) {
966 schoenebeck 798 const char cPadByte = 0;
967 schoenebeck 780 #if POSIX
968 schoenebeck 2912 lseek(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
969 schoenebeck 780 write(pFile->hFileWrite, &cPadByte, 1);
970 schoenebeck 1050 #elif defined(WIN32)
971 schoenebeck 2912 SetFilePointerEx(pFile->hFileWrite, ullStartPos + ullNewChunkSize, NULL/*new pos pointer*/, FILE_BEGIN);
972 schoenebeck 1050 DWORD dwBytesWritten;
973     WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
974 schoenebeck 780 #else
975 schoenebeck 2912 fseeko(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
976 schoenebeck 780 fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
977     #endif
978 schoenebeck 2912 return ullStartPos + ullNewChunkSize + 1;
979 schoenebeck 780 }
980    
981 schoenebeck 2912 return ullStartPos + ullNewChunkSize;
982 schoenebeck 780 }
983    
984     void Chunk::__resetPos() {
985 schoenebeck 2912 ullPos = 0;
986 schoenebeck 780 }
987    
988    
989    
990 schoenebeck 2 // *************** List ***************
991     // *
992    
993 schoenebeck 780 List::List(File* pFile) : Chunk(pFile) {
994 schoenebeck 2912 #if DEBUG
995     std::cout << "List::List(File* pFile)" << std::endl;
996     #endif // DEBUG
997 schoenebeck 2 pSubChunks = NULL;
998     pSubChunksMap = NULL;
999     }
1000    
1001 schoenebeck 2912 List::List(File* pFile, file_offset_t StartPos, List* Parent)
1002 schoenebeck 780 : Chunk(pFile, StartPos, Parent) {
1003 schoenebeck 2 #if DEBUG
1004 schoenebeck 2912 std::cout << "List::List(File*,file_offset_t,List*)" << std::endl;
1005 schoenebeck 2 #endif // DEBUG
1006     pSubChunks = NULL;
1007     pSubChunksMap = NULL;
1008     ReadHeader(StartPos);
1009 schoenebeck 2912 ullStartPos = StartPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1010 schoenebeck 2 }
1011    
1012 schoenebeck 780 List::List(File* pFile, List* pParent, uint32_t uiListID)
1013     : Chunk(pFile, pParent, CHUNK_ID_LIST, 0) {
1014     pSubChunks = NULL;
1015     pSubChunksMap = NULL;
1016     ListType = uiListID;
1017     }
1018    
1019 schoenebeck 2 List::~List() {
1020 schoenebeck 2912 #if DEBUG
1021     std::cout << "List::~List()" << std::endl;
1022     #endif // DEBUG
1023 persson 1869 DeleteChunkList();
1024     }
1025    
1026     void List::DeleteChunkList() {
1027 schoenebeck 2 if (pSubChunks) {
1028     ChunkList::iterator iter = pSubChunks->begin();
1029     ChunkList::iterator end = pSubChunks->end();
1030     while (iter != end) {
1031     delete *iter;
1032     iter++;
1033     }
1034     delete pSubChunks;
1035 persson 1869 pSubChunks = NULL;
1036 schoenebeck 2 }
1037 persson 1869 if (pSubChunksMap) {
1038     delete pSubChunksMap;
1039     pSubChunksMap = NULL;
1040     }
1041 schoenebeck 2 }
1042    
1043 schoenebeck 11 /**
1044     * Returns subchunk with chunk ID <i>\a ChunkID</i> within this chunk
1045     * list. Use this method if you expect only one subchunk of that type in
1046     * the list. It there are more than one, it's undetermined which one of
1047     * them will be returned! If there are no subchunks with that desired
1048     * chunk ID, NULL will be returned.
1049     *
1050     * @param ChunkID - chunk ID of the sought subchunk
1051     * @returns pointer to the subchunk or NULL if there is none of
1052     * that ID
1053     */
1054 schoenebeck 2 Chunk* List::GetSubChunk(uint32_t ChunkID) {
1055 schoenebeck 2912 #if DEBUG
1056     std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
1057     #endif // DEBUG
1058 schoenebeck 2 if (!pSubChunksMap) LoadSubChunks();
1059     return (*pSubChunksMap)[ChunkID];
1060     }
1061    
1062 schoenebeck 11 /**
1063     * Returns sublist chunk with list type <i>\a ListType</i> within this
1064     * chunk list. Use this method if you expect only one sublist chunk of
1065     * that type in the list. It there are more than one, it's undetermined
1066     * which one of them will be returned! If there are no sublists with
1067     * that desired list type, NULL will be returned.
1068     *
1069     * @param ListType - list type of the sought sublist
1070     * @returns pointer to the sublist or NULL if there is none of
1071     * that type
1072     */
1073 schoenebeck 2 List* List::GetSubList(uint32_t ListType) {
1074     #if DEBUG
1075     std::cout << "List::GetSubList(uint32_t)" << std::endl;
1076     #endif // DEBUG
1077     if (!pSubChunks) LoadSubChunks();
1078     ChunkList::iterator iter = pSubChunks->begin();
1079     ChunkList::iterator end = pSubChunks->end();
1080     while (iter != end) {
1081     if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1082     List* l = (List*) *iter;
1083     if (l->GetListType() == ListType) return l;
1084     }
1085     iter++;
1086     }
1087     return NULL;
1088     }
1089    
1090 schoenebeck 11 /**
1091     * Returns the first subchunk within the list. You have to call this
1092     * method before you can call GetNextSubChunk(). Recall it when you want
1093     * to start from the beginning of the list again.
1094     *
1095     * @returns pointer to the first subchunk within the list, NULL
1096     * otherwise
1097     */
1098 schoenebeck 2 Chunk* List::GetFirstSubChunk() {
1099     #if DEBUG
1100     std::cout << "List::GetFirstSubChunk()" << std::endl;
1101     #endif // DEBUG
1102     if (!pSubChunks) LoadSubChunks();
1103     ChunksIterator = pSubChunks->begin();
1104     return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1105     }
1106    
1107 schoenebeck 11 /**
1108     * Returns the next subchunk within the list. You have to call
1109     * GetFirstSubChunk() before you can use this method!
1110     *
1111     * @returns pointer to the next subchunk within the list or NULL if
1112     * end of list is reached
1113     */
1114 schoenebeck 2 Chunk* List::GetNextSubChunk() {
1115     #if DEBUG
1116     std::cout << "List::GetNextSubChunk()" << std::endl;
1117     #endif // DEBUG
1118     if (!pSubChunks) return NULL;
1119     ChunksIterator++;
1120     return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1121     }
1122    
1123 schoenebeck 11 /**
1124     * Returns the first sublist within the list (that is a subchunk with
1125     * chunk ID "LIST"). You have to call this method before you can call
1126     * GetNextSubList(). Recall it when you want to start from the beginning
1127     * of the list again.
1128     *
1129     * @returns pointer to the first sublist within the list, NULL
1130     * otherwise
1131     */
1132 schoenebeck 2 List* List::GetFirstSubList() {
1133     #if DEBUG
1134     std::cout << "List::GetFirstSubList()" << std::endl;
1135     #endif // DEBUG
1136     if (!pSubChunks) LoadSubChunks();
1137     ListIterator = pSubChunks->begin();
1138     ChunkList::iterator end = pSubChunks->end();
1139     while (ListIterator != end) {
1140     if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1141     ListIterator++;
1142     }
1143     return NULL;
1144     }
1145    
1146 schoenebeck 11 /**
1147     * Returns the next sublist (that is a subchunk with chunk ID "LIST")
1148     * within the list. You have to call GetFirstSubList() before you can
1149     * use this method!
1150     *
1151     * @returns pointer to the next sublist within the list, NULL if
1152     * end of list is reached
1153     */
1154 schoenebeck 2 List* List::GetNextSubList() {
1155     #if DEBUG
1156     std::cout << "List::GetNextSubList()" << std::endl;
1157     #endif // DEBUG
1158     if (!pSubChunks) return NULL;
1159     if (ListIterator == pSubChunks->end()) return NULL;
1160     ListIterator++;
1161     ChunkList::iterator end = pSubChunks->end();
1162     while (ListIterator != end) {
1163     if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1164     ListIterator++;
1165     }
1166     return NULL;
1167     }
1168    
1169 schoenebeck 11 /**
1170 schoenebeck 515 * Returns number of subchunks within the list.
1171 schoenebeck 11 */
1172 schoenebeck 2 unsigned int List::CountSubChunks() {
1173     if (!pSubChunks) LoadSubChunks();
1174     return pSubChunks->size();
1175     }
1176    
1177 schoenebeck 11 /**
1178     * Returns number of subchunks within the list with chunk ID
1179     * <i>\a ChunkId</i>.
1180     */
1181 schoenebeck 2 unsigned int List::CountSubChunks(uint32_t ChunkID) {
1182     unsigned int result = 0;
1183     if (!pSubChunks) LoadSubChunks();
1184     ChunkList::iterator iter = pSubChunks->begin();
1185     ChunkList::iterator end = pSubChunks->end();
1186     while (iter != end) {
1187     if ((*iter)->GetChunkID() == ChunkID) {
1188     result++;
1189     }
1190     iter++;
1191     }
1192     return result;
1193     }
1194    
1195 schoenebeck 11 /**
1196     * Returns number of sublists within the list.
1197     */
1198 schoenebeck 2 unsigned int List::CountSubLists() {
1199     return CountSubChunks(CHUNK_ID_LIST);
1200     }
1201    
1202 schoenebeck 11 /**
1203     * Returns number of sublists within the list with list type
1204     * <i>\a ListType</i>
1205     */
1206 schoenebeck 2 unsigned int List::CountSubLists(uint32_t ListType) {
1207     unsigned int result = 0;
1208     if (!pSubChunks) LoadSubChunks();
1209     ChunkList::iterator iter = pSubChunks->begin();
1210     ChunkList::iterator end = pSubChunks->end();
1211     while (iter != end) {
1212     if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1213     List* l = (List*) *iter;
1214     if (l->GetListType() == ListType) result++;
1215     }
1216     iter++;
1217     }
1218     return result;
1219     }
1220    
1221 schoenebeck 780 /** @brief Creates a new sub chunk.
1222     *
1223     * Creates and adds a new sub chunk to this list chunk. Note that the
1224 schoenebeck 2912 * chunk's body size given by \a ullBodySize must be greater than zero.
1225 schoenebeck 780 * You have to call File::Save() to make this change persistent to the
1226     * actual file and <b>before</b> performing any data write operations
1227     * on the new chunk!
1228     *
1229     * @param uiChunkID - chunk ID of the new chunk
1230 schoenebeck 2912 * @param ullBodySize - size of the new chunk's body, that is its actual
1231     * data size (without header)
1232     * @throws RIFF::Exception if \a ullBodySize equals zero
1233 schoenebeck 780 */
1234 schoenebeck 2912 Chunk* List::AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize) {
1235     if (ullBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1236 schoenebeck 780 if (!pSubChunks) LoadSubChunks();
1237 schoenebeck 798 Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1238 schoenebeck 780 pSubChunks->push_back(pNewChunk);
1239     (*pSubChunksMap)[uiChunkID] = pNewChunk;
1240 schoenebeck 2912 pNewChunk->Resize(ullBodySize);
1241     ullNewChunkSize += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1242 schoenebeck 780 return pNewChunk;
1243     }
1244    
1245 schoenebeck 2584 /** @brief Moves a sub chunk witin this list.
1246 persson 1102 *
1247 schoenebeck 2584 * Moves a sub chunk from one position in this list to another
1248 persson 1102 * position in the same list. The pSrc chunk is placed before the
1249     * pDst chunk.
1250     *
1251     * @param pSrc - sub chunk to be moved
1252     * @param pDst - the position to move to. pSrc will be placed
1253     * before pDst. If pDst is 0, pSrc will be placed
1254     * last in list.
1255     */
1256     void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1257     if (!pSubChunks) LoadSubChunks();
1258     pSubChunks->remove(pSrc);
1259     ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1260     pSubChunks->insert(iter, pSrc);
1261     }
1262    
1263 schoenebeck 2584 /** @brief Moves a sub chunk from this list to another list.
1264     *
1265     * Moves a sub chunk from this list list to the end of another
1266     * list.
1267     *
1268     * @param pSrc - sub chunk to be moved
1269     * @param pDst - destination list where the chunk shall be moved to
1270     */
1271     void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1272     if (pNewParent == this || !pNewParent) return;
1273     if (!pSubChunks) LoadSubChunks();
1274     if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1275     pSubChunks->remove(pSrc);
1276     pNewParent->pSubChunks->push_back(pSrc);
1277     // update chunk id map of this List
1278     if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1279     pSubChunksMap->erase(pSrc->GetChunkID());
1280     // try to find another chunk of the same chunk ID
1281     ChunkList::iterator iter = pSubChunks->begin();
1282     ChunkList::iterator end = pSubChunks->end();
1283     for (; iter != end; ++iter) {
1284     if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1285     (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1286     break; // we're done, stop search
1287     }
1288     }
1289     }
1290     // update chunk id map of other list
1291     if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1292     (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1293     }
1294    
1295 schoenebeck 780 /** @brief Creates a new list sub chunk.
1296     *
1297     * Creates and adds a new list sub chunk to this list chunk. Note that
1298     * you have to add sub chunks / sub list chunks to the new created chunk
1299     * <b>before</b> trying to make this change persisten to the actual
1300     * file with File::Save()!
1301     *
1302     * @param uiListType - list ID of the new list chunk
1303     */
1304     List* List::AddSubList(uint32_t uiListType) {
1305     if (!pSubChunks) LoadSubChunks();
1306     List* pNewListChunk = new List(pFile, this, uiListType);
1307     pSubChunks->push_back(pNewListChunk);
1308     (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1309 schoenebeck 2912 ullNewChunkSize += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1310 schoenebeck 780 return pNewListChunk;
1311     }
1312    
1313     /** @brief Removes a sub chunk.
1314     *
1315     * Removes the sub chunk given by \a pSubChunk from this list and frees
1316     * it completely from RAM. The given chunk can either be a normal sub
1317 schoenebeck 1093 * chunk or a list sub chunk. In case the given chunk is a list chunk,
1318     * all its subchunks (if any) will be removed recursively as well. You
1319     * should call File::Save() to make this change persistent at any time.
1320 schoenebeck 780 *
1321     * @param pSubChunk - sub chunk or sub list chunk to be removed
1322     */
1323     void List::DeleteSubChunk(Chunk* pSubChunk) {
1324     if (!pSubChunks) LoadSubChunks();
1325     pSubChunks->remove(pSubChunk);
1326     if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1327     pSubChunksMap->erase(pSubChunk->GetChunkID());
1328     // try to find another chunk of the same chunk ID
1329     ChunkList::iterator iter = pSubChunks->begin();
1330     ChunkList::iterator end = pSubChunks->end();
1331     for (; iter != end; ++iter) {
1332     if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1333     (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1334     break; // we're done, stop search
1335     }
1336     }
1337     }
1338     delete pSubChunk;
1339     }
1340    
1341 schoenebeck 2912 /**
1342     * Returns the actual total size in bytes (including List chunk header and
1343     * all subchunks) of this List Chunk if being stored to a file.
1344     *
1345     * @param fileOffsetSize - RIFF file offset size (in bytes) assumed when
1346     * being saved to a file
1347     */
1348     file_offset_t List::RequiredPhysicalSize(int fileOffsetSize) {
1349     if (!pSubChunks) LoadSubChunks();
1350     file_offset_t size = LIST_HEADER_SIZE(fileOffsetSize);
1351     ChunkList::iterator iter = pSubChunks->begin();
1352     ChunkList::iterator end = pSubChunks->end();
1353     for (; iter != end; ++iter)
1354     size += (*iter)->RequiredPhysicalSize(fileOffsetSize);
1355     return size;
1356     }
1357    
1358     void List::ReadHeader(file_offset_t filePos) {
1359     #if DEBUG
1360     std::cout << "List::Readheader(file_offset_t) ";
1361     #endif // DEBUG
1362     Chunk::ReadHeader(filePos);
1363     if (ullCurrentChunkSize < 4) return;
1364     ullNewChunkSize = ullCurrentChunkSize -= 4;
1365 schoenebeck 2 #if POSIX
1366 schoenebeck 2912 lseek(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1367 schoenebeck 780 read(pFile->hFileRead, &ListType, 4);
1368 schoenebeck 1050 #elif defined(WIN32)
1369 schoenebeck 2912 SetFilePointerEx(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), NULL/*new pos pointer*/, FILE_BEGIN);
1370 schoenebeck 1050 DWORD dwBytesRead;
1371     ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1372 schoenebeck 2 #else
1373 schoenebeck 2912 fseeko(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1374 schoenebeck 780 fread(&ListType, 4, 1, pFile->hFileRead);
1375 schoenebeck 2 #endif // POSIX
1376 schoenebeck 2912 #if DEBUG
1377     std::cout << "listType=" << convertToString(ListType) << std::endl;
1378     #endif // DEBUG
1379 schoenebeck 780 if (!pFile->bEndianNative) {
1380 schoenebeck 11 //swapBytes_32(&ListType);
1381 schoenebeck 2 }
1382     }
1383    
1384 schoenebeck 2912 void List::WriteHeader(file_offset_t filePos) {
1385 schoenebeck 780 // the four list type bytes officially belong the chunk's body in the RIFF format
1386 schoenebeck 2912 ullNewChunkSize += 4;
1387     Chunk::WriteHeader(filePos);
1388     ullNewChunkSize -= 4; // just revert the +4 incrementation
1389 schoenebeck 780 #if POSIX
1390 schoenebeck 2912 lseek(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1391 schoenebeck 780 write(pFile->hFileWrite, &ListType, 4);
1392 schoenebeck 1050 #elif defined(WIN32)
1393 schoenebeck 2912 SetFilePointerEx(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), NULL/*new pos pointer*/, FILE_BEGIN);
1394 schoenebeck 1050 DWORD dwBytesWritten;
1395     WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1396 schoenebeck 780 #else
1397 schoenebeck 2912 fseeko(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1398 schoenebeck 780 fwrite(&ListType, 4, 1, pFile->hFileWrite);
1399     #endif // POSIX
1400     }
1401    
1402 schoenebeck 2682 void List::LoadSubChunks(progress_t* pProgress) {
1403 schoenebeck 2912 #if DEBUG
1404     std::cout << "List::LoadSubChunks()";
1405     #endif // DEBUG
1406 schoenebeck 2 if (!pSubChunks) {
1407     pSubChunks = new ChunkList();
1408     pSubChunksMap = new ChunkMap();
1409 persson 1301 #if defined(WIN32)
1410     if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1411     #else
1412 schoenebeck 780 if (!pFile->hFileRead) return;
1413 persson 1301 #endif
1414 schoenebeck 2912 file_offset_t ullOriginalPos = GetPos();
1415 schoenebeck 515 SetPos(0); // jump to beginning of list chunk body
1416 schoenebeck 2912 while (RemainingBytes() >= CHUNK_HEADER_SIZE(pFile->FileOffsetSize)) {
1417 schoenebeck 2 Chunk* ck;
1418 schoenebeck 11 uint32_t ckid;
1419     Read(&ckid, 4, 1);
1420 schoenebeck 2912 #if DEBUG
1421     std::cout << " ckid=" << convertToString(ckid) << std::endl;
1422     #endif // DEBUG
1423 schoenebeck 2 if (ckid == CHUNK_ID_LIST) {
1424 schoenebeck 2912 ck = new RIFF::List(pFile, ullStartPos + ullPos - 4, this);
1425     SetPos(ck->GetSize() + LIST_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1426 schoenebeck 2 }
1427     else { // simple chunk
1428 schoenebeck 2912 ck = new RIFF::Chunk(pFile, ullStartPos + ullPos - 4, this);
1429     SetPos(ck->GetSize() + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1430 schoenebeck 2 }
1431     pSubChunks->push_back(ck);
1432     (*pSubChunksMap)[ckid] = ck;
1433     if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte
1434     }
1435 schoenebeck 2912 SetPos(ullOriginalPos); // restore position before this call
1436 schoenebeck 2 }
1437 schoenebeck 2682 __notify_progress(pProgress, 1.0); // notify done
1438 schoenebeck 2 }
1439    
1440 schoenebeck 2682 void List::LoadSubChunksRecursively(progress_t* pProgress) {
1441     const int n = CountSubLists();
1442     int i = 0;
1443     for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList(), ++i) {
1444     // divide local progress into subprogress
1445     progress_t subprogress;
1446     __divide_progress(pProgress, &subprogress, n, i);
1447     // do the actual work
1448     pList->LoadSubChunksRecursively(&subprogress);
1449     }
1450     __notify_progress(pProgress, 1.0); // notify done
1451 schoenebeck 833 }
1452    
1453 schoenebeck 780 /** @brief Write list chunk persistently e.g. to disk.
1454     *
1455     * Stores the list chunk persistently to its actual "physical" file. All
1456     * subchunks (including sub list chunks) will be stored recursively as
1457     * well.
1458     *
1459 schoenebeck 2912 * @param ullWritePos - position within the "physical" file where this
1460 schoenebeck 780 * list chunk should be written to
1461 schoenebeck 2912 * @param ullCurrentDataOffset - offset of current (old) data within
1462 schoenebeck 780 * the file
1463 schoenebeck 2682 * @param pProgress - optional: callback function for progress notification
1464 schoenebeck 780 * @returns new write position in the "physical" file, that is
1465 schoenebeck 2912 * \a ullWritePos incremented by this list chunk's new size
1466 schoenebeck 780 * (including its header size of course)
1467     */
1468 schoenebeck 2912 file_offset_t List::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
1469     const file_offset_t ullOriginalPos = ullWritePos;
1470     ullWritePos += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1471 schoenebeck 780
1472 schoenebeck 798 if (pFile->Mode != stream_mode_read_write)
1473     throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1474    
1475 schoenebeck 780 // write all subchunks (including sub list chunks) recursively
1476     if (pSubChunks) {
1477 schoenebeck 2682 int i = 0;
1478     const int n = pSubChunks->size();
1479     for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1480     // divide local progress into subprogress for loading current Instrument
1481     progress_t subprogress;
1482     __divide_progress(pProgress, &subprogress, n, i);
1483     // do the actual work
1484 schoenebeck 2912 ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, &subprogress);
1485 schoenebeck 780 }
1486     }
1487    
1488     // update this list chunk's header
1489 schoenebeck 2912 ullCurrentChunkSize = ullNewChunkSize = ullWritePos - ullOriginalPos - LIST_HEADER_SIZE(pFile->FileOffsetSize);
1490     WriteHeader(ullOriginalPos);
1491 schoenebeck 780
1492 schoenebeck 798 // offset of this list chunk in new written file may have changed
1493 schoenebeck 2912 ullStartPos = ullOriginalPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1494 schoenebeck 798
1495 schoenebeck 2682 __notify_progress(pProgress, 1.0); // notify done
1496    
1497 schoenebeck 2912 return ullWritePos;
1498 schoenebeck 780 }
1499    
1500     void List::__resetPos() {
1501     Chunk::__resetPos();
1502     if (pSubChunks) {
1503     for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1504     (*iter)->__resetPos();
1505     }
1506     }
1507     }
1508    
1509 schoenebeck 11 /**
1510     * Returns string representation of the lists's id
1511     */
1512 schoenebeck 2912 String List::GetListTypeString() const {
1513 schoenebeck 2 return convertToString(ListType);
1514     }
1515    
1516    
1517    
1518     // *************** File ***************
1519     // *
1520    
1521 schoenebeck 780 /** @brief Create new RIFF file.
1522     *
1523     * Use this constructor if you want to create a new RIFF file completely
1524     * "from scratch". Note: there must be no empty chunks or empty list
1525     * chunks when trying to make the new RIFF file persistent with Save()!
1526     *
1527 persson 1207 * Note: by default, the RIFF file will be saved in native endian
1528     * format; that is, as a RIFF file on little-endian machines and
1529     * as a RIFX file on big-endian. To change this behaviour, call
1530     * SetByteOrder() before calling Save().
1531     *
1532 schoenebeck 798 * @param FileType - four-byte identifier of the RIFF file type
1533 persson 1207 * @see AddSubChunk(), AddSubList(), SetByteOrder()
1534 schoenebeck 780 */
1535 schoenebeck 2543 File::File(uint32_t FileType)
1536 schoenebeck 2912 : List(this), bIsNewFile(true), Layout(layout_standard),
1537     FileOffsetPreference(offset_size_auto)
1538 schoenebeck 2543 {
1539 schoenebeck 1050 #if defined(WIN32)
1540     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1541     #else
1542 schoenebeck 780 hFileRead = hFileWrite = 0;
1543 schoenebeck 1050 #endif
1544 schoenebeck 798 Mode = stream_mode_closed;
1545 schoenebeck 780 bEndianNative = true;
1546 schoenebeck 798 ListType = FileType;
1547 schoenebeck 2912 FileOffsetSize = 4;
1548     ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1549 schoenebeck 780 }
1550    
1551     /** @brief Load existing RIFF file.
1552     *
1553     * Loads an existing RIFF file with all its chunks.
1554     *
1555     * @param path - path and file name of the RIFF file to open
1556     * @throws RIFF::Exception if error occured while trying to load the
1557     * given RIFF file
1558     */
1559 schoenebeck 2543 File::File(const String& path)
1560 schoenebeck 2912 : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard),
1561     FileOffsetPreference(offset_size_auto)
1562 schoenebeck 2543 {
1563 schoenebeck 2912 #if DEBUG
1564     std::cout << "File::File("<<path<<")" << std::endl;
1565     #endif // DEBUG
1566 schoenebeck 2543 bEndianNative = true;
1567 schoenebeck 2912 FileOffsetSize = 4;
1568 persson 2155 try {
1569 schoenebeck 2543 __openExistingFile(path);
1570 persson 2155 if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1571     throw RIFF::Exception("Not a RIFF file");
1572     }
1573 schoenebeck 2 }
1574 persson 2155 catch (...) {
1575     Cleanup();
1576     throw;
1577 schoenebeck 1050 }
1578 schoenebeck 2 }
1579    
1580 schoenebeck 2543 /** @brief Load existing RIFF-like file.
1581     *
1582     * Loads an existing file, which is not a "real" RIFF file, but similar to
1583     * an ordinary RIFF file.
1584     *
1585     * A "real" RIFF file contains at top level a List chunk either with chunk
1586     * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1587     * case, and if it finds the toplevel List chunk to have another chunk ID
1588     * than one of those two expected ones, it would throw an Exception and
1589     * would refuse to load the file accordingly.
1590     *
1591     * Since there are however a lot of file formats which use the same simple
1592     * principles of the RIFF format, with another toplevel List chunk ID
1593     * though, you can use this alternative constructor here to be able to load
1594     * and handle those files in the same way as you would do with "real" RIFF
1595     * files.
1596     *
1597     * @param path - path and file name of the RIFF-alike file to be opened
1598     * @param FileType - expected toplevel List chunk ID (this is the very
1599     * first chunk found in the file)
1600     * @param Endian - whether the file uses little endian or big endian layout
1601     * @param layout - general file structure type
1602 schoenebeck 2912 * @param fileOffsetSize - (optional) preference how to deal with large files
1603 schoenebeck 2543 * @throws RIFF::Exception if error occured while trying to load the
1604     * given RIFF-alike file
1605     */
1606 schoenebeck 2912 File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout, offset_size_t fileOffsetSize)
1607     : List(this), Filename(path), bIsNewFile(false), Layout(layout),
1608     FileOffsetPreference(fileOffsetSize)
1609 schoenebeck 2543 {
1610     SetByteOrder(Endian);
1611 schoenebeck 2912 if (fileOffsetSize < offset_size_auto || fileOffsetSize > offset_size_64bit)
1612     throw Exception("Invalid RIFF::offset_size_t");
1613     FileOffsetSize = 4;
1614 schoenebeck 2543 try {
1615     __openExistingFile(path, &FileType);
1616     }
1617     catch (...) {
1618     Cleanup();
1619     throw;
1620     }
1621     }
1622    
1623     /**
1624     * Opens an already existing RIFF file or RIFF-alike file. This method
1625     * shall only be called once (in a File class constructor).
1626     *
1627     * @param path - path and file name of the RIFF file or RIFF-alike file to
1628     * be opened
1629     * @param FileType - (optional) expected chunk ID of first chunk in file
1630     * @throws RIFF::Exception if error occured while trying to load the
1631     * given RIFF file or RIFF-alike file
1632     */
1633     void File::__openExistingFile(const String& path, uint32_t* FileType) {
1634     #if POSIX
1635     hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1636 schoenebeck 2675 if (hFileRead == -1) {
1637 schoenebeck 2543 hFileRead = hFileWrite = 0;
1638 schoenebeck 2675 String sError = strerror(errno);
1639     throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1640 schoenebeck 2543 }
1641     #elif defined(WIN32)
1642     hFileRead = hFileWrite = CreateFile(
1643     path.c_str(), GENERIC_READ,
1644     FILE_SHARE_READ | FILE_SHARE_WRITE,
1645     NULL, OPEN_EXISTING,
1646     FILE_ATTRIBUTE_NORMAL |
1647     FILE_FLAG_RANDOM_ACCESS, NULL
1648     );
1649     if (hFileRead == INVALID_HANDLE_VALUE) {
1650     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1651     throw RIFF::Exception("Can't open \"" + path + "\"");
1652     }
1653     #else
1654     hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1655     if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1656     #endif // POSIX
1657     Mode = stream_mode_read;
1658 schoenebeck 2912
1659     // determine RIFF file offset size to be used (in RIFF chunk headers)
1660     // according to the current file offset preference
1661     FileOffsetSize = FileOffsetSizeFor(GetCurrentFileSize());
1662    
1663 schoenebeck 2543 switch (Layout) {
1664     case layout_standard: // this is a normal RIFF file
1665 schoenebeck 2912 ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1666 schoenebeck 2543 ReadHeader(0);
1667     if (FileType && ChunkID != *FileType)
1668     throw RIFF::Exception("Invalid file container ID");
1669     break;
1670     case layout_flat: // non-standard RIFF-alike file
1671 schoenebeck 2912 ullStartPos = 0;
1672     ullNewChunkSize = ullCurrentChunkSize = GetCurrentFileSize();
1673 schoenebeck 2543 if (FileType) {
1674     uint32_t ckid;
1675     if (Read(&ckid, 4, 1) != 4) {
1676     throw RIFF::Exception("Invalid file header ID (premature end of header)");
1677     } else if (ckid != *FileType) {
1678     String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1679     throw RIFF::Exception("Invalid file header ID" + s);
1680     }
1681     SetPos(0); // reset to first byte of file
1682     }
1683     LoadSubChunks();
1684     break;
1685     }
1686     }
1687    
1688 schoenebeck 2912 String File::GetFileName() const {
1689 schoenebeck 780 return Filename;
1690     }
1691 schoenebeck 2482
1692     void File::SetFileName(const String& path) {
1693     Filename = path;
1694     }
1695 schoenebeck 780
1696 schoenebeck 2912 stream_mode_t File::GetMode() const {
1697 schoenebeck 780 return Mode;
1698     }
1699    
1700 schoenebeck 2543 layout_t File::GetLayout() const {
1701     return Layout;
1702     }
1703    
1704 schoenebeck 780 /** @brief Change file access mode.
1705     *
1706     * Changes files access mode either to read-only mode or to read/write
1707     * mode.
1708     *
1709     * @param NewMode - new file access mode
1710     * @returns true if mode was changed, false if current mode already
1711     * equals new mode
1712     * @throws RIFF::Exception if new file access mode is unknown
1713     */
1714     bool File::SetMode(stream_mode_t NewMode) {
1715     if (NewMode != Mode) {
1716     switch (NewMode) {
1717     case stream_mode_read:
1718     #if POSIX
1719     if (hFileRead) close(hFileRead);
1720     hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1721 schoenebeck 2675 if (hFileRead == -1) {
1722 schoenebeck 780 hFileRead = hFileWrite = 0;
1723 schoenebeck 2675 String sError = strerror(errno);
1724     throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1725 schoenebeck 780 }
1726 schoenebeck 1050 #elif defined(WIN32)
1727     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1728     hFileRead = hFileWrite = CreateFile(
1729     Filename.c_str(), GENERIC_READ,
1730     FILE_SHARE_READ | FILE_SHARE_WRITE,
1731     NULL, OPEN_EXISTING,
1732 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1733     FILE_FLAG_RANDOM_ACCESS,
1734     NULL
1735 schoenebeck 1050 );
1736     if (hFileRead == INVALID_HANDLE_VALUE) {
1737     hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1738     throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1739     }
1740 schoenebeck 780 #else
1741     if (hFileRead) fclose(hFileRead);
1742 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1743 schoenebeck 780 if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1744     #endif
1745     __resetPos(); // reset read/write position of ALL 'Chunk' objects
1746 schoenebeck 798 break;
1747 schoenebeck 780 case stream_mode_read_write:
1748     #if POSIX
1749     if (hFileRead) close(hFileRead);
1750     hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1751 schoenebeck 2675 if (hFileRead == -1) {
1752 schoenebeck 780 hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1753 schoenebeck 2675 String sError = strerror(errno);
1754     throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1755 schoenebeck 780 }
1756 schoenebeck 1050 #elif defined(WIN32)
1757     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1758     hFileRead = hFileWrite = CreateFile(
1759     Filename.c_str(),
1760     GENERIC_READ | GENERIC_WRITE,
1761     FILE_SHARE_READ,
1762     NULL, OPEN_ALWAYS,
1763 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1764     FILE_FLAG_RANDOM_ACCESS,
1765     NULL
1766 schoenebeck 1050 );
1767     if (hFileRead == INVALID_HANDLE_VALUE) {
1768     hFileRead = hFileWrite = CreateFile(
1769     Filename.c_str(), GENERIC_READ,
1770     FILE_SHARE_READ | FILE_SHARE_WRITE,
1771     NULL, OPEN_EXISTING,
1772 schoenebeck 1459 FILE_ATTRIBUTE_NORMAL |
1773     FILE_FLAG_RANDOM_ACCESS,
1774     NULL
1775 schoenebeck 1050 );
1776 persson 1301 throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1777 schoenebeck 1050 }
1778 schoenebeck 780 #else
1779     if (hFileRead) fclose(hFileRead);
1780 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1781 schoenebeck 780 if (!hFileRead) {
1782 schoenebeck 1050 hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1783 schoenebeck 780 throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1784     }
1785     #endif
1786     __resetPos(); // reset read/write position of ALL 'Chunk' objects
1787 schoenebeck 798 break;
1788     case stream_mode_closed:
1789     #if POSIX
1790     if (hFileRead) close(hFileRead);
1791     if (hFileWrite) close(hFileWrite);
1792 schoenebeck 1050 #elif defined(WIN32)
1793     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1794     if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1795 schoenebeck 798 #else
1796     if (hFileRead) fclose(hFileRead);
1797     if (hFileWrite) fclose(hFileWrite);
1798     #endif
1799     hFileRead = hFileWrite = 0;
1800     break;
1801 schoenebeck 780 default:
1802     throw Exception("Unknown file access mode");
1803     }
1804 schoenebeck 798 Mode = NewMode;
1805     return true;
1806 schoenebeck 780 }
1807     return false;
1808     }
1809    
1810 persson 1184 /** @brief Set the byte order to be used when saving.
1811     *
1812     * Set the byte order to be used in the file. A value of
1813     * endian_little will create a RIFF file, endian_big a RIFX file
1814     * and endian_native will create a RIFF file on little-endian
1815     * machines and RIFX on big-endian machines.
1816     *
1817     * @param Endian - endianess to use when file is saved.
1818     */
1819     void File::SetByteOrder(endian_t Endian) {
1820     #if WORDS_BIGENDIAN
1821     bEndianNative = Endian != endian_little;
1822     #else
1823     bEndianNative = Endian != endian_big;
1824     #endif
1825     }
1826    
1827 schoenebeck 780 /** @brief Save changes to same file.
1828     *
1829     * Make all changes of all chunks persistent by writing them to the
1830 schoenebeck 2912 * actual (same) file.
1831 schoenebeck 780 *
1832 schoenebeck 2682 * @param pProgress - optional: callback function for progress notification
1833 schoenebeck 780 * @throws RIFF::Exception if there is an empty chunk or empty list
1834     * chunk or any kind of IO error occured
1835     */
1836 schoenebeck 2682 void File::Save(progress_t* pProgress) {
1837 schoenebeck 2543 //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1838     if (Layout == layout_flat)
1839     throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1840    
1841 schoenebeck 833 // make sure the RIFF tree is built (from the original file)
1842 schoenebeck 2682 {
1843     // divide progress into subprogress
1844     progress_t subprogress;
1845     __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
1846     // do the actual work
1847     LoadSubChunksRecursively(&subprogress);
1848     // notify subprogress done
1849     __notify_progress(&subprogress, 1.f);
1850     }
1851 schoenebeck 833
1852 schoenebeck 780 // reopen file in write mode
1853 schoenebeck 798 SetMode(stream_mode_read_write);
1854 schoenebeck 780
1855 schoenebeck 2912 // get the current file size as it is now still physically stored on disk
1856     const file_offset_t workingFileSize = GetCurrentFileSize();
1857    
1858     // get the overall file size required to save this file
1859     const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1860    
1861     // determine whether this file will yield in a large file (>=4GB) and
1862     // the RIFF file offset size to be used accordingly for all chunks
1863     FileOffsetSize = FileOffsetSizeFor(newFileSize);
1864    
1865 schoenebeck 780 // to be able to save the whole file without loading everything into
1866     // RAM and without having to store the data in a temporary file, we
1867 schoenebeck 2912 // enlarge the file with the overall positive file size change,
1868     // then move current data towards the end of the file by the calculated
1869     // positive file size difference and finally update / rewrite the file
1870     // by copying the old data back to the right position at the beginning
1871     // of the file
1872 schoenebeck 780
1873 schoenebeck 2912 // if there are positive size changes...
1874     file_offset_t positiveSizeDiff = 0;
1875     if (newFileSize > workingFileSize) {
1876     positiveSizeDiff = newFileSize - workingFileSize;
1877 schoenebeck 780
1878 schoenebeck 2682 // divide progress into subprogress
1879     progress_t subprogress;
1880     __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1881    
1882 schoenebeck 780 // ... we enlarge this file first ...
1883 schoenebeck 2912 ResizeFile(newFileSize);
1884    
1885 schoenebeck 780 // ... and move current data by the same amount towards end of file.
1886     int8_t* pCopyBuffer = new int8_t[4096];
1887 schoenebeck 1050 #if defined(WIN32)
1888     DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1889     #else
1890 schoenebeck 1459 int iBytesMoved = 1;
1891 schoenebeck 1050 #endif
1892 schoenebeck 2912 for (file_offset_t ullPos = workingFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1893     iBytesMoved = (ullPos < 4096) ? ullPos : 4096;
1894     ullPos -= iBytesMoved;
1895 schoenebeck 780 #if POSIX
1896 schoenebeck 2912 lseek(hFileRead, ullPos, SEEK_SET);
1897 schoenebeck 780 iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1898 schoenebeck 2912 lseek(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1899 schoenebeck 780 iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1900 schoenebeck 1050 #elif defined(WIN32)
1901 schoenebeck 2912 SetFilePointerEx(hFileRead, ullPos, NULL/*new pos pointer*/, FILE_BEGIN);
1902 schoenebeck 1050 ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1903 schoenebeck 2912 SetFilePointerEx(hFileWrite, ullPos + positiveSizeDiff, NULL/*new pos pointer*/, FILE_BEGIN);
1904 schoenebeck 1050 WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1905 schoenebeck 780 #else
1906 schoenebeck 2912 fseeko(hFileRead, ullPos, SEEK_SET);
1907 schoenebeck 780 iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
1908 schoenebeck 2912 fseeko(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1909 schoenebeck 780 iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1910     #endif
1911 schoenebeck 2682 if (!(iNotif % 8) && iBytesMoved > 0)
1912 schoenebeck 2912 __notify_progress(&subprogress, float(workingFileSize - ullPos) / float(workingFileSize));
1913 schoenebeck 780 }
1914     delete[] pCopyBuffer;
1915     if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1916 schoenebeck 2682
1917     __notify_progress(&subprogress, 1.f); // notify subprogress done
1918 schoenebeck 780 }
1919    
1920 schoenebeck 2682 // rebuild / rewrite complete RIFF tree ...
1921    
1922     // divide progress into subprogress
1923     progress_t subprogress;
1924     __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
1925     // do the actual work
1926 schoenebeck 2912 const file_offset_t finalSize = WriteChunk(0, positiveSizeDiff, &subprogress);
1927     const file_offset_t finalActualSize = __GetFileSize(hFileWrite);
1928 schoenebeck 2682 // notify subprogress done
1929     __notify_progress(&subprogress, 1.f);
1930 schoenebeck 780
1931     // resize file to the final size
1932 schoenebeck 2912 if (finalSize < finalActualSize) ResizeFile(finalSize);
1933 schoenebeck 780
1934 schoenebeck 2682 __notify_progress(pProgress, 1.0); // notify done
1935 schoenebeck 780 }
1936    
1937     /** @brief Save changes to another file.
1938     *
1939     * Make all changes of all chunks persistent by writing them to another
1940     * file. <b>Caution:</b> this method is optimized for writing to
1941     * <b>another</b> file, do not use it to save the changes to the same
1942 schoenebeck 798 * file! Use File::Save() in that case instead! Ignoring this might
1943     * result in a corrupted file, especially in case chunks were resized!
1944 schoenebeck 780 *
1945     * After calling this method, this File object will be associated with
1946     * the new file (given by \a path) afterwards.
1947     *
1948     * @param path - path and file name where everything should be written to
1949 schoenebeck 2682 * @param pProgress - optional: callback function for progress notification
1950 schoenebeck 780 */
1951 schoenebeck 2682 void File::Save(const String& path, progress_t* pProgress) {
1952 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
1953    
1954 schoenebeck 2543 //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1955     if (Layout == layout_flat)
1956     throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1957    
1958 schoenebeck 833 // make sure the RIFF tree is built (from the original file)
1959 schoenebeck 2682 {
1960     // divide progress into subprogress
1961     progress_t subprogress;
1962     __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
1963     // do the actual work
1964     LoadSubChunksRecursively(&subprogress);
1965     // notify subprogress done
1966     __notify_progress(&subprogress, 1.f);
1967     }
1968 schoenebeck 833
1969 schoenebeck 2482 if (!bIsNewFile) SetMode(stream_mode_read);
1970 schoenebeck 780 // open the other (new) file for writing and truncate it to zero size
1971     #if POSIX
1972 schoenebeck 798 hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1973 schoenebeck 2675 if (hFileWrite == -1) {
1974 schoenebeck 780 hFileWrite = hFileRead;
1975 schoenebeck 2675 String sError = strerror(errno);
1976     throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
1977 schoenebeck 780 }
1978 schoenebeck 1050 #elif defined(WIN32)
1979     hFileWrite = CreateFile(
1980     path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1981 schoenebeck 1459 NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1982     FILE_FLAG_RANDOM_ACCESS, NULL
1983 schoenebeck 1050 );
1984     if (hFileWrite == INVALID_HANDLE_VALUE) {
1985     hFileWrite = hFileRead;
1986     throw Exception("Could not open file \"" + path + "\" for writing");
1987     }
1988 schoenebeck 780 #else
1989     hFileWrite = fopen(path.c_str(), "w+b");
1990     if (!hFileWrite) {
1991     hFileWrite = hFileRead;
1992     throw Exception("Could not open file \"" + path + "\" for writing");
1993     }
1994     #endif // POSIX
1995 schoenebeck 798 Mode = stream_mode_read_write;
1996 schoenebeck 780
1997 schoenebeck 2912 // get the overall file size required to save this file
1998     const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1999    
2000     // determine whether this file will yield in a large file (>=4GB) and
2001     // the RIFF file offset size to be used accordingly for all chunks
2002     FileOffsetSize = FileOffsetSizeFor(newFileSize);
2003    
2004 schoenebeck 780 // write complete RIFF tree to the other (new) file
2005 schoenebeck 2912 file_offset_t ullTotalSize;
2006 schoenebeck 2682 {
2007     // divide progress into subprogress
2008     progress_t subprogress;
2009     __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
2010     // do the actual work
2011 schoenebeck 2912 ullTotalSize = WriteChunk(0, 0, &subprogress);
2012 schoenebeck 2682 // notify subprogress done
2013     __notify_progress(&subprogress, 1.f);
2014     }
2015 schoenebeck 2912 file_offset_t ullActualSize = __GetFileSize(hFileWrite);
2016 schoenebeck 780
2017 schoenebeck 798 // resize file to the final size (if the file was originally larger)
2018 schoenebeck 2912 if (ullActualSize > ullTotalSize) ResizeFile(ullTotalSize);
2019 schoenebeck 798
2020 persson 1301 #if POSIX
2021     if (hFileWrite) close(hFileWrite);
2022     #elif defined(WIN32)
2023     if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
2024     #else
2025     if (hFileWrite) fclose(hFileWrite);
2026     #endif
2027     hFileWrite = hFileRead;
2028 schoenebeck 798
2029 schoenebeck 780 // associate new file with this File object from now on
2030     Filename = path;
2031 schoenebeck 2482 bIsNewFile = false;
2032 schoenebeck 798 Mode = (stream_mode_t) -1; // Just set it to an undefined mode ...
2033     SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
2034 schoenebeck 2682
2035     __notify_progress(pProgress, 1.0); // notify done
2036 schoenebeck 780 }
2037    
2038 schoenebeck 2912 void File::ResizeFile(file_offset_t ullNewSize) {
2039 schoenebeck 780 #if POSIX
2040 schoenebeck 2912 if (ftruncate(hFileWrite, ullNewSize) < 0)
2041 schoenebeck 780 throw Exception("Could not resize file \"" + Filename + "\"");
2042 schoenebeck 1050 #elif defined(WIN32)
2043     if (
2044 schoenebeck 2912 !SetFilePointerEx(hFileWrite, ullNewSize, NULL/*new pos pointer*/, FILE_BEGIN) ||
2045 schoenebeck 1050 !SetEndOfFile(hFileWrite)
2046     ) throw Exception("Could not resize file \"" + Filename + "\"");
2047 schoenebeck 780 #else
2048 schoenebeck 1050 # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
2049 schoenebeck 798 # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
2050 schoenebeck 780 #endif
2051     }
2052    
2053 schoenebeck 2 File::~File() {
2054 schoenebeck 2912 #if DEBUG
2055     std::cout << "File::~File()" << std::endl;
2056     #endif // DEBUG
2057 persson 2155 Cleanup();
2058     }
2059 schoenebeck 2912
2060 schoenebeck 2482 /**
2061     * Returns @c true if this file has been created new from scratch and
2062     * has not been stored to disk yet.
2063     */
2064     bool File::IsNew() const {
2065     return bIsNewFile;
2066     }
2067 persson 2155
2068     void File::Cleanup() {
2069 schoenebeck 2 #if POSIX
2070 schoenebeck 780 if (hFileRead) close(hFileRead);
2071 schoenebeck 1050 #elif defined(WIN32)
2072     if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
2073 schoenebeck 2 #else
2074 schoenebeck 780 if (hFileRead) fclose(hFileRead);
2075 schoenebeck 2 #endif // POSIX
2076 persson 1869 DeleteChunkList();
2077     pFile = NULL;
2078 schoenebeck 2 }
2079    
2080 schoenebeck 2912 /**
2081     * Returns the current size of this file (in bytes) as it is currently
2082     * yet stored on disk. If this file does not yet exist on disk (i.e. when
2083     * this RIFF File has just been created from scratch and Save() has not
2084     * been called yet) then this method returns 0.
2085     */
2086     file_offset_t File::GetCurrentFileSize() const {
2087     file_offset_t size = 0;
2088     try {
2089     size = __GetFileSize(hFileRead);
2090     } catch (...) {
2091     size = 0;
2092     }
2093     return size;
2094 schoenebeck 780 }
2095    
2096 schoenebeck 2912 /**
2097     * Returns the required size (in bytes) for this RIFF File to be saved to
2098     * disk. The precise size of the final file on disk depends on the RIFF
2099     * file offset size actually used internally in all headers of the RIFF
2100     * chunks. By default libgig handles the required file offset size
2101     * automatically for you; that means it is using 32 bit offsets for files
2102     * smaller than 4 GB and 64 bit offsets for files equal or larger than
2103     * 4 GB. You may however also override this default behavior by passing the
2104     * respective option to the RIFF File constructor to force one particular
2105     * offset size. In the latter case this method will return the file size
2106     * for the requested forced file offset size that will be used when calling
2107     * Save() later on.
2108     *
2109     * You may also use the overridden method below to get the file size for
2110     * an arbitrary other file offset size instead.
2111     *
2112     * @see offset_size_t
2113     * @see GetFileOffsetSize()
2114     */
2115     file_offset_t File::GetRequiredFileSize() {
2116     return GetRequiredFileSize(FileOffsetPreference);
2117 schoenebeck 1095 }
2118    
2119 schoenebeck 2912 /**
2120     * Returns the rquired size (in bytes) for this RIFF file to be saved to
2121     * disk, assuming the passed @a fileOffsestSize would be used for the
2122     * Save() operation.
2123     *
2124     * This overridden method essentialy behaves like the above method, with
2125     * the difference that you must provide a specific RIFF @a fileOffsetSize
2126     * for calculating the theoretical final file size.
2127     *
2128     * @see GetFileOffsetSize()
2129     */
2130     file_offset_t File::GetRequiredFileSize(offset_size_t fileOffsetSize) {
2131     switch (fileOffsetSize) {
2132     case offset_size_auto: {
2133     file_offset_t fileSize = GetRequiredFileSize(offset_size_32bit);
2134     if (fileSize >> 32)
2135     return GetRequiredFileSize(offset_size_64bit);
2136     else
2137     return fileSize;
2138     }
2139     case offset_size_32bit: break;
2140     case offset_size_64bit: break;
2141     default: throw Exception("Internal error: Invalid RIFF::offset_size_t");
2142     }
2143     return RequiredPhysicalSize(FileOffsetSize);
2144 schoenebeck 798 }
2145    
2146 schoenebeck 2912 int File::FileOffsetSizeFor(file_offset_t fileSize) const {
2147     switch (FileOffsetPreference) {
2148     case offset_size_auto:
2149     return (fileSize >> 32) ? 8 : 4;
2150     case offset_size_32bit:
2151     return 4;
2152     case offset_size_64bit:
2153     return 8;
2154     default:
2155     throw Exception("Internal error: Invalid RIFF::offset_size_t");
2156     }
2157     }
2158    
2159     /**
2160     * Returns the current size (in bytes) of file offsets stored in the
2161     * headers of all chunks of this file.
2162     *
2163     * Most RIFF files are using 32 bit file offsets internally, which limits
2164     * them to a maximum file size of less than 4 GB though. In contrast to the
2165     * common standard, this RIFF File class implementation supports handling of
2166     * RIFF files equal or larger than 4 GB. In such cases 64 bit file offsets
2167     * have to be used in all headers of all RIFF Chunks when being stored to a
2168     * physical file. libgig by default automatically selects the correct file
2169     * offset size for you. You may however also force one particular file
2170     * offset size by supplying the respective option to the RIFF::File
2171     * constructor.
2172     *
2173     * This method can be used to check which RIFF file offset size is currently
2174     * being used for this RIFF File.
2175     *
2176     * @returns current RIFF file offset size used (in bytes)
2177     * @see offset_size_t
2178     */
2179     int File::GetFileOffsetSize() const {
2180     return FileOffsetSize;
2181     }
2182    
2183     /**
2184     * Returns the required size (in bytes) of file offsets stored in the
2185     * headers of all chunks of this file if the current RIFF tree would be
2186     * saved to disk by calling Save().
2187     *
2188     * See GetFileOffsetSize() for mor details about RIFF file offsets.
2189     *
2190     * @returns RIFF file offset size required (in bytes) if being saved
2191     * @see offset_size_t
2192     */
2193     int File::GetRequiredFileOffsetSize() {
2194     return FileOffsetSizeFor(GetCurrentFileSize());
2195     }
2196    
2197 schoenebeck 798 #if POSIX
2198 schoenebeck 2912 file_offset_t File::__GetFileSize(int hFile) const {
2199 schoenebeck 2 struct stat filestat;
2200 schoenebeck 2912 if (fstat(hFile, &filestat) == -1)
2201     throw Exception("POSIX FS error: could not determine file size");
2202     return filestat.st_size;
2203 schoenebeck 2 }
2204 schoenebeck 1050 #elif defined(WIN32)
2205 schoenebeck 2912 file_offset_t File::__GetFileSize(HANDLE hFile) const {
2206     PLARGE_INTEGER size;
2207     if (!GetFileSizeEx(hFile, &size))
2208 schoenebeck 1063 throw Exception("Windows FS error: could not determine file size");
2209 schoenebeck 2912 return size;
2210 schoenebeck 1050 }
2211 schoenebeck 798 #else // standard C functions
2212 schoenebeck 2912 file_offset_t File::__GetFileSize(FILE* hFile) const {
2213     off_t curpos = ftello(hFile);
2214     if (fseeko(hFile, 0, SEEK_END) == -1)
2215     throw Exception("FS error: could not determine file size");
2216     off_t size = ftello(hFile);
2217     fseeko(hFile, curpos, SEEK_SET);
2218 schoenebeck 798 return size;
2219     }
2220     #endif
2221 schoenebeck 2
2222    
2223     // *************** Exception ***************
2224     // *
2225    
2226     void Exception::PrintMessage() {
2227     std::cout << "RIFF::Exception: " << Message << std::endl;
2228     }
2229    
2230 schoenebeck 518
2231     // *************** functions ***************
2232     // *
2233    
2234     /**
2235     * Returns the name of this C++ library. This is usually "libgig" of
2236     * course. This call is equivalent to DLS::libraryName() and
2237     * gig::libraryName().
2238     */
2239     String libraryName() {
2240     return PACKAGE;
2241     }
2242    
2243     /**
2244     * Returns version of this C++ library. This call is equivalent to
2245     * DLS::libraryVersion() and gig::libraryVersion().
2246     */
2247     String libraryVersion() {
2248     return VERSION;
2249     }
2250    
2251 schoenebeck 2 } // namespace RIFF

  ViewVC Help
Powered by ViewVC