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

Legend:
Removed from v.933  
changed lines
  Added in v.1713

  ViewVC Help
Powered by ViewVC