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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3912 - (hide annotations) (download)
Fri Jun 4 11:20:19 2021 UTC (2 years, 11 months ago) by schoenebeck
File size: 100496 byte(s)
- RIFF.cpp: fix API comment of File::SetMode()

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

  ViewVC Help
Powered by ViewVC