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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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

  ViewVC Help
Powered by ViewVC