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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2914 - (hide annotations) (download)
Tue May 17 19:04:56 2016 UTC (7 years, 11 months ago) by schoenebeck
File size: 95773 byte(s)
* Fixed compile error on Windows.

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

  ViewVC Help
Powered by ViewVC