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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

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

  ViewVC Help
Powered by ViewVC