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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2543 - (show annotations) (download)
Sat May 10 02:06:58 2014 UTC (9 years, 10 months ago) by schoenebeck
File size: 81599 byte(s)
* Initial support for sample based instruments in KORG's file format (.KMP
  and .KSF files) -> Korg.h, Korg.cpp.
* Added new command line tool "korgdump" (and a man page for it).
* Added new command line tool "korg2gig" (and a man page for it), for
  converting KORG sounds to Giga format.
* riftree tool: Added more command line options for being able to also dump
  other kind of file formats similar but not equal to the RIFF format.
* gig.h/.cpp: Added new method File::GetGroup(String name) for retrieving
  group by name.
* RIFF.h/.cpp: Added support for loading RIFF-like files with a bit
  different layout than "real" RIFF files (used for KORG format support).
* RIFF.h/.cpp: Added new method Chunk::GetFile().
* RIFF.h/.cpp: Added new method Chunk::GetLayout().
* Bumped version (3.3.0.svn9).

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

  ViewVC Help
Powered by ViewVC