libgig  4.3.0
RIFF.cpp
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 
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 
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 
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 
264  String Chunk::GetChunkIDString() const {
265  return convertToString(ChunkID);
266  }
267 
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 
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 
327  return CHUNK_HEADER_SIZE(fileOffsetSize) + // RIFF chunk header
328  ullNewChunkSize + // chunks's actual data body
329  ullNewChunkSize % 2; // optional pad byte
330  }
331 
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 
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 
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 
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 
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 
538  file_offset_t Chunk::WriteInt8(int8_t* pData, file_offset_t WordCount) {
539  return Write(pData, WordCount, 1);
540  }
541 
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 
575  file_offset_t Chunk::WriteUint8(uint8_t* pData, file_offset_t WordCount) {
576  return Write(pData, WordCount, 1);
577  }
578 
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 
612  file_offset_t Chunk::WriteInt16(int16_t* pData, file_offset_t WordCount) {
613  return Write(pData, WordCount, 2);
614  }
615 
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 
649  file_offset_t Chunk::WriteUint16(uint16_t* pData, file_offset_t WordCount) {
650  return Write(pData, WordCount, 2);
651  }
652 
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 
686  file_offset_t Chunk::WriteInt32(int32_t* pData, file_offset_t WordCount) {
687  return Write(pData, WordCount, 4);
688  }
689 
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 
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 
740  file_offset_t Chunk::WriteUint32(uint32_t* pData, file_offset_t WordCount) {
741  return Write(pData, WordCount, 4);
742  }
743 
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 
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 
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 
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 
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 
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 
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 
912  if (pChunkData) {
913  delete[] pChunkData;
914  pChunkData = NULL;
915  }
916  }
917 
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 
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  if (pProgress)
1030  __notify_progress(pProgress, 1.0); // notify done
1031 
1032  // update chunk's position pointers
1033  ullStartPos = ullOriginalPos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1034  ullPos = 0;
1035 
1036  // add pad byte if needed
1037  if ((ullStartPos + ullNewChunkSize) % 2 != 0) {
1038  const char cPadByte = 0;
1039  #if POSIX
1040  lseek(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
1041  write(pFile->hFileWrite, &cPadByte, 1);
1042  #elif defined(WIN32)
1043  LARGE_INTEGER liFilePos;
1044  liFilePos.QuadPart = ullStartPos + ullNewChunkSize;
1045  SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1046  DWORD dwBytesWritten;
1047  WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
1048  #else
1049  fseeko(pFile->hFileWrite, ullStartPos + ullNewChunkSize, SEEK_SET);
1050  fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
1051  #endif
1052  return ullStartPos + ullNewChunkSize + 1;
1053  }
1054 
1055  return ullStartPos + ullNewChunkSize;
1056  }
1057 
1059  ullPos = 0;
1060  }
1061 
1062 
1063 
1064 // *************** List ***************
1065 // *
1066 
1067  List::List(File* pFile) : Chunk(pFile) {
1068  #if DEBUG_RIFF
1069  std::cout << "List::List(File* pFile)" << std::endl;
1070  #endif // DEBUG_RIFF
1071  pSubChunks = NULL;
1072  pSubChunksMap = NULL;
1073  }
1074 
1075  List::List(File* pFile, file_offset_t StartPos, List* Parent)
1076  : Chunk(pFile, StartPos, Parent) {
1077  #if DEBUG_RIFF
1078  std::cout << "List::List(File*,file_offset_t,List*)" << std::endl;
1079  #endif // DEBUG_RIFF
1080  pSubChunks = NULL;
1081  pSubChunksMap = NULL;
1082  ReadHeader(StartPos);
1083  ullStartPos = StartPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1084  }
1085 
1086  List::List(File* pFile, List* pParent, uint32_t uiListID)
1087  : Chunk(pFile, pParent, CHUNK_ID_LIST, 0) {
1088  pSubChunks = NULL;
1089  pSubChunksMap = NULL;
1090  ListType = uiListID;
1091  }
1092 
1093  List::~List() {
1094  #if DEBUG_RIFF
1095  std::cout << "List::~List()" << std::endl;
1096  #endif // DEBUG_RIFF
1097  DeleteChunkList();
1098  }
1099 
1100  void List::DeleteChunkList() {
1101  if (pSubChunks) {
1102  ChunkList::iterator iter = pSubChunks->begin();
1103  ChunkList::iterator end = pSubChunks->end();
1104  while (iter != end) {
1105  delete *iter;
1106  iter++;
1107  }
1108  delete pSubChunks;
1109  pSubChunks = NULL;
1110  }
1111  if (pSubChunksMap) {
1112  delete pSubChunksMap;
1113  pSubChunksMap = NULL;
1114  }
1115  }
1116 
1128  Chunk* List::GetSubChunk(uint32_t ChunkID) {
1129  #if DEBUG_RIFF
1130  std::cout << "List::GetSubChunk(uint32_t)" << std::endl;
1131  #endif // DEBUG_RIFF
1132  if (!pSubChunksMap) LoadSubChunks();
1133  return (*pSubChunksMap)[ChunkID];
1134  }
1135 
1147  List* List::GetSubList(uint32_t ListType) {
1148  #if DEBUG_RIFF
1149  std::cout << "List::GetSubList(uint32_t)" << std::endl;
1150  #endif // DEBUG_RIFF
1151  if (!pSubChunks) LoadSubChunks();
1152  ChunkList::iterator iter = pSubChunks->begin();
1153  ChunkList::iterator end = pSubChunks->end();
1154  while (iter != end) {
1155  if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1156  List* l = (List*) *iter;
1157  if (l->GetListType() == ListType) return l;
1158  }
1159  iter++;
1160  }
1161  return NULL;
1162  }
1163 
1174  #if DEBUG_RIFF
1175  std::cout << "List::GetFirstSubChunk()" << std::endl;
1176  #endif // DEBUG_RIFF
1177  if (!pSubChunks) LoadSubChunks();
1178  ChunksIterator = pSubChunks->begin();
1179  return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1180  }
1181 
1191  #if DEBUG_RIFF
1192  std::cout << "List::GetNextSubChunk()" << std::endl;
1193  #endif // DEBUG_RIFF
1194  if (!pSubChunks) return NULL;
1195  ChunksIterator++;
1196  return (ChunksIterator != pSubChunks->end()) ? *ChunksIterator : NULL;
1197  }
1198 
1209  #if DEBUG_RIFF
1210  std::cout << "List::GetFirstSubList()" << std::endl;
1211  #endif // DEBUG_RIFF
1212  if (!pSubChunks) LoadSubChunks();
1213  ListIterator = pSubChunks->begin();
1214  ChunkList::iterator end = pSubChunks->end();
1215  while (ListIterator != end) {
1216  if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1217  ListIterator++;
1218  }
1219  return NULL;
1220  }
1221 
1231  #if DEBUG_RIFF
1232  std::cout << "List::GetNextSubList()" << std::endl;
1233  #endif // DEBUG_RIFF
1234  if (!pSubChunks) return NULL;
1235  if (ListIterator == pSubChunks->end()) return NULL;
1236  ListIterator++;
1237  ChunkList::iterator end = pSubChunks->end();
1238  while (ListIterator != end) {
1239  if ((*ListIterator)->GetChunkID() == CHUNK_ID_LIST) return (List*) *ListIterator;
1240  ListIterator++;
1241  }
1242  return NULL;
1243  }
1244 
1249  if (!pSubChunks) LoadSubChunks();
1250  return pSubChunks->size();
1251  }
1252 
1257  size_t List::CountSubChunks(uint32_t ChunkID) {
1258  size_t result = 0;
1259  if (!pSubChunks) LoadSubChunks();
1260  ChunkList::iterator iter = pSubChunks->begin();
1261  ChunkList::iterator end = pSubChunks->end();
1262  while (iter != end) {
1263  if ((*iter)->GetChunkID() == ChunkID) {
1264  result++;
1265  }
1266  iter++;
1267  }
1268  return result;
1269  }
1270 
1275  return CountSubChunks(CHUNK_ID_LIST);
1276  }
1277 
1282  size_t List::CountSubLists(uint32_t ListType) {
1283  size_t result = 0;
1284  if (!pSubChunks) LoadSubChunks();
1285  ChunkList::iterator iter = pSubChunks->begin();
1286  ChunkList::iterator end = pSubChunks->end();
1287  while (iter != end) {
1288  if ((*iter)->GetChunkID() == CHUNK_ID_LIST) {
1289  List* l = (List*) *iter;
1290  if (l->GetListType() == ListType) result++;
1291  }
1292  iter++;
1293  }
1294  return result;
1295  }
1296 
1310  Chunk* List::AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize) {
1311  if (ullBodySize == 0) throw Exception("Chunk body size must be at least 1 byte");
1312  if (!pSubChunks) LoadSubChunks();
1313  Chunk* pNewChunk = new Chunk(pFile, this, uiChunkID, 0);
1314  pSubChunks->push_back(pNewChunk);
1315  (*pSubChunksMap)[uiChunkID] = pNewChunk;
1316  pNewChunk->Resize(ullBodySize);
1317  ullNewChunkSize += CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1318  return pNewChunk;
1319  }
1320 
1332  void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1333  if (!pSubChunks) LoadSubChunks();
1334  pSubChunks->remove(pSrc);
1335  ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1336  pSubChunks->insert(iter, pSrc);
1337  }
1338 
1347  void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1348  if (pNewParent == this || !pNewParent) return;
1349  if (!pSubChunks) LoadSubChunks();
1350  if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1351  pSubChunks->remove(pSrc);
1352  pNewParent->pSubChunks->push_back(pSrc);
1353  // update chunk id map of this List
1354  if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1355  pSubChunksMap->erase(pSrc->GetChunkID());
1356  // try to find another chunk of the same chunk ID
1357  ChunkList::iterator iter = pSubChunks->begin();
1358  ChunkList::iterator end = pSubChunks->end();
1359  for (; iter != end; ++iter) {
1360  if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1361  (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1362  break; // we're done, stop search
1363  }
1364  }
1365  }
1366  // update chunk id map of other list
1367  if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1368  (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1369  }
1370 
1380  List* List::AddSubList(uint32_t uiListType) {
1381  if (!pSubChunks) LoadSubChunks();
1382  List* pNewListChunk = new List(pFile, this, uiListType);
1383  pSubChunks->push_back(pNewListChunk);
1384  (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1385  ullNewChunkSize += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1386  return pNewListChunk;
1387  }
1388 
1399  void List::DeleteSubChunk(Chunk* pSubChunk) {
1400  if (!pSubChunks) LoadSubChunks();
1401  pSubChunks->remove(pSubChunk);
1402  if ((*pSubChunksMap)[pSubChunk->GetChunkID()] == pSubChunk) {
1403  pSubChunksMap->erase(pSubChunk->GetChunkID());
1404  // try to find another chunk of the same chunk ID
1405  ChunkList::iterator iter = pSubChunks->begin();
1406  ChunkList::iterator end = pSubChunks->end();
1407  for (; iter != end; ++iter) {
1408  if ((*iter)->GetChunkID() == pSubChunk->GetChunkID()) {
1409  (*pSubChunksMap)[pSubChunk->GetChunkID()] = *iter;
1410  break; // we're done, stop search
1411  }
1412  }
1413  }
1414  delete pSubChunk;
1415  }
1416 
1425  if (!pSubChunks) LoadSubChunks();
1426  file_offset_t size = LIST_HEADER_SIZE(fileOffsetSize);
1427  ChunkList::iterator iter = pSubChunks->begin();
1428  ChunkList::iterator end = pSubChunks->end();
1429  for (; iter != end; ++iter)
1430  size += (*iter)->RequiredPhysicalSize(fileOffsetSize);
1431  return size;
1432  }
1433 
1434  void List::ReadHeader(file_offset_t filePos) {
1435  #if DEBUG_RIFF
1436  std::cout << "List::Readheader(file_offset_t) ";
1437  #endif // DEBUG_RIFF
1438  Chunk::ReadHeader(filePos);
1439  if (ullCurrentChunkSize < 4) return;
1440  ullNewChunkSize = ullCurrentChunkSize -= 4;
1441  #if POSIX
1442  lseek(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1443  read(pFile->hFileRead, &ListType, 4);
1444  #elif defined(WIN32)
1445  LARGE_INTEGER liFilePos;
1446  liFilePos.QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1447  SetFilePointerEx(pFile->hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1448  DWORD dwBytesRead;
1449  ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1450  #else
1451  fseeko(pFile->hFileRead, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1452  fread(&ListType, 4, 1, pFile->hFileRead);
1453  #endif // POSIX
1454  #if DEBUG_RIFF
1455  std::cout << "listType=" << convertToString(ListType) << std::endl;
1456  #endif // DEBUG_RIFF
1457  if (!pFile->bEndianNative) {
1458  //swapBytes_32(&ListType);
1459  }
1460  }
1461 
1462  void List::WriteHeader(file_offset_t filePos) {
1463  // the four list type bytes officially belong the chunk's body in the RIFF format
1464  ullNewChunkSize += 4;
1465  Chunk::WriteHeader(filePos);
1466  ullNewChunkSize -= 4; // just revert the +4 incrementation
1467  #if POSIX
1468  lseek(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1469  write(pFile->hFileWrite, &ListType, 4);
1470  #elif defined(WIN32)
1471  LARGE_INTEGER liFilePos;
1472  liFilePos.QuadPart = filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize);
1473  SetFilePointerEx(pFile->hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1474  DWORD dwBytesWritten;
1475  WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1476  #else
1477  fseeko(pFile->hFileWrite, filePos + CHUNK_HEADER_SIZE(pFile->FileOffsetSize), SEEK_SET);
1478  fwrite(&ListType, 4, 1, pFile->hFileWrite);
1479  #endif // POSIX
1480  }
1481 
1482  void List::LoadSubChunks(progress_t* pProgress) {
1483  #if DEBUG_RIFF
1484  std::cout << "List::LoadSubChunks()";
1485  #endif // DEBUG_RIFF
1486  if (!pSubChunks) {
1487  pSubChunks = new ChunkList();
1488  pSubChunksMap = new ChunkMap();
1489  #if defined(WIN32)
1490  if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1491  #else
1492  if (!pFile->hFileRead) return;
1493  #endif
1494  file_offset_t ullOriginalPos = GetPos();
1495  SetPos(0); // jump to beginning of list chunk body
1496  while (RemainingBytes() >= CHUNK_HEADER_SIZE(pFile->FileOffsetSize)) {
1497  Chunk* ck;
1498  uint32_t ckid;
1499  Read(&ckid, 4, 1);
1500  #if DEBUG_RIFF
1501  std::cout << " ckid=" << convertToString(ckid) << std::endl;
1502  #endif // DEBUG_RIFF
1503  if (ckid == CHUNK_ID_LIST) {
1504  ck = new RIFF::List(pFile, ullStartPos + ullPos - 4, this);
1505  SetPos(ck->GetSize() + LIST_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1506  }
1507  else { // simple chunk
1508  ck = new RIFF::Chunk(pFile, ullStartPos + ullPos - 4, this);
1509  SetPos(ck->GetSize() + CHUNK_HEADER_SIZE(pFile->FileOffsetSize) - 4, RIFF::stream_curpos);
1510  }
1511  pSubChunks->push_back(ck);
1512  (*pSubChunksMap)[ckid] = ck;
1513  if (GetPos() % 2 != 0) SetPos(1, RIFF::stream_curpos); // jump over pad byte
1514  }
1515  SetPos(ullOriginalPos); // restore position before this call
1516  }
1517  if (pProgress)
1518  __notify_progress(pProgress, 1.0); // notify done
1519  }
1520 
1521  void List::LoadSubChunksRecursively(progress_t* pProgress) {
1522  const int n = (int) CountSubLists();
1523  int i = 0;
1524  for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList(), ++i) {
1525  if (pProgress) {
1526  // divide local progress into subprogress
1527  progress_t subprogress;
1528  __divide_progress(pProgress, &subprogress, n, i);
1529  // do the actual work
1530  pList->LoadSubChunksRecursively(&subprogress);
1531  } else
1532  pList->LoadSubChunksRecursively(NULL);
1533  }
1534  if (pProgress)
1535  __notify_progress(pProgress, 1.0); // notify done
1536  }
1537 
1553  file_offset_t List::WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t* pProgress) {
1554  const file_offset_t ullOriginalPos = ullWritePos;
1555  ullWritePos += LIST_HEADER_SIZE(pFile->FileOffsetSize);
1556 
1557  if (pFile->Mode != stream_mode_read_write)
1558  throw Exception("Cannot write list chunk, file has to be opened in read+write mode");
1559 
1560  // write all subchunks (including sub list chunks) recursively
1561  if (pSubChunks) {
1562  size_t i = 0;
1563  const size_t n = pSubChunks->size();
1564  for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1565  if (pProgress) {
1566  // divide local progress into subprogress for loading current Instrument
1567  progress_t subprogress;
1568  __divide_progress(pProgress, &subprogress, n, i);
1569  // do the actual work
1570  ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, &subprogress);
1571  } else
1572  ullWritePos = (*iter)->WriteChunk(ullWritePos, ullCurrentDataOffset, NULL);
1573  }
1574  }
1575 
1576  // update this list chunk's header
1577  ullCurrentChunkSize = ullNewChunkSize = ullWritePos - ullOriginalPos - LIST_HEADER_SIZE(pFile->FileOffsetSize);
1578  WriteHeader(ullOriginalPos);
1579 
1580  // offset of this list chunk in new written file may have changed
1581  ullStartPos = ullOriginalPos + LIST_HEADER_SIZE(pFile->FileOffsetSize);
1582 
1583  if (pProgress)
1584  __notify_progress(pProgress, 1.0); // notify done
1585 
1586  return ullWritePos;
1587  }
1588 
1591  if (pSubChunks) {
1592  for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {
1593  (*iter)->__resetPos();
1594  }
1595  }
1596  }
1597 
1601  String List::GetListTypeString() const {
1602  return convertToString(ListType);
1603  }
1604 
1605 
1606 
1607 // *************** File ***************
1608 // *
1609 
1624  File::File(uint32_t FileType)
1625  : List(this), bIsNewFile(true), Layout(layout_standard),
1626  FileOffsetPreference(offset_size_auto)
1627  {
1628  #if defined(WIN32)
1629  hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1630  #else
1631  hFileRead = hFileWrite = 0;
1632  #endif
1633  Mode = stream_mode_closed;
1634  bEndianNative = true;
1635  ListType = FileType;
1636  FileOffsetSize = 4;
1637  ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1638  }
1639 
1648  File::File(const String& path)
1649  : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard),
1650  FileOffsetPreference(offset_size_auto)
1651  {
1652  #if DEBUG_RIFF
1653  std::cout << "File::File("<<path<<")" << std::endl;
1654  #endif // DEBUG_RIFF
1655  bEndianNative = true;
1656  FileOffsetSize = 4;
1657  try {
1658  __openExistingFile(path);
1659  if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1660  throw RIFF::Exception("Not a RIFF file");
1661  }
1662  }
1663  catch (...) {
1664  Cleanup();
1665  throw;
1666  }
1667  }
1668 
1695  File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout, offset_size_t fileOffsetSize)
1696  : List(this), Filename(path), bIsNewFile(false), Layout(layout),
1697  FileOffsetPreference(fileOffsetSize)
1698  {
1699  SetByteOrder(Endian);
1700  if (fileOffsetSize < offset_size_auto || fileOffsetSize > offset_size_64bit)
1701  throw Exception("Invalid RIFF::offset_size_t");
1702  FileOffsetSize = 4;
1703  try {
1704  __openExistingFile(path, &FileType);
1705  }
1706  catch (...) {
1707  Cleanup();
1708  throw;
1709  }
1710  }
1711 
1722  void File::__openExistingFile(const String& path, uint32_t* FileType) {
1723  #if POSIX
1724  hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1725  if (hFileRead == -1) {
1726  hFileRead = hFileWrite = 0;
1727  String sError = strerror(errno);
1728  throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1729  }
1730  #elif defined(WIN32)
1731  hFileRead = hFileWrite = CreateFile(
1732  path.c_str(), GENERIC_READ,
1733  FILE_SHARE_READ | FILE_SHARE_WRITE,
1734  NULL, OPEN_EXISTING,
1735  FILE_ATTRIBUTE_NORMAL |
1736  FILE_FLAG_RANDOM_ACCESS, NULL
1737  );
1738  if (hFileRead == INVALID_HANDLE_VALUE) {
1739  hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1740  throw RIFF::Exception("Can't open \"" + path + "\"");
1741  }
1742  #else
1743  hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1744  if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1745  #endif // POSIX
1746  Mode = stream_mode_read;
1747 
1748  // determine RIFF file offset size to be used (in RIFF chunk headers)
1749  // according to the current file offset preference
1750  FileOffsetSize = FileOffsetSizeFor(GetCurrentFileSize());
1751 
1752  switch (Layout) {
1753  case layout_standard: // this is a normal RIFF file
1754  ullStartPos = RIFF_HEADER_SIZE(FileOffsetSize);
1755  ReadHeader(0);
1756  if (FileType && ChunkID != *FileType)
1757  throw RIFF::Exception("Invalid file container ID");
1758  break;
1759  case layout_flat: // non-standard RIFF-alike file
1760  ullStartPos = 0;
1761  ullNewChunkSize = ullCurrentChunkSize = GetCurrentFileSize();
1762  if (FileType) {
1763  uint32_t ckid;
1764  if (Read(&ckid, 4, 1) != 4) {
1765  throw RIFF::Exception("Invalid file header ID (premature end of header)");
1766  } else if (ckid != *FileType) {
1767  String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1768  throw RIFF::Exception("Invalid file header ID" + s);
1769  }
1770  SetPos(0); // reset to first byte of file
1771  }
1772  LoadSubChunks();
1773  break;
1774  }
1775  }
1776 
1777  String File::GetFileName() const {
1778  return Filename;
1779  }
1780 
1781  void File::SetFileName(const String& path) {
1782  Filename = path;
1783  }
1784 
1785  stream_mode_t File::GetMode() const {
1786  return Mode;
1787  }
1788 
1789  layout_t File::GetLayout() const {
1790  return Layout;
1791  }
1792 
1804  if (NewMode != Mode) {
1805  switch (NewMode) {
1806  case stream_mode_read:
1807  #if POSIX
1808  if (hFileRead) close(hFileRead);
1809  hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1810  if (hFileRead == -1) {
1811  hFileRead = hFileWrite = 0;
1812  String sError = strerror(errno);
1813  throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1814  }
1815  #elif defined(WIN32)
1816  if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1817  hFileRead = hFileWrite = CreateFile(
1818  Filename.c_str(), GENERIC_READ,
1819  FILE_SHARE_READ | FILE_SHARE_WRITE,
1820  NULL, OPEN_EXISTING,
1821  FILE_ATTRIBUTE_NORMAL |
1822  FILE_FLAG_RANDOM_ACCESS,
1823  NULL
1824  );
1825  if (hFileRead == INVALID_HANDLE_VALUE) {
1826  hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1827  throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1828  }
1829  #else
1830  if (hFileRead) fclose(hFileRead);
1831  hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1832  if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1833  #endif
1834  __resetPos(); // reset read/write position of ALL 'Chunk' objects
1835  break;
1836  case stream_mode_read_write:
1837  #if POSIX
1838  if (hFileRead) close(hFileRead);
1839  hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1840  if (hFileRead == -1) {
1841  hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1842  String sError = strerror(errno);
1843  throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1844  }
1845  #elif defined(WIN32)
1846  if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1847  hFileRead = hFileWrite = CreateFile(
1848  Filename.c_str(),
1849  GENERIC_READ | GENERIC_WRITE,
1850  FILE_SHARE_READ,
1851  NULL, OPEN_ALWAYS,
1852  FILE_ATTRIBUTE_NORMAL |
1853  FILE_FLAG_RANDOM_ACCESS,
1854  NULL
1855  );
1856  if (hFileRead == INVALID_HANDLE_VALUE) {
1857  hFileRead = hFileWrite = CreateFile(
1858  Filename.c_str(), GENERIC_READ,
1859  FILE_SHARE_READ | FILE_SHARE_WRITE,
1860  NULL, OPEN_EXISTING,
1861  FILE_ATTRIBUTE_NORMAL |
1862  FILE_FLAG_RANDOM_ACCESS,
1863  NULL
1864  );
1865  throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1866  }
1867  #else
1868  if (hFileRead) fclose(hFileRead);
1869  hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1870  if (!hFileRead) {
1871  hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1872  throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1873  }
1874  #endif
1875  __resetPos(); // reset read/write position of ALL 'Chunk' objects
1876  break;
1877  case stream_mode_closed:
1878  #if POSIX
1879  if (hFileRead) close(hFileRead);
1880  if (hFileWrite) close(hFileWrite);
1881  hFileRead = hFileWrite = 0;
1882  #elif defined(WIN32)
1883  if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1884  if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1885  hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1886  #else
1887  if (hFileRead) fclose(hFileRead);
1888  if (hFileWrite) fclose(hFileWrite);
1889  hFileRead = hFileWrite = NULL;
1890  #endif
1891  break;
1892  default:
1893  throw Exception("Unknown file access mode");
1894  }
1895  Mode = NewMode;
1896  return true;
1897  }
1898  return false;
1899  }
1900 
1911  #if WORDS_BIGENDIAN
1912  bEndianNative = Endian != endian_little;
1913  #else
1914  bEndianNative = Endian != endian_big;
1915  #endif
1916  }
1917 
1927  void File::Save(progress_t* pProgress) {
1928  //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1929  if (Layout == layout_flat)
1930  throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1931 
1932  // make sure the RIFF tree is built (from the original file)
1933  if (pProgress) {
1934  // divide progress into subprogress
1935  progress_t subprogress;
1936  __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
1937  // do the actual work
1938  LoadSubChunksRecursively(&subprogress);
1939  // notify subprogress done
1940  __notify_progress(&subprogress, 1.f);
1941  } else
1942  LoadSubChunksRecursively(NULL);
1943 
1944  // reopen file in write mode
1945  SetMode(stream_mode_read_write);
1946 
1947  // get the current file size as it is now still physically stored on disk
1948  const file_offset_t workingFileSize = GetCurrentFileSize();
1949 
1950  // get the overall file size required to save this file
1951  const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
1952 
1953  // determine whether this file will yield in a large file (>=4GB) and
1954  // the RIFF file offset size to be used accordingly for all chunks
1955  FileOffsetSize = FileOffsetSizeFor(newFileSize);
1956 
1957  // to be able to save the whole file without loading everything into
1958  // RAM and without having to store the data in a temporary file, we
1959  // enlarge the file with the overall positive file size change,
1960  // then move current data towards the end of the file by the calculated
1961  // positive file size difference and finally update / rewrite the file
1962  // by copying the old data back to the right position at the beginning
1963  // of the file
1964 
1965  // if there are positive size changes...
1966  file_offset_t positiveSizeDiff = 0;
1967  if (newFileSize > workingFileSize) {
1968  positiveSizeDiff = newFileSize - workingFileSize;
1969 
1970  // divide progress into subprogress
1971  progress_t subprogress;
1972  if (pProgress)
1973  __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1974 
1975  // ... we enlarge this file first ...
1976  ResizeFile(newFileSize);
1977 
1978  // ... and move current data by the same amount towards end of file.
1979  int8_t* pCopyBuffer = new int8_t[4096];
1980  #if defined(WIN32)
1981  DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1982  #else
1983  ssize_t iBytesMoved = 1;
1984  #endif
1985  for (file_offset_t ullPos = workingFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1986  iBytesMoved = (ullPos < 4096) ? ullPos : 4096;
1987  ullPos -= iBytesMoved;
1988  #if POSIX
1989  lseek(hFileRead, ullPos, SEEK_SET);
1990  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1991  lseek(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
1992  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1993  #elif defined(WIN32)
1994  LARGE_INTEGER liFilePos;
1995  liFilePos.QuadPart = ullPos;
1996  SetFilePointerEx(hFileRead, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
1997  ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1998  liFilePos.QuadPart = ullPos + positiveSizeDiff;
1999  SetFilePointerEx(hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN);
2000  WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
2001  #else
2002  fseeko(hFileRead, ullPos, SEEK_SET);
2003  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
2004  fseeko(hFileWrite, ullPos + positiveSizeDiff, SEEK_SET);
2005  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
2006  #endif
2007  if (pProgress && !(iNotif % 8) && iBytesMoved > 0)
2008  __notify_progress(&subprogress, float(workingFileSize - ullPos) / float(workingFileSize));
2009  }
2010  delete[] pCopyBuffer;
2011  if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
2012 
2013  if (pProgress)
2014  __notify_progress(&subprogress, 1.f); // notify subprogress done
2015  }
2016 
2017  // rebuild / rewrite complete RIFF tree ...
2018 
2019  // divide progress into subprogress
2020  progress_t subprogress;
2021  if (pProgress)
2022  __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
2023  // do the actual work
2024  const file_offset_t finalSize = WriteChunk(0, positiveSizeDiff, pProgress ? &subprogress : NULL);
2025  const file_offset_t finalActualSize = __GetFileSize(hFileWrite);
2026  // notify subprogress done
2027  if (pProgress)
2028  __notify_progress(&subprogress, 1.f);
2029 
2030  // resize file to the final size
2031  if (finalSize < finalActualSize) ResizeFile(finalSize);
2032 
2033  if (pProgress)
2034  __notify_progress(pProgress, 1.0); // notify done
2035  }
2036 
2051  void File::Save(const String& path, progress_t* pProgress) {
2052  //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
2053 
2054  //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
2055  if (Layout == layout_flat)
2056  throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
2057 
2058  // make sure the RIFF tree is built (from the original file)
2059  if (pProgress) {
2060  // divide progress into subprogress
2061  progress_t subprogress;
2062  __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
2063  // do the actual work
2064  LoadSubChunksRecursively(&subprogress);
2065  // notify subprogress done
2066  __notify_progress(&subprogress, 1.f);
2067  } else
2068  LoadSubChunksRecursively(NULL);
2069 
2070  if (!bIsNewFile) SetMode(stream_mode_read);
2071  // open the other (new) file for writing and truncate it to zero size
2072  #if POSIX
2073  hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
2074  if (hFileWrite == -1) {
2076  String sError = strerror(errno);
2077  throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
2078  }
2079  #elif defined(WIN32)
2080  hFileWrite = CreateFile(
2081  path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
2082  NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
2083  FILE_FLAG_RANDOM_ACCESS, NULL
2084  );
2085  if (hFileWrite == INVALID_HANDLE_VALUE) {
2087  throw Exception("Could not open file \"" + path + "\" for writing");
2088  }
2089  #else
2090  hFileWrite = fopen(path.c_str(), "w+b");
2091  if (!hFileWrite) {
2093  throw Exception("Could not open file \"" + path + "\" for writing");
2094  }
2095  #endif // POSIX
2096  Mode = stream_mode_read_write;
2097 
2098  // get the overall file size required to save this file
2099  const file_offset_t newFileSize = GetRequiredFileSize(FileOffsetPreference);
2100 
2101  // determine whether this file will yield in a large file (>=4GB) and
2102  // the RIFF file offset size to be used accordingly for all chunks
2103  FileOffsetSize = FileOffsetSizeFor(newFileSize);
2104 
2105  // write complete RIFF tree to the other (new) file
2106  file_offset_t ullTotalSize;
2107  if (pProgress) {
2108  // divide progress into subprogress
2109  progress_t subprogress;
2110  __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
2111  // do the actual work
2112  ullTotalSize = WriteChunk(0, 0, &subprogress);
2113  // notify subprogress done
2114  __notify_progress(&subprogress, 1.f);
2115  } else
2116  ullTotalSize = WriteChunk(0, 0, NULL);
2117 
2118  file_offset_t ullActualSize = __GetFileSize(hFileWrite);
2119 
2120  // resize file to the final size (if the file was originally larger)
2121  if (ullActualSize > ullTotalSize) ResizeFile(ullTotalSize);
2122 
2123  #if POSIX
2124  if (hFileWrite) close(hFileWrite);
2125  #elif defined(WIN32)
2126  if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
2127  #else
2128  if (hFileWrite) fclose(hFileWrite);
2129  #endif
2131 
2132  // associate new file with this File object from now on
2133  Filename = path;
2134  bIsNewFile = false;
2135  Mode = (stream_mode_t) -1; // Just set it to an undefined mode ...
2136  SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
2137 
2138  if (pProgress)
2139  __notify_progress(pProgress, 1.0); // notify done
2140  }
2141 
2142  void File::ResizeFile(file_offset_t ullNewSize) {
2143  #if POSIX
2144  if (ftruncate(hFileWrite, ullNewSize) < 0)
2145  throw Exception("Could not resize file \"" + Filename + "\"");
2146  #elif defined(WIN32)
2147  LARGE_INTEGER liFilePos;
2148  liFilePos.QuadPart = ullNewSize;
2149  if (
2150  !SetFilePointerEx(hFileWrite, liFilePos, NULL/*new pos pointer*/, FILE_BEGIN) ||
2151  !SetEndOfFile(hFileWrite)
2152  ) throw Exception("Could not resize file \"" + Filename + "\"");
2153  #else
2154  # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
2155  # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
2156  #endif
2157  }
2158 
2159  File::~File() {
2160  #if DEBUG_RIFF
2161  std::cout << "File::~File()" << std::endl;
2162  #endif // DEBUG_RIFF
2163  Cleanup();
2164  }
2165 
2170  bool File::IsNew() const {
2171  return bIsNewFile;
2172  }
2173 
2174  void File::Cleanup() {
2175  #if POSIX
2176  if (hFileRead) close(hFileRead);
2177  #elif defined(WIN32)
2178  if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
2179  #else
2180  if (hFileRead) fclose(hFileRead);
2181  #endif // POSIX
2182  DeleteChunkList();
2183  pFile = NULL;
2184  }
2185 
2193  file_offset_t size = 0;
2194  try {
2195  size = __GetFileSize(hFileRead);
2196  } catch (...) {
2197  size = 0;
2198  }
2199  return size;
2200  }
2201 
2222  return GetRequiredFileSize(FileOffsetPreference);
2223  }
2224 
2237  switch (fileOffsetSize) {
2238  case offset_size_auto: {
2240  if (fileSize >> 32)
2242  else
2243  return fileSize;
2244  }
2245  case offset_size_32bit: break;
2246  case offset_size_64bit: break;
2247  default: throw Exception("Internal error: Invalid RIFF::offset_size_t");
2248  }
2250  }
2251 
2252  int File::FileOffsetSizeFor(file_offset_t fileSize) const {
2253  switch (FileOffsetPreference) {
2254  case offset_size_auto:
2255  return (fileSize >> 32) ? 8 : 4;
2256  case offset_size_32bit:
2257  return 4;
2258  case offset_size_64bit:
2259  return 8;
2260  default:
2261  throw Exception("Internal error: Invalid RIFF::offset_size_t");
2262  }
2263  }
2264 
2286  return FileOffsetSize;
2287  }
2288 
2300  return FileOffsetSizeFor(GetCurrentFileSize());
2301  }
2302 
2303  #if POSIX
2304  file_offset_t File::__GetFileSize(int hFile) const {
2305  struct stat filestat;
2306  if (fstat(hFile, &filestat) == -1)
2307  throw Exception("POSIX FS error: could not determine file size");
2308  return filestat.st_size;
2309  }
2310  #elif defined(WIN32)
2311  file_offset_t File::__GetFileSize(HANDLE hFile) const {
2312  LARGE_INTEGER size;
2313  if (!GetFileSizeEx(hFile, &size))
2314  throw Exception("Windows FS error: could not determine file size");
2315  return size.QuadPart;
2316  }
2317  #else // standard C functions
2318  file_offset_t File::__GetFileSize(FILE* hFile) const {
2319  off_t curpos = ftello(hFile);
2320  if (fseeko(hFile, 0, SEEK_END) == -1)
2321  throw Exception("FS error: could not determine file size");
2322  off_t size = ftello(hFile);
2323  fseeko(hFile, curpos, SEEK_SET);
2324  return size;
2325  }
2326  #endif
2327 
2328 
2329 // *************** Exception ***************
2330 // *
2331 
2332  Exception::Exception() {
2333  }
2334 
2335  Exception::Exception(String format, ...) {
2336  va_list arg;
2337  va_start(arg, format);
2338  Message = assemble(format, arg);
2339  va_end(arg);
2340  }
2341 
2342  Exception::Exception(String format, va_list arg) {
2343  Message = assemble(format, arg);
2344  }
2345 
2346  void Exception::PrintMessage() {
2347  std::cout << "RIFF::Exception: " << Message << std::endl;
2348  }
2349 
2350  String Exception::assemble(String format, va_list arg) {
2351  char* buf = NULL;
2352  vasprintf(&buf, format.c_str(), arg);
2353  String s = buf;
2354  free(buf);
2355  return s;
2356  }
2357 
2358 
2359 // *************** functions ***************
2360 // *
2361 
2367  String libraryName() {
2368  return PACKAGE;
2369  }
2370 
2375  String libraryVersion() {
2376  return VERSION;
2377  }
2378 
2379 } // namespace RIFF
Ordinary RIFF Chunk.
Definition: RIFF.h:232
file_offset_t WriteInt16(int16_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 16 Bit signed integer words from the buffer pointed by pData to the chunk'...
Definition: RIFF.cpp:612
virtual void __resetPos()
Sets Chunk's read/write position to zero.
Definition: RIFF.cpp:1058
void Resize(file_offset_t NewSize)
Resize chunk.
Definition: RIFF.cpp:936
int8_t ReadInt8()
Reads one 8 Bit signed integer word and increments the position within the chunk.
Definition: RIFF.cpp:751
uint32_t ReadUint32()
Reads one 32 Bit unsigned integer word and increments the position within the chunk.
Definition: RIFF.cpp:835
stream_state_t GetState() const
Returns the current state of the chunk object.
Definition: RIFF.cpp:343
file_offset_t SetPos(file_offset_t Where, stream_whence_t Whence=stream_start)
Sets the position within the chunk body, thus within the data portion of the chunk (in bytes).
Definition: RIFF.cpp:280
void ReleaseChunkData()
Free loaded chunk body from RAM.
Definition: RIFF.cpp:911
file_offset_t Write(void *pData, file_offset_t WordCount, file_offset_t WordSize)
Writes WordCount number of data words with given WordSize from the buffer pointed by pData.
Definition: RIFF.cpp:444
file_offset_t RemainingBytes() const
Returns the number of bytes left to read in the chunk body.
Definition: RIFF.cpp:312
int16_t ReadInt16()
Reads one 16 Bit signed integer word and increments the position within the chunk.
Definition: RIFF.cpp:784
virtual file_offset_t WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t *pProgress=NULL)
Write chunk persistently e.g.
Definition: RIFF.cpp:958
file_offset_t GetPos() const
Position within the chunk data body (starting with 0).
Definition: RIFF.h:241
file_offset_t WriteInt32(int32_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 32 Bit signed integer words from the buffer pointed by pData to the chunk'...
Definition: RIFF.cpp:686
file_offset_t ReadSceptical(void *pData, file_offset_t WordCount, file_offset_t WordSize)
Just an internal wrapper for the main Read() method with additional Exception throwing on errors.
Definition: RIFF.cpp:500
virtual file_offset_t RequiredPhysicalSize(int fileOffsetSize)
Returns the actual total size in bytes (including header) of this Chunk if being stored to a file.
Definition: RIFF.cpp:326
file_offset_t Read(void *pData, file_offset_t WordCount, file_offset_t WordSize)
Reads WordCount number of data words with given WordSize and copies it into a buffer pointed by pData...
Definition: RIFF.cpp:374
uint32_t GetChunkID() const
Chunk ID in unsigned integer representation.
Definition: RIFF.h:236
void * LoadChunkData()
Load chunk body into RAM.
Definition: RIFF.cpp:865
String GetChunkIDString() const
Returns the String representation of the chunk's ID (e.g.
Definition: RIFF.cpp:264
uint8_t ReadUint8()
Reads one 8 Bit unsigned integer word and increments the position within the chunk.
Definition: RIFF.cpp:767
file_offset_t WriteInt8(int8_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 8 Bit signed integer words from the buffer pointed by pData to the chunk's...
Definition: RIFF.cpp:538
file_offset_t WriteUint16(uint16_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 16 Bit unsigned integer words from the buffer pointed by pData to the chun...
Definition: RIFF.cpp:649
file_offset_t WriteUint32(uint32_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 32 Bit unsigned integer words from the buffer pointed by pData to the chun...
Definition: RIFF.cpp:740
void ReadString(String &s, int size)
Reads a null-padded string of size characters and copies it into the string s.
Definition: RIFF.cpp:719
uint16_t ReadUint16()
Reads one 16 Bit unsigned integer word and increments the position within the chunk.
Definition: RIFF.cpp:801
file_offset_t GetSize() const
Chunk size in bytes (without header, thus the chunk data body)
Definition: RIFF.h:239
int32_t ReadInt32()
Reads one 32 Bit signed integer word and increments the position within the chunk.
Definition: RIFF.cpp:818
file_offset_t WriteUint8(uint8_t *pData, file_offset_t WordCount=1)
Writes WordCount number of 8 Bit unsigned integer words from the buffer pointed by pData to the chunk...
Definition: RIFF.cpp:575
Will be thrown whenever an error occurs while handling a RIFF file.
Definition: RIFF.h:418
RIFF File.
Definition: RIFF.h:358
bool SetMode(stream_mode_t NewMode)
Change file access mode.
Definition: RIFF.cpp:1803
int GetRequiredFileOffsetSize()
Returns the required size (in bytes) of file offsets stored in the headers of all chunks of this file...
Definition: RIFF.cpp:2299
int GetFileOffsetSize() const
Returns the current size (in bytes) of file offsets stored in the headers of all chunks of this file.
Definition: RIFF.cpp:2285
File(uint32_t FileType)
Create new RIFF file.
Definition: RIFF.cpp:1624
file_offset_t GetCurrentFileSize() const
Returns the current size of this file (in bytes) as it is currently yet stored on disk.
Definition: RIFF.cpp:2192
void SetByteOrder(endian_t Endian)
Set the byte order to be used when saving.
Definition: RIFF.cpp:1910
int hFileRead
handle / descriptor for reading from file
Definition: RIFF.h:381
bool IsNew() const
Returns true if this file has been created new from scratch and has not been stored to disk yet.
Definition: RIFF.cpp:2170
file_offset_t GetRequiredFileSize()
Returns the required size (in bytes) for this RIFF File to be saved to disk.
Definition: RIFF.cpp:2221
int hFileWrite
handle / descriptor for writing to (some) file
Definition: RIFF.h:382
virtual void Save(progress_t *pProgress=NULL)
Save changes to same file.
Definition: RIFF.cpp:1927
layout_t Layout
An ordinary RIFF file is always set to layout_standard.
Definition: RIFF.h:393
int FileOffsetSize
Size of file offsets (in bytes) when this file was opened (or saved the last time).
Definition: RIFF.h:395
RIFF List Chunk.
Definition: RIFF.h:308
size_t CountSubLists()
Returns number of sublists within the list.
Definition: RIFF.cpp:1274
Chunk * GetSubChunk(uint32_t ChunkID)
Returns subchunk with chunk ID ChunkID within this chunk list.
Definition: RIFF.cpp:1128
virtual file_offset_t RequiredPhysicalSize(int fileOffsetSize)
Returns the actual total size in bytes (including List chunk header and all subchunks) of this List C...
Definition: RIFF.cpp:1424
void MoveSubChunk(Chunk *pSrc, Chunk *pDst)
Moves a sub chunk witin this list.
Definition: RIFF.cpp:1332
List * GetFirstSubList()
Returns the first sublist within the list (that is a subchunk with chunk ID "LIST").
Definition: RIFF.cpp:1208
List * AddSubList(uint32_t uiListType)
Creates a new list sub chunk.
Definition: RIFF.cpp:1380
Chunk * GetFirstSubChunk()
Returns the first subchunk within the list (which may be an ordinary chunk as well as a list chunk).
Definition: RIFF.cpp:1173
virtual file_offset_t WriteChunk(file_offset_t ullWritePos, file_offset_t ullCurrentDataOffset, progress_t *pProgress=NULL)
Write list chunk persistently e.g.
Definition: RIFF.cpp:1553
void DeleteSubChunk(Chunk *pSubChunk)
Removes a sub chunk.
Definition: RIFF.cpp:1399
size_t CountSubChunks()
Returns number of subchunks within the list (including list chunks).
Definition: RIFF.cpp:1248
List * GetSubList(uint32_t ListType)
Returns sublist chunk with list type ListType within this chunk list.
Definition: RIFF.cpp:1147
Chunk * GetNextSubChunk()
Returns the next subchunk within the list (which may be an ordinary chunk as well as a list chunk).
Definition: RIFF.cpp:1190
uint32_t GetListType() const
Returns unsigned integer representation of the list's ID.
Definition: RIFF.h:312
String GetListTypeString() const
Returns string representation of the lists's id.
Definition: RIFF.cpp:1601
List * GetNextSubList()
Returns the next sublist (that is a subchunk with chunk ID "LIST") within the list.
Definition: RIFF.cpp:1230
Chunk * AddSubChunk(uint32_t uiChunkID, file_offset_t ullBodySize)
Creates a new sub chunk.
Definition: RIFF.cpp:1310
virtual void __resetPos()
Sets List Chunk's read/write position to zero and causes all sub chunks to do the same.
Definition: RIFF.cpp:1589
RIFF specific classes and definitions.
Definition: RIFF.h:150
String libraryVersion()
Returns version of this C++ library.
Definition: RIFF.cpp:2375
stream_whence_t
File stream position dependent to these relations.
Definition: RIFF.h:177
stream_state_t
Current state of the file stream.
Definition: RIFF.h:170
String libraryName()
Returns the name of this C++ library.
Definition: RIFF.cpp:2367
offset_size_t
Size of RIFF file offsets used in all RIFF chunks' headers.
Definition: RIFF.h:198
@ offset_size_64bit
Always use 64 bit offsets (even for files smaller than 4 GB).
Definition: RIFF.h:201
@ offset_size_auto
Use 32 bit offsets for files smaller than 4 GB, use 64 bit offsets for files equal or larger than 4 G...
Definition: RIFF.h:199
@ offset_size_32bit
Always use 32 bit offsets (even for files larger than 4 GB).
Definition: RIFF.h:200
stream_mode_t
Whether file stream is open in read or in read/write mode.
Definition: RIFF.h:163
layout_t
General RIFF chunk structure of a RIFF file.
Definition: RIFF.h:192
@ layout_standard
Standard RIFF file layout: First chunk in file is a List chunk which contains all other chunks and th...
Definition: RIFF.h:193
@ layout_flat
Not a "real" RIFF file: First chunk in file is an ordinary data chunk, not a List chunk,...
Definition: RIFF.h:194
endian_t
Alignment of data bytes in memory (system dependant).
Definition: RIFF.h:185
uint64_t file_offset_t
Type used by libgig for handling file positioning during file I/O tasks.
Definition: RIFF.h:160
Used for indicating the progress of a certain task.
Definition: RIFF.h:216
float __range_min
Only for internal usage, do not modify!
Definition: RIFF.h:220
std::vector< progress_t > subdivide(int iSubtasks)
Divides this progress task into the requested amount of equal weighted sub-progress tasks and returns...
Definition: RIFF.cpp:74
void(* callback)(progress_t *)
Callback function pointer which has to be assigned to a function for progress notification.
Definition: RIFF.h:217
void * custom
This pointer can be used for arbitrary data.
Definition: RIFF.h:219
float __range_max
Only for internal usage, do not modify!
Definition: RIFF.h:221