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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3481 - (show annotations) (download)
Fri Feb 22 12:12:50 2019 UTC (5 years, 1 month ago) by schoenebeck
File size: 99319 byte(s)
* gig.h, gig.cpp: Added File::GetRiffFile() method.
* DLS.h, DLS.cpp: Added File::GetRiffFile() method.
* sf2.h, sf2.cpp: Added Sample::GetFile() and
  File::GetRiffFile() methods.
* RIFF.h, RIFF.cpp: Added a 2nd (overridden)
  progress_t::subdivide() method which allows a more
  fine graded control into which portions the subtasks
  are divided to.
* RIFF Fix: API doc comment for Chunk::GetFilePos() was
  completely wrong.
* Bumped version (4.1.0.svn14).

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

  ViewVC Help
Powered by ViewVC