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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 800 by schoenebeck, Wed Nov 9 20:04:11 2005 UTC revision 1678 by persson, Sun Feb 10 16:07:22 2008 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 29  Line 29 
29    
30  namespace RIFF {  namespace RIFF {
31    
32    // *************** Internal functions **************
33    // *
34    
35        /// Returns a human readable path of the given chunk.
36        static String __resolveChunkPath(Chunk* pCk) {
37            String sPath;
38            for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
39                if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
40                    List* pList = (List*) pChunk;
41                    sPath = "->'" + pList->GetListTypeString() + "'" + sPath;
42                } else {
43                    sPath = "->'" + pChunk->GetChunkIDString() + "'" + sPath;
44                }
45            }
46            return sPath;
47        }
48    
49    
50    
51  // *************** Chunk **************  // *************** Chunk **************
52  // *  // *
53    
# Line 70  namespace RIFF { Line 89  namespace RIFF {
89      }      }
90    
91      Chunk::~Chunk() {      Chunk::~Chunk() {
92            pFile->UnlogResized(this);
93          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
94      }      }
95    
# Line 81  namespace RIFF { Line 101  namespace RIFF {
101          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
102              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
103              read(pFile->hFileRead, &CurrentChunkSize, 4);              read(pFile->hFileRead, &CurrentChunkSize, 4);
104            #elif defined(WIN32)
105            if (SetFilePointer(pFile->hFileRead, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
106                DWORD dwBytesRead;
107                ReadFile(pFile->hFileRead, &ChunkID, 4, &dwBytesRead, NULL);
108                ReadFile(pFile->hFileRead, &CurrentChunkSize, 4, &dwBytesRead, NULL);
109          #else          #else
110          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileRead, fPos, SEEK_SET)) {
111              fread(&ChunkID, 4, 1, pFile->hFileRead);              fread(&ChunkID, 4, 1, pFile->hFileRead);
# Line 88  namespace RIFF { Line 113  namespace RIFF {
113          #endif // POSIX          #endif // POSIX
114              #if WORDS_BIGENDIAN              #if WORDS_BIGENDIAN
115              if (ChunkID == CHUNK_ID_RIFF) {              if (ChunkID == CHUNK_ID_RIFF) {
116                  bEndianNative = false;                  pFile->bEndianNative = false;
117              }              }
118              #else // little endian              #else // little endian
119              if (ChunkID == CHUNK_ID_RIFX) {              if (ChunkID == CHUNK_ID_RIFX) {
# Line 129  namespace RIFF { Line 154  namespace RIFF {
154              write(pFile->hFileWrite, &uiNewChunkID, 4);              write(pFile->hFileWrite, &uiNewChunkID, 4);
155              write(pFile->hFileWrite, &uiNewChunkSize, 4);              write(pFile->hFileWrite, &uiNewChunkSize, 4);
156          }          }
157            #elif defined(WIN32)
158            if (SetFilePointer(pFile->hFileWrite, fPos, NULL/*32 bit*/, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
159                DWORD dwBytesWritten;
160                WriteFile(pFile->hFileWrite, &uiNewChunkID, 4, &dwBytesWritten, NULL);
161                WriteFile(pFile->hFileWrite, &uiNewChunkSize, 4, &dwBytesWritten, NULL);
162            }
163          #else          #else
164          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {          if (!fseek(pFile->hFileWrite, fPos, SEEK_SET)) {
165              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);              fwrite(&uiNewChunkID, 4, 1, pFile->hFileWrite);
# Line 204  namespace RIFF { Line 235  namespace RIFF {
235       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
236       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
237       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
238       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
239       *    possible without SetPos()       *    possible without SetPos()
240       */       */
241      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
# Line 212  namespace RIFF { Line 243  namespace RIFF {
243        std::cout << "Chunk::GetState()" << std::endl;        std::cout << "Chunk::GetState()" << std::endl;
244        #endif // DEBUG        #endif // DEBUG
245          #if POSIX          #if POSIX
246          if (pFile->hFileRead == 0)    return stream_closed;          if (pFile->hFileRead == 0) return stream_closed;
247            #elif defined (WIN32)
248            if (pFile->hFileRead == INVALID_HANDLE_VALUE)
249                return stream_closed;
250          #else          #else
251          if (pFile->hFileRead == NULL) return stream_closed;          if (pFile->hFileRead == NULL) return stream_closed;
252          #endif // POSIX          #endif // POSIX
# Line 246  namespace RIFF { Line 280  namespace RIFF {
280          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
281          if (readWords < 1) return 0;          if (readWords < 1) return 0;
282          readWords /= WordSize;          readWords /= WordSize;
283            #elif defined(WIN32)
284            if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
285            DWORD readWords;
286            ReadFile(pFile->hFileRead, pData, WordCount * WordSize, &readWords, NULL);
287            if (readWords < 1) return 0;
288            readWords /= WordSize;
289          #else // standard C functions          #else // standard C functions
290          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
291          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
# Line 315  namespace RIFF { Line 355  namespace RIFF {
355          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);          unsigned long writtenWords = write(pFile->hFileWrite, pData, WordCount * WordSize);
356          if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");          if (writtenWords < 1) throw Exception("POSIX IO Error while trying to write chunk data");
357          writtenWords /= WordSize;          writtenWords /= WordSize;
358            #elif defined(WIN32)
359            if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
360                throw Exception("Could not seek to position " + ToString(ulPos) +
361                                " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
362            }
363            DWORD writtenWords;
364            WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
365            if (writtenWords < 1) throw Exception("Windows IO Error while trying to write chunk data");
366            writtenWords /= WordSize;
367          #else // standard C functions          #else // standard C functions
368          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {          if (fseek(pFile->hFileWrite, ulStartPos + ulPos, SEEK_SET)) {
369              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
# Line 676  namespace RIFF { Line 725  namespace RIFF {
725       * @see ReleaseChunkData()       * @see ReleaseChunkData()
726       */       */
727      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
728          if (!pChunkData) {          if (!pChunkData && pFile->Filename != "") {
729              #if POSIX              #if POSIX
730              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
731                #elif defined(WIN32)
732                if (SetFilePointer(pFile->hFileRead, ulStartPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return NULL;
733              #else              #else
734              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;              if (fseek(pFile->hFileRead, ulStartPos, SEEK_SET)) return NULL;
735              #endif // POSIX              #endif // POSIX
# Line 688  namespace RIFF { Line 739  namespace RIFF {
739              memset(pChunkData, 0, ulBufferSize);              memset(pChunkData, 0, ulBufferSize);
740              #if POSIX              #if POSIX
741              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());              unsigned long readWords = read(pFile->hFileRead, pChunkData, GetSize());
742                #elif defined(WIN32)
743                DWORD readWords;
744                ReadFile(pFile->hFileRead, pChunkData, GetSize(), &readWords, NULL);
745              #else              #else
746              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);              unsigned long readWords = fread(pChunkData, 1, GetSize(), pFile->hFileRead);
747              #endif // POSIX              #endif // POSIX
# Line 740  namespace RIFF { Line 794  namespace RIFF {
794       * @see File::Save()       * @see File::Save()
795       */       */
796      void Chunk::Resize(int iNewSize) {      void Chunk::Resize(int iNewSize) {
797          if (iNewSize <= 0) throw Exception("Chunk size must be at least one byte");          if (iNewSize <= 0)
798                throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(this));
799          if (NewChunkSize == iNewSize) return;          if (NewChunkSize == iNewSize) return;
800          NewChunkSize = iNewSize;          NewChunkSize = iNewSize;
801          pFile->LogAsResized(this);          pFile->LogAsResized(this);
# Line 775  namespace RIFF { Line 830  namespace RIFF {
830              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {              if (write(pFile->hFileWrite, pChunkData, NewChunkSize) != NewChunkSize) {
831                  throw Exception("Writing Chunk data (from RAM) failed");                  throw Exception("Writing Chunk data (from RAM) failed");
832              }              }
833                #elif defined(WIN32)
834                SetFilePointer(pFile->hFileWrite, ulWritePos, NULL/*32 bit*/, FILE_BEGIN);
835                DWORD dwBytesWritten;
836                WriteFile(pFile->hFileWrite, pChunkData, NewChunkSize, &dwBytesWritten, NULL);
837                if (dwBytesWritten != NewChunkSize) {
838                    throw Exception("Writing Chunk data (from RAM) failed");
839                }
840              #else              #else
841              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);              fseek(pFile->hFileWrite, ulWritePos, SEEK_SET);
842              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {              if (fwrite(pChunkData, 1, NewChunkSize, pFile->hFileWrite) != NewChunkSize) {
# Line 785  namespace RIFF { Line 847  namespace RIFF {
847              // move chunk data from the end of the file to the appropriate position              // move chunk data from the end of the file to the appropriate position
848              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
849              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;              unsigned long ulToMove = (NewChunkSize < CurrentChunkSize) ? NewChunkSize : CurrentChunkSize;
850                #if defined(WIN32)
851                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
852                #else
853              int iBytesMoved = 1;              int iBytesMoved = 1;
854                #endif
855              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
856                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
857                  #if POSIX                  #if POSIX
# Line 793  namespace RIFF { Line 859  namespace RIFF {
859                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(pFile->hFileRead, pCopyBuffer, iBytesMoved);
860                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);                  lseek(pFile->hFileWrite, ulWritePos + ulOffset, SEEK_SET);
861                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(pFile->hFileWrite, pCopyBuffer, iBytesMoved);
862                    #elif defined(WIN32)
863                    SetFilePointer(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
864                    ReadFile(pFile->hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
865                    SetFilePointer(pFile->hFileWrite, ulWritePos + ulOffset, NULL/*32 bit*/, FILE_BEGIN);
866                    WriteFile(pFile->hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
867                  #else                  #else
868                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  fseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
869                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, pFile->hFileRead);
# Line 818  namespace RIFF { Line 889  namespace RIFF {
889              #if POSIX              #if POSIX
890              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              lseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
891              write(pFile->hFileWrite, &cPadByte, 1);              write(pFile->hFileWrite, &cPadByte, 1);
892                #elif defined(WIN32)
893                SetFilePointer(pFile->hFileWrite, ulStartPos + NewChunkSize, NULL/*32 bit*/, FILE_BEGIN);
894                DWORD dwBytesWritten;
895                WriteFile(pFile->hFileWrite, &cPadByte, 1, &dwBytesWritten, NULL);
896              #else              #else
897              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);              fseek(pFile->hFileWrite, ulStartPos + NewChunkSize, SEEK_SET);
898              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);              fwrite(&cPadByte, 1, 1, pFile->hFileWrite);
# Line 1077  namespace RIFF { Line 1152  namespace RIFF {
1152          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1153          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1154          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(uiBodySize);
1155            NewChunkSize += CHUNK_HEADER_SIZE;
1156            pFile->LogAsResized(this);
1157          return pNewChunk;          return pNewChunk;
1158      }      }
1159    
1160        /** @brief Moves a sub chunk.
1161         *
1162         * Moves a sub chunk from one position in a list to another
1163         * position in the same list. The pSrc chunk is placed before the
1164         * pDst chunk.
1165         *
1166         * @param pSrc - sub chunk to be moved
1167         * @param pDst - the position to move to. pSrc will be placed
1168         *               before pDst. If pDst is 0, pSrc will be placed
1169         *               last in list.
1170         */
1171        void List::MoveSubChunk(Chunk* pSrc, Chunk* pDst) {
1172            if (!pSubChunks) LoadSubChunks();
1173            pSubChunks->remove(pSrc);
1174            ChunkList::iterator iter = find(pSubChunks->begin(), pSubChunks->end(), pDst);
1175            pSubChunks->insert(iter, pSrc);
1176        }
1177    
1178      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1179       *       *
1180       * Creates and adds a new list sub chunk to this list chunk. Note that       * Creates and adds a new list sub chunk to this list chunk. Note that
# Line 1094  namespace RIFF { Line 1189  namespace RIFF {
1189          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1190          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1191          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1192            NewChunkSize += LIST_HEADER_SIZE;
1193            pFile->LogAsResized(this);
1194          return pNewListChunk;          return pNewListChunk;
1195      }      }
1196    
# Line 1101  namespace RIFF { Line 1198  namespace RIFF {
1198       *       *
1199       * Removes the sub chunk given by \a pSubChunk from this list and frees       * Removes the sub chunk given by \a pSubChunk from this list and frees
1200       * it completely from RAM. The given chunk can either be a normal sub       * it completely from RAM. The given chunk can either be a normal sub
1201       * chunk or a list sub chunk. You should call File::Save() to make this       * chunk or a list sub chunk. In case the given chunk is a list chunk,
1202       * change persistent at any time.       * all its subchunks (if any) will be removed recursively as well. You
1203         * should call File::Save() to make this change persistent at any time.
1204       *       *
1205       * @param pSubChunk - sub chunk or sub list chunk to be removed       * @param pSubChunk - sub chunk or sub list chunk to be removed
1206       */       */
# Line 1133  namespace RIFF { Line 1231  namespace RIFF {
1231          #if POSIX          #if POSIX
1232          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1233          read(pFile->hFileRead, &ListType, 4);          read(pFile->hFileRead, &ListType, 4);
1234            #elif defined(WIN32)
1235            SetFilePointer(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1236            DWORD dwBytesRead;
1237            ReadFile(pFile->hFileRead, &ListType, 4, &dwBytesRead, NULL);
1238          #else          #else
1239          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1240          fread(&ListType, 4, 1, pFile->hFileRead);          fread(&ListType, 4, 1, pFile->hFileRead);
# Line 1153  namespace RIFF { Line 1255  namespace RIFF {
1255          #if POSIX          #if POSIX
1256          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1257          write(pFile->hFileWrite, &ListType, 4);          write(pFile->hFileWrite, &ListType, 4);
1258            #elif defined(WIN32)
1259            SetFilePointer(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, NULL/*32 bit*/, FILE_BEGIN);
1260            DWORD dwBytesWritten;
1261            WriteFile(pFile->hFileWrite, &ListType, 4, &dwBytesWritten, NULL);
1262          #else          #else
1263          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          fseek(pFile->hFileWrite, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
1264          fwrite(&ListType, 4, 1, pFile->hFileWrite);          fwrite(&ListType, 4, 1, pFile->hFileWrite);
# Line 1166  namespace RIFF { Line 1272  namespace RIFF {
1272          if (!pSubChunks) {          if (!pSubChunks) {
1273              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1274              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1275                #if defined(WIN32)
1276                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1277                #else
1278              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1279                #endif
1280              unsigned long uiOriginalPos = GetPos();              unsigned long uiOriginalPos = GetPos();
1281              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1282              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
# Line 1192  namespace RIFF { Line 1302  namespace RIFF {
1302          }          }
1303      }      }
1304    
1305        void List::LoadSubChunksRecursively() {
1306            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())
1307                pList->LoadSubChunksRecursively();
1308        }
1309    
1310      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
1311       *       *
1312       * Stores the list chunk persistently to its actual "physical" file. All       * Stores the list chunk persistently to its actual "physical" file. All
# Line 1257  namespace RIFF { Line 1372  namespace RIFF {
1372       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1373       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1374       *       *
1375         * Note: by default, the RIFF file will be saved in native endian
1376         * format; that is, as a RIFF file on little-endian machines and
1377         * as a RIFX file on big-endian. To change this behaviour, call
1378         * SetByteOrder() before calling Save().
1379         *
1380       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1381       * @see AddSubChunk(), AddSubList()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1382       */       */
1383      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType) : List(this) {
1384            #if defined(WIN32)
1385            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1386            #else
1387          hFileRead = hFileWrite = 0;          hFileRead = hFileWrite = 0;
1388            #endif
1389          Mode = stream_mode_closed;          Mode = stream_mode_closed;
1390          bEndianNative = true;          bEndianNative = true;
1391          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
# Line 1287  namespace RIFF { Line 1411  namespace RIFF {
1411              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1412              throw RIFF::Exception("Can't open \"" + path + "\"");              throw RIFF::Exception("Can't open \"" + path + "\"");
1413          }          }
1414            #elif defined(WIN32)
1415            hFileRead = hFileWrite = CreateFile(
1416                                         path.c_str(), GENERIC_READ,
1417                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1418                                         NULL, OPEN_EXISTING,
1419                                         FILE_ATTRIBUTE_NORMAL |
1420                                         FILE_FLAG_RANDOM_ACCESS, NULL
1421                                     );
1422            if (hFileRead == INVALID_HANDLE_VALUE) {
1423                hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1424                throw RIFF::Exception("Can't open \"" + path + "\"");
1425            }
1426          #else          #else
1427          hFileRead = hFileWrite = fopen(path.c_str(), "rb");          hFileRead = hFileWrite = fopen(path.c_str(), "rb");
1428          if (!hFile) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1429          #endif // POSIX          #endif // POSIX
1430          Mode = stream_mode_read;          Mode = stream_mode_read;
1431          ulStartPos = RIFF_HEADER_SIZE;          ulStartPos = RIFF_HEADER_SIZE;
# Line 1328  namespace RIFF { Line 1464  namespace RIFF {
1464                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1465                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1466                      }                      }
1467                        #elif defined(WIN32)
1468                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1469                        hFileRead = hFileWrite = CreateFile(
1470                                                     Filename.c_str(), GENERIC_READ,
1471                                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
1472                                                     NULL, OPEN_EXISTING,
1473                                                     FILE_ATTRIBUTE_NORMAL |
1474                                                     FILE_FLAG_RANDOM_ACCESS,
1475                                                     NULL
1476                                                 );
1477                        if (hFileRead == INVALID_HANDLE_VALUE) {
1478                            hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1479                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1480                        }
1481                      #else                      #else
1482                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1483                      hFileRead = hFileWrite = fopen(path.c_str(), "rb");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1484                      if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                      if (!hFileRead) throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");
1485                      #endif                      #endif
1486                      __resetPos(); // reset read/write position of ALL 'Chunk' objects                      __resetPos(); // reset read/write position of ALL 'Chunk' objects
# Line 1343  namespace RIFF { Line 1493  namespace RIFF {
1493                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1494                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1495                      }                      }
1496                        #elif defined(WIN32)
1497                        if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1498                        hFileRead = hFileWrite = CreateFile(
1499                                                     Filename.c_str(),
1500                                                     GENERIC_READ | GENERIC_WRITE,
1501                                                     FILE_SHARE_READ,
1502                                                     NULL, OPEN_ALWAYS,
1503                                                     FILE_ATTRIBUTE_NORMAL |
1504                                                     FILE_FLAG_RANDOM_ACCESS,
1505                                                     NULL
1506                                                 );
1507                        if (hFileRead == INVALID_HANDLE_VALUE) {
1508                            hFileRead = hFileWrite = CreateFile(
1509                                                         Filename.c_str(), GENERIC_READ,
1510                                                         FILE_SHARE_READ | FILE_SHARE_WRITE,
1511                                                         NULL, OPEN_EXISTING,
1512                                                         FILE_ATTRIBUTE_NORMAL |
1513                                                         FILE_FLAG_RANDOM_ACCESS,
1514                                                         NULL
1515                                                     );
1516                            throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1517                        }
1518                      #else                      #else
1519                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
1520                      hFileRead = hFileWrite = fopen(path.c_str(), "r+b");                      hFileRead = hFileWrite = fopen(Filename.c_str(), "r+b");
1521                      if (!hFileRead) {                      if (!hFileRead) {
1522                          hFileRead = hFileWrite = fopen(path.c_str(), "rb");                          hFileRead = hFileWrite = fopen(Filename.c_str(), "rb");
1523                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");
1524                      }                      }
1525                      #endif                      #endif
# Line 1357  namespace RIFF { Line 1529  namespace RIFF {
1529                      #if POSIX                      #if POSIX
1530                      if (hFileRead)  close(hFileRead);                      if (hFileRead)  close(hFileRead);
1531                      if (hFileWrite) close(hFileWrite);                      if (hFileWrite) close(hFileWrite);
1532                        #elif defined(WIN32)
1533                        if (hFileRead  != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1534                        if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1535                      #else                      #else
1536                      if (hFileRead)  fclose(hFileRead);                      if (hFileRead)  fclose(hFileRead);
1537                      if (hFileWrite) fclose(hFileWrite);                      if (hFileWrite) fclose(hFileWrite);
# Line 1372  namespace RIFF { Line 1547  namespace RIFF {
1547          return false;          return false;
1548      }      }
1549    
1550        /** @brief Set the byte order to be used when saving.
1551         *
1552         * Set the byte order to be used in the file. A value of
1553         * endian_little will create a RIFF file, endian_big a RIFX file
1554         * and endian_native will create a RIFF file on little-endian
1555         * machines and RIFX on big-endian machines.
1556         *
1557         * @param Endian - endianess to use when file is saved.
1558         */
1559        void File::SetByteOrder(endian_t Endian) {
1560            #if WORDS_BIGENDIAN
1561            bEndianNative = Endian != endian_little;
1562            #else
1563            bEndianNative = Endian != endian_big;
1564            #endif
1565        }
1566    
1567      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1568       *       *
1569       * Make all changes of all chunks persistent by writing them to the       * Make all changes of all chunks persistent by writing them to the
# Line 1383  namespace RIFF { Line 1575  namespace RIFF {
1575       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1576       */       */
1577      void File::Save() {      void File::Save() {
1578            // make sure the RIFF tree is built (from the original file)
1579            LoadSubChunksRecursively();
1580    
1581          // reopen file in write mode          // reopen file in write mode
1582          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
1583    
# Line 1395  namespace RIFF { Line 1590  namespace RIFF {
1590    
1591          // first we sum up all positive chunk size changes (and skip all negative ones)          // first we sum up all positive chunk size changes (and skip all negative ones)
1592          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1593          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          for (std::set<Chunk*>::const_iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {
1594              if ((*iter)->GetNewSize() == 0) throw Exception("There is at least one empty chunk (zero size)");              if ((*iter)->GetNewSize() == 0) {
1595              if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {                  throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
                 unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte  
                 ulPositiveSizeDiff += ulDiff;  
1596              }              }
1597                unsigned long ulDiff = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2 - (*iter)->GetSize() - (*iter)->GetSize() % 2;
1598                if (ulDiff > 0) ulPositiveSizeDiff += ulDiff;
1599          }          }
1600    
1601          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1413  namespace RIFF { Line 1608  namespace RIFF {
1608              // ... and move current data by the same amount towards end of file.              // ... and move current data by the same amount towards end of file.
1609              int8_t* pCopyBuffer = new int8_t[4096];              int8_t* pCopyBuffer = new int8_t[4096];
1610              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;              const unsigned long ulFileSize = GetSize() + RIFF_HEADER_SIZE;
1611                #if defined(WIN32)
1612                DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1613                #else
1614              int iBytesMoved = 1;              int iBytesMoved = 1;
1615              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              #endif
1616                  const unsigned long ulToMove = ulFileSize - ulPos;              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1617                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1618                    ulPos -= iBytesMoved;
1619                  #if POSIX                  #if POSIX
1620                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ulPos, SEEK_SET);
1621                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
1622                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  lseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1623                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);                  iBytesMoved = write(hFileWrite, pCopyBuffer, iBytesMoved);
1624                    #elif defined(WIN32)
1625                    SetFilePointer(hFileRead, ulPos, NULL/*32 bit*/, FILE_BEGIN);
1626                    ReadFile(hFileRead, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1627                    SetFilePointer(hFileWrite, ulPos + ulPositiveSizeDiff, NULL/*32 bit*/, FILE_BEGIN);
1628                    WriteFile(hFileWrite, pCopyBuffer, iBytesMoved, &iBytesMoved, NULL);
1629                  #else                  #else
1630                  fseek(hFileRead, ulPos, SEEK_SET);                  fseek(hFileRead, ulPos, SEEK_SET);
1631                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);                  iBytesMoved = fread(pCopyBuffer, 1, iBytesMoved, hFileRead);
# Line 1460  namespace RIFF { Line 1664  namespace RIFF {
1664      void File::Save(const String& path) {      void File::Save(const String& path) {
1665          //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          //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
1666    
1667            // make sure the RIFF tree is built (from the original file)
1668            LoadSubChunksRecursively();
1669    
1670          if (Filename.length() > 0) SetMode(stream_mode_read);          if (Filename.length() > 0) SetMode(stream_mode_read);
1671          // open the other (new) file for writing and truncate it to zero size          // open the other (new) file for writing and truncate it to zero size
1672          #if POSIX          #if POSIX
# Line 1468  namespace RIFF { Line 1675  namespace RIFF {
1675              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1676              throw Exception("Could not open file \"" + path + "\" for writing");              throw Exception("Could not open file \"" + path + "\" for writing");
1677          }          }
1678            #elif defined(WIN32)
1679            hFileWrite = CreateFile(
1680                             path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1681                             NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1682                             FILE_FLAG_RANDOM_ACCESS, NULL
1683                         );
1684            if (hFileWrite == INVALID_HANDLE_VALUE) {
1685                hFileWrite = hFileRead;
1686                throw Exception("Could not open file \"" + path + "\" for writing");
1687            }
1688          #else          #else
1689          hFileWrite = fopen(path.c_str(), "w+b");          hFileWrite = fopen(path.c_str(), "w+b");
1690          if (!hFileWrite) {          if (!hFileWrite) {
# Line 1487  namespace RIFF { Line 1704  namespace RIFF {
1704          // forget all resized chunks          // forget all resized chunks
1705          ResizedChunks.clear();          ResizedChunks.clear();
1706    
1707          if (Filename.length() > 0) {          #if POSIX
1708              #if POSIX          if (hFileWrite) close(hFileWrite);
1709              close(hFileWrite);          #elif defined(WIN32)
1710              #else          if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1711              fclose(hFileWrite);          #else
1712              #endif          if (hFileWrite) fclose(hFileWrite);
1713              hFileWrite = hFileRead;          #endif
1714          }          hFileWrite = hFileRead;
1715    
1716          // associate new file with this File object from now on          // associate new file with this File object from now on
1717          Filename = path;          Filename = path;
# Line 1506  namespace RIFF { Line 1723  namespace RIFF {
1723          #if POSIX          #if POSIX
1724          if (ftruncate(hFileWrite, ulNewSize) < 0)          if (ftruncate(hFileWrite, ulNewSize) < 0)
1725              throw Exception("Could not resize file \"" + Filename + "\"");              throw Exception("Could not resize file \"" + Filename + "\"");
1726            #elif defined(WIN32)
1727            if (
1728                SetFilePointer(hFileWrite, ulNewSize, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
1729                !SetEndOfFile(hFileWrite)
1730            ) throw Exception("Could not resize file \"" + Filename + "\"");
1731          #else          #else
1732          # error Sorry, this version of libgig only supports POSIX systems yet.          # error Sorry, this version of libgig only supports POSIX and Windows systems yet.
1733          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!          # error Reason: portable implementation of RIFF::File::ResizeFile() is missing (yet)!
1734          #endif          #endif
1735      }      }
# Line 1518  namespace RIFF { Line 1740  namespace RIFF {
1740         #endif // DEBUG         #endif // DEBUG
1741          #if POSIX          #if POSIX
1742          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1743            #elif defined(WIN32)
1744            if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
1745          #else          #else
1746          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1747          #endif // POSIX          #endif // POSIX
1748      }      }
1749    
1750      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {
1751          ResizedChunks.push_back(pResizedChunk);          ResizedChunks.insert(pResizedChunk);
1752        }
1753    
1754        void File::UnlogResized(Chunk* pResizedChunk) {
1755            ResizedChunks.erase(pResizedChunk);
1756      }      }
1757    
1758      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {
# Line 1538  namespace RIFF { Line 1766  namespace RIFF {
1766          long size = filestat.st_size;          long size = filestat.st_size;
1767          return size;          return size;
1768      }      }
1769        #elif defined(WIN32)
1770        unsigned long File::__GetFileSize(HANDLE hFile) {
1771            DWORD dwSize = ::GetFileSize(hFile, NULL /*32bit*/);
1772            if (dwSize == INVALID_FILE_SIZE)
1773                throw Exception("Windows FS error: could not determine file size");
1774            return dwSize;
1775        }
1776      #else // standard C functions      #else // standard C functions
1777      unsigned long File::__GetFileSize(FILE* hFile) {      unsigned long File::__GetFileSize(FILE* hFile) {
1778          long curpos = ftell(hFile);          long curpos = ftell(hFile);

Legend:
Removed from v.800  
changed lines
  Added in v.1678

  ViewVC Help
Powered by ViewVC