/[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 1105 by schoenebeck, Sun Mar 18 19:32:42 2007 UTC revision 2675 by schoenebeck, Sun Sep 14 16:07:34 2014 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-2007 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2014 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 <set>
26  #include <string.h>  #include <string.h>
27    
28  #include "RIFF.h"  #include "RIFF.h"
29    
30  #include "helper.h"  #include "helper.h"
31    
32    #if POSIX
33    # include <errno.h>
34    #endif
35    
36  namespace RIFF {  namespace RIFF {
37    
38  // *************** Internal functions **************  // *************** Internal functions **************
39  // *  // *
40    
41      /// Returns a human readable path of the given chunk.      /// Returns a human readable path of the given chunk.
42      String __resolveChunkPath(Chunk* pCk) {      static String __resolveChunkPath(Chunk* pCk) {
43          String sPath;          String sPath;
44          for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {          for (Chunk* pChunk = pCk; pChunk; pChunk = pChunk->GetParent()) {
45              if (pChunk->GetChunkID() == CHUNK_ID_LIST) {              if (pChunk->GetChunkID() == CHUNK_ID_LIST) {
# Line 58  namespace RIFF { Line 64  namespace RIFF {
64          ulPos      = 0;          ulPos      = 0;
65          pParent    = NULL;          pParent    = NULL;
66          pChunkData = NULL;          pChunkData = NULL;
67            CurrentChunkSize = 0;
68            NewChunkSize = 0;
69          ulChunkDataSize = 0;          ulChunkDataSize = 0;
70          ChunkID    = CHUNK_ID_RIFF;          ChunkID    = CHUNK_ID_RIFF;
71          this->pFile = pFile;          this->pFile = pFile;
# Line 72  namespace RIFF { Line 80  namespace RIFF {
80          pParent       = Parent;          pParent       = Parent;
81          ulPos         = 0;          ulPos         = 0;
82          pChunkData    = NULL;          pChunkData    = NULL;
83            CurrentChunkSize = 0;
84            NewChunkSize = 0;
85          ulChunkDataSize = 0;          ulChunkDataSize = 0;
86          ReadHeader(StartPos);          ReadHeader(StartPos);
87      }      }
# Line 82  namespace RIFF { Line 92  namespace RIFF {
92          this->pParent    = pParent;          this->pParent    = pParent;
93          ulPos            = 0;          ulPos            = 0;
94          pChunkData       = NULL;          pChunkData       = NULL;
         ulChunkDataSize  = 0;  
95          ChunkID          = uiChunkID;          ChunkID          = uiChunkID;
96            ulChunkDataSize  = 0;
97          CurrentChunkSize = 0;          CurrentChunkSize = 0;
98          NewChunkSize     = uiBodySize;          NewChunkSize     = uiBodySize;
99      }      }
100    
101      Chunk::~Chunk() {      Chunk::~Chunk() {
102          if (CurrentChunkSize != NewChunkSize) pFile->UnlogResized(this);          if (pFile) pFile->UnlogResized(this);
103          if (pChunkData) delete[] pChunkData;          if (pChunkData) delete[] pChunkData;
104      }      }
105    
# Line 97  namespace RIFF { Line 107  namespace RIFF {
107          #if DEBUG          #if DEBUG
108          std::cout << "Chunk::Readheader(" << fPos << ") ";          std::cout << "Chunk::Readheader(" << fPos << ") ";
109          #endif // DEBUG          #endif // DEBUG
110            ChunkID = 0;
111            NewChunkSize = CurrentChunkSize = 0;
112          #if POSIX          #if POSIX
113          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {          if (lseek(pFile->hFileRead, fPos, SEEK_SET) != -1) {
114              read(pFile->hFileRead, &ChunkID, 4);              read(pFile->hFileRead, &ChunkID, 4);
# Line 127  namespace RIFF { Line 139  namespace RIFF {
139              }              }
140              #if DEBUG              #if DEBUG
141              std::cout << "ckID=" << convertToString(ChunkID) << " ";              std::cout << "ckID=" << convertToString(ChunkID) << " ";
142              std::cout << "ckSize=" << ChunkSize << " ";              std::cout << "ckSize=" << CurrentChunkSize << " ";
143              std::cout << "bEndianNative=" << bEndianNative << std::endl;              std::cout << "bEndianNative=" << pFile->bEndianNative << std::endl;
144              #endif // DEBUG              #endif // DEBUG
145              NewChunkSize = CurrentChunkSize;              NewChunkSize = CurrentChunkSize;
146          }          }
# Line 224  namespace RIFF { Line 236  namespace RIFF {
236         #if DEBUG         #if DEBUG
237         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;         std::cout << "Chunk::Remainingbytes()=" << CurrentChunkSize - ulPos << std::endl;
238         #endif // DEBUG         #endif // DEBUG
239          return CurrentChunkSize - ulPos;          return (CurrentChunkSize > ulPos) ? CurrentChunkSize - ulPos : 0;
240      }      }
241    
242      /**      /**
# Line 235  namespace RIFF { Line 247  namespace RIFF {
247       *  - RIFF::stream_closed :       *  - RIFF::stream_closed :
248       *    the data stream was closed somehow, no more reading possible       *    the data stream was closed somehow, no more reading possible
249       *  - RIFF::stream_end_reached :       *  - RIFF::stream_end_reached :
250       *    alreaady reached the end of the chunk data, no more reading       *    already reached the end of the chunk data, no more reading
251       *    possible without SetPos()       *    possible without SetPos()
252       */       */
253      stream_state_t Chunk::GetState() {      stream_state_t Chunk::GetState() {
# Line 273  namespace RIFF { Line 285  namespace RIFF {
285         #if DEBUG         #if DEBUG
286         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
287         #endif // DEBUG         #endif // DEBUG
288            //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
289          if (ulPos >= CurrentChunkSize) return 0;          if (ulPos >= CurrentChunkSize) return 0;
290          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
291          #if POSIX          #if POSIX
# Line 358  namespace RIFF { Line 371  namespace RIFF {
371          #elif defined(WIN32)          #elif defined(WIN32)
372          if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {          if (SetFilePointer(pFile->hFileWrite, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {
373              throw Exception("Could not seek to position " + ToString(ulPos) +              throw Exception("Could not seek to position " + ToString(ulPos) +
374                              " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");                                          " in chunk (" + ToString(ulStartPos + ulPos) + " in file)");
375          }          }
376          DWORD writtenWords;          DWORD writtenWords;
377          WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);          WriteFile(pFile->hFileWrite, pData, WordCount * WordSize, &writtenWords, NULL);
# Line 586  namespace RIFF { Line 599  namespace RIFF {
599      }      }
600    
601      /**      /**
602         * Reads a null-padded string of size characters and copies it
603         * into the string \a s. The position within the chunk will
604         * automatically be incremented.
605         *
606         * @param s                 destination string
607         * @param size              number of characters to read
608         * @throws RIFF::Exception  if an error occured or less than
609         *                          \a size characters could be read!
610         */
611        void Chunk::ReadString(String& s, int size) {
612            char* buf = new char[size];
613            ReadSceptical(buf, 1, size);
614            s.assign(buf, std::find(buf, buf + size, '\0'));
615            delete[] buf;
616        }
617    
618        /**
619       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
620       * buffer pointed by \a pData to the chunk's body, directly to the       * buffer pointed by \a pData to the chunk's body, directly to the
621       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 725  namespace RIFF { Line 755  namespace RIFF {
755       * @see ReleaseChunkData()       * @see ReleaseChunkData()
756       */       */
757      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
758          if (!pChunkData && pFile->Filename != "") {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
759              #if POSIX              #if POSIX
760              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
761              #elif defined(WIN32)              #elif defined(WIN32)
# Line 852  namespace RIFF { Line 882  namespace RIFF {
882              #else              #else
883              int iBytesMoved = 1;              int iBytesMoved = 1;
884              #endif              #endif
885              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
886                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
887                  #if POSIX                  #if POSIX
888                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
# Line 942  namespace RIFF { Line 972  namespace RIFF {
972        #if DEBUG        #if DEBUG
973        std::cout << "List::~List()" << std::endl;        std::cout << "List::~List()" << std::endl;
974        #endif // DEBUG        #endif // DEBUG
975            DeleteChunkList();
976        }
977    
978        void List::DeleteChunkList() {
979          if (pSubChunks) {          if (pSubChunks) {
980              ChunkList::iterator iter = pSubChunks->begin();              ChunkList::iterator iter = pSubChunks->begin();
981              ChunkList::iterator end  = pSubChunks->end();              ChunkList::iterator end  = pSubChunks->end();
# Line 950  namespace RIFF { Line 984  namespace RIFF {
984                  iter++;                  iter++;
985              }              }
986              delete pSubChunks;              delete pSubChunks;
987                pSubChunks = NULL;
988            }
989            if (pSubChunksMap) {
990                delete pSubChunksMap;
991                pSubChunksMap = NULL;
992          }          }
         if (pSubChunksMap) delete pSubChunksMap;  
993      }      }
994    
995      /**      /**
# Line 1152  namespace RIFF { Line 1190  namespace RIFF {
1190          pSubChunks->push_back(pNewChunk);          pSubChunks->push_back(pNewChunk);
1191          (*pSubChunksMap)[uiChunkID] = pNewChunk;          (*pSubChunksMap)[uiChunkID] = pNewChunk;
1192          pNewChunk->Resize(uiBodySize);          pNewChunk->Resize(uiBodySize);
1193            NewChunkSize += CHUNK_HEADER_SIZE;
1194            pFile->LogAsResized(this);
1195          return pNewChunk;          return pNewChunk;
1196      }      }
1197    
1198      /** @brief Moves a sub chunk.      /** @brief Moves a sub chunk witin this list.
1199       *       *
1200       * Moves a sub chunk from one position in a list to another       * Moves a sub chunk from one position in this list to another
1201       * position in the same list. The pSrc chunk is placed before the       * position in the same list. The pSrc chunk is placed before the
1202       * pDst chunk.       * pDst chunk.
1203       *       *
# Line 1173  namespace RIFF { Line 1213  namespace RIFF {
1213          pSubChunks->insert(iter, pSrc);          pSubChunks->insert(iter, pSrc);
1214      }      }
1215    
1216        /** @brief Moves a sub chunk from this list to another list.
1217         *
1218         * Moves a sub chunk from this list list to the end of another
1219         * list.
1220         *
1221         * @param pSrc - sub chunk to be moved
1222         * @param pDst - destination list where the chunk shall be moved to
1223         */
1224        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1225            if (pNewParent == this || !pNewParent) return;
1226            if (!pSubChunks) LoadSubChunks();
1227            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1228            pSubChunks->remove(pSrc);
1229            pNewParent->pSubChunks->push_back(pSrc);
1230            // update chunk id map of this List
1231            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1232                pSubChunksMap->erase(pSrc->GetChunkID());
1233                // try to find another chunk of the same chunk ID
1234                ChunkList::iterator iter = pSubChunks->begin();
1235                ChunkList::iterator end  = pSubChunks->end();
1236                for (; iter != end; ++iter) {
1237                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1238                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1239                        break; // we're done, stop search
1240                    }
1241                }
1242            }
1243            // update chunk id map of other list
1244            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1245                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1246        }
1247    
1248      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1249       *       *
1250       * 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 1187  namespace RIFF { Line 1259  namespace RIFF {
1259          List* pNewListChunk = new List(pFile, this, uiListType);          List* pNewListChunk = new List(pFile, this, uiListType);
1260          pSubChunks->push_back(pNewListChunk);          pSubChunks->push_back(pNewListChunk);
1261          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;          (*pSubChunksMap)[CHUNK_ID_LIST] = pNewListChunk;
1262            NewChunkSize += LIST_HEADER_SIZE;
1263            pFile->LogAsResized(this);
1264          return pNewListChunk;          return pNewListChunk;
1265      }      }
1266    
# Line 1223  namespace RIFF { Line 1297  namespace RIFF {
1297        std::cout << "List::Readheader(ulong) ";        std::cout << "List::Readheader(ulong) ";
1298        #endif // DEBUG        #endif // DEBUG
1299          Chunk::ReadHeader(fPos);          Chunk::ReadHeader(fPos);
1300            if (CurrentChunkSize < 4) return;
1301          NewChunkSize = CurrentChunkSize -= 4;          NewChunkSize = CurrentChunkSize -= 4;
1302          #if POSIX          #if POSIX
1303          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);          lseek(pFile->hFileRead, fPos + CHUNK_HEADER_SIZE, SEEK_SET);
# Line 1268  namespace RIFF { Line 1343  namespace RIFF {
1343          if (!pSubChunks) {          if (!pSubChunks) {
1344              pSubChunks    = new ChunkList();              pSubChunks    = new ChunkList();
1345              pSubChunksMap = new ChunkMap();              pSubChunksMap = new ChunkMap();
1346                #if defined(WIN32)
1347                if (pFile->hFileRead == INVALID_HANDLE_VALUE) return;
1348                #else
1349              if (!pFile->hFileRead) return;              if (!pFile->hFileRead) return;
1350                #endif
1351              unsigned long uiOriginalPos = GetPos();              unsigned long uiOriginalPos = GetPos();
1352              SetPos(0); // jump to beginning of list chunk body              SetPos(0); // jump to beginning of list chunk body
1353              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {              while (RemainingBytes() >= CHUNK_HEADER_SIZE) {
# Line 1358  namespace RIFF { Line 1437  namespace RIFF {
1437  // *************** File ***************  // *************** File ***************
1438  // *  // *
1439    
1440    //HACK: to avoid breaking DLL compatibility to older versions of libgig we roll the new std::set<Chunk*> into the old std::list<Chunk*> container, should be replaced on member variable level soon though
1441    #define _GET_RESIZED_CHUNKS() \
1442            (reinterpret_cast<std::set<Chunk*>*>(ResizedChunks.front()))
1443    
1444      /** @brief Create new RIFF file.      /** @brief Create new RIFF file.
1445       *       *
1446       * Use this constructor if you want to create a new RIFF file completely       * Use this constructor if you want to create a new RIFF file completely
1447       * "from scratch". Note: there must be no empty chunks or empty list       * "from scratch". Note: there must be no empty chunks or empty list
1448       * chunks when trying to make the new RIFF file persistent with Save()!       * chunks when trying to make the new RIFF file persistent with Save()!
1449       *       *
1450         * Note: by default, the RIFF file will be saved in native endian
1451         * format; that is, as a RIFF file on little-endian machines and
1452         * as a RIFX file on big-endian. To change this behaviour, call
1453         * SetByteOrder() before calling Save().
1454         *
1455       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1456       * @see AddSubChunk(), AddSubList()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1457       */       */
1458      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType)
1459            : List(this), bIsNewFile(true), Layout(layout_standard)
1460        {
1461            //HACK: see _GET_RESIZED_CHUNKS() comment
1462            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1463          #if defined(WIN32)          #if defined(WIN32)
1464          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1465          #else          #else
# Line 1387  namespace RIFF { Line 1479  namespace RIFF {
1479       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occured while trying to load the
1480       *                         given RIFF file       *                         given RIFF file
1481       */       */
1482      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path)
1483        #if DEBUG          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard)
1484        std::cout << "File::File("<<path<<")" << std::endl;      {
1485        #endif // DEBUG         #if DEBUG
1486           std::cout << "File::File("<<path<<")" << std::endl;
1487           #endif // DEBUG
1488          bEndianNative = true;          bEndianNative = true;
1489            try {
1490                __openExistingFile(path);
1491                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1492                    throw RIFF::Exception("Not a RIFF file");
1493                }
1494            }
1495            catch (...) {
1496                Cleanup();
1497                throw;
1498            }
1499        }
1500    
1501        /** @brief Load existing RIFF-like file.
1502         *
1503         * Loads an existing file, which is not a "real" RIFF file, but similar to
1504         * an ordinary RIFF file.
1505         *
1506         * A "real" RIFF file contains at top level a List chunk either with chunk
1507         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1508         * case, and if it finds the toplevel List chunk to have another chunk ID
1509         * than one of those two expected ones, it would throw an Exception and
1510         * would refuse to load the file accordingly.
1511         *
1512         * Since there are however a lot of file formats which use the same simple
1513         * principles of the RIFF format, with another toplevel List chunk ID
1514         * though, you can use this alternative constructor here to be able to load
1515         * and handle those files in the same way as you would do with "real" RIFF
1516         * files.
1517         *
1518         * @param path - path and file name of the RIFF-alike file to be opened
1519         * @param FileType - expected toplevel List chunk ID (this is the very
1520         *                   first chunk found in the file)
1521         * @param Endian - whether the file uses little endian or big endian layout
1522         * @param layout - general file structure type
1523         * @throws RIFF::Exception if error occured while trying to load the
1524         *                         given RIFF-alike file
1525         */
1526        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout)
1527            : List(this), Filename(path), bIsNewFile(false), Layout(layout)
1528        {
1529            SetByteOrder(Endian);
1530            try {
1531                __openExistingFile(path, &FileType);
1532            }
1533            catch (...) {
1534                Cleanup();
1535                throw;
1536            }
1537        }
1538    
1539        /**
1540         * Opens an already existing RIFF file or RIFF-alike file. This method
1541         * shall only be called once (in a File class constructor).
1542         *
1543         * @param path - path and file name of the RIFF file or RIFF-alike file to
1544         *               be opened
1545         * @param FileType - (optional) expected chunk ID of first chunk in file
1546         * @throws RIFF::Exception if error occured while trying to load the
1547         *                         given RIFF file or RIFF-alike file
1548         */
1549        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1550            //HACK: see _GET_RESIZED_CHUNKS() comment
1551            ResizedChunks.push_back(reinterpret_cast<Chunk*>(new std::set<Chunk*>));
1552          #if POSIX          #if POSIX
1553          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1554          if (hFileRead <= 0) {          if (hFileRead == -1) {
1555              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1556              throw RIFF::Exception("Can't open \"" + path + "\"");              String sError = strerror(errno);
1557                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1558          }          }
1559          #elif defined(WIN32)          #elif defined(WIN32)
1560          hFileRead = hFileWrite = CreateFile(          hFileRead = hFileWrite = CreateFile(
1561                                       path.c_str(), GENERIC_READ,                                       path.c_str(), GENERIC_READ,
1562                                       FILE_SHARE_READ | FILE_SHARE_WRITE,                                       FILE_SHARE_READ | FILE_SHARE_WRITE,
1563                                       NULL, OPEN_EXISTING,                                       NULL, OPEN_EXISTING,
1564                                       FILE_ATTRIBUTE_NORMAL, NULL                                       FILE_ATTRIBUTE_NORMAL |
1565                                         FILE_FLAG_RANDOM_ACCESS, NULL
1566                                   );                                   );
1567          if (hFileRead == INVALID_HANDLE_VALUE) {          if (hFileRead == INVALID_HANDLE_VALUE) {
1568              hFileRead = hFileWrite = INVALID_HANDLE_VALUE;              hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
# Line 1414  namespace RIFF { Line 1573  namespace RIFF {
1573          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1574          #endif // POSIX          #endif // POSIX
1575          Mode = stream_mode_read;          Mode = stream_mode_read;
1576          ulStartPos = RIFF_HEADER_SIZE;          switch (Layout) {
1577          ReadHeader(0);              case layout_standard: // this is a normal RIFF file
1578          if (ChunkID != CHUNK_ID_RIFF) {                  ulStartPos = RIFF_HEADER_SIZE;
1579              throw RIFF::Exception("Not a RIFF file");                  ReadHeader(0);
1580                    if (FileType && ChunkID != *FileType)
1581                        throw RIFF::Exception("Invalid file container ID");
1582                    break;
1583                case layout_flat: // non-standard RIFF-alike file
1584                    ulStartPos = 0;
1585                    NewChunkSize = CurrentChunkSize = GetFileSize();
1586                    if (FileType) {
1587                        uint32_t ckid;
1588                        if (Read(&ckid, 4, 1) != 4) {
1589                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1590                        } else if (ckid != *FileType) {
1591                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1592                            throw RIFF::Exception("Invalid file header ID" + s);
1593                        }
1594                        SetPos(0); // reset to first byte of file
1595                    }
1596                    LoadSubChunks();
1597                    break;
1598          }          }
1599      }      }
1600    
1601      String File::GetFileName() {      String File::GetFileName() {
1602          return Filename;          return Filename;
1603      }      }
1604        
1605        void File::SetFileName(const String& path) {
1606            Filename = path;
1607        }
1608    
1609      stream_mode_t File::GetMode() {      stream_mode_t File::GetMode() {
1610          return Mode;          return Mode;
1611      }      }
1612    
1613        layout_t File::GetLayout() const {
1614            return Layout;
1615        }
1616    
1617      /** @brief Change file access mode.      /** @brief Change file access mode.
1618       *       *
1619       * Changes files access mode either to read-only mode or to read/write       * Changes files access mode either to read-only mode or to read/write
# Line 1446  namespace RIFF { Line 1631  namespace RIFF {
1631                      #if POSIX                      #if POSIX
1632                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1633                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1634                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1635                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1636                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          String sError = strerror(errno);
1637                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1638                      }                      }
1639                      #elif defined(WIN32)                      #elif defined(WIN32)
1640                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1456  namespace RIFF { Line 1642  namespace RIFF {
1642                                                   Filename.c_str(), GENERIC_READ,                                                   Filename.c_str(), GENERIC_READ,
1643                                                   FILE_SHARE_READ | FILE_SHARE_WRITE,                                                   FILE_SHARE_READ | FILE_SHARE_WRITE,
1644                                                   NULL, OPEN_EXISTING,                                                   NULL, OPEN_EXISTING,
1645                                                   FILE_ATTRIBUTE_NORMAL, NULL                                                   FILE_ATTRIBUTE_NORMAL |
1646                                                     FILE_FLAG_RANDOM_ACCESS,
1647                                                     NULL
1648                                               );                                               );
1649                      if (hFileRead == INVALID_HANDLE_VALUE) {                      if (hFileRead == INVALID_HANDLE_VALUE) {
1650                          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;                          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
# Line 1473  namespace RIFF { Line 1661  namespace RIFF {
1661                      #if POSIX                      #if POSIX
1662                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1663                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1664                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1665                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1666                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          String sError = strerror(errno);
1667                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1668                      }                      }
1669                      #elif defined(WIN32)                      #elif defined(WIN32)
1670                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1484  namespace RIFF { Line 1673  namespace RIFF {
1673                                                   GENERIC_READ | GENERIC_WRITE,                                                   GENERIC_READ | GENERIC_WRITE,
1674                                                   FILE_SHARE_READ,                                                   FILE_SHARE_READ,
1675                                                   NULL, OPEN_ALWAYS,                                                   NULL, OPEN_ALWAYS,
1676                                                   FILE_ATTRIBUTE_NORMAL, NULL                                                   FILE_ATTRIBUTE_NORMAL |
1677                                                     FILE_FLAG_RANDOM_ACCESS,
1678                                                     NULL
1679                                               );                                               );
1680                      if (hFileRead == INVALID_HANDLE_VALUE) {                      if (hFileRead == INVALID_HANDLE_VALUE) {
1681                          hFileRead = hFileWrite = CreateFile(                          hFileRead = hFileWrite = CreateFile(
1682                                                       Filename.c_str(), GENERIC_READ,                                                       Filename.c_str(), GENERIC_READ,
1683                                                       FILE_SHARE_READ | FILE_SHARE_WRITE,                                                       FILE_SHARE_READ | FILE_SHARE_WRITE,
1684                                                       NULL, OPEN_EXISTING,                                                       NULL, OPEN_EXISTING,
1685                                                       FILE_ATTRIBUTE_NORMAL, NULL                                                       FILE_ATTRIBUTE_NORMAL |
1686                                                         FILE_FLAG_RANDOM_ACCESS,
1687                                                         NULL
1688                                                   );                                                   );
1689                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          throw Exception("Could not (re)open file \"" + Filename + "\" in read+write mode");
1690                      }                      }
1691                      #else                      #else
1692                      if (hFileRead) fclose(hFileRead);                      if (hFileRead) fclose(hFileRead);
# Line 1527  namespace RIFF { Line 1720  namespace RIFF {
1720          return false;          return false;
1721      }      }
1722    
1723        /** @brief Set the byte order to be used when saving.
1724         *
1725         * Set the byte order to be used in the file. A value of
1726         * endian_little will create a RIFF file, endian_big a RIFX file
1727         * and endian_native will create a RIFF file on little-endian
1728         * machines and RIFX on big-endian machines.
1729         *
1730         * @param Endian - endianess to use when file is saved.
1731         */
1732        void File::SetByteOrder(endian_t Endian) {
1733            #if WORDS_BIGENDIAN
1734            bEndianNative = Endian != endian_little;
1735            #else
1736            bEndianNative = Endian != endian_big;
1737            #endif
1738        }
1739    
1740      /** @brief Save changes to same file.      /** @brief Save changes to same file.
1741       *       *
1742       * 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 1538  namespace RIFF { Line 1748  namespace RIFF {
1748       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1749       */       */
1750      void File::Save() {      void File::Save() {
1751            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1752            if (Layout == layout_flat)
1753                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1754    
1755          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1756          LoadSubChunksRecursively();          LoadSubChunksRecursively();
1757    
# Line 1553  namespace RIFF { Line 1767  namespace RIFF {
1767    
1768          // 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)
1769          unsigned long ulPositiveSizeDiff = 0;          unsigned long ulPositiveSizeDiff = 0;
1770          for (ChunkList::iterator iter = ResizedChunks.begin(), end = ResizedChunks.end(); iter != end; ++iter) {          std::set<Chunk*>* resizedChunks = _GET_RESIZED_CHUNKS();
1771            for (std::set<Chunk*>::const_iterator iter = resizedChunks->begin(), end = resizedChunks->end(); iter != end; ++iter) {
1772              if ((*iter)->GetNewSize() == 0) {              if ((*iter)->GetNewSize() == 0) {
1773                  throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));                  throw Exception("There is at least one empty chunk (zero size): " + __resolveChunkPath(*iter));
1774              }              }
1775              if ((*iter)->GetNewSize() + 1L > (*iter)->GetSize()) {              unsigned long newSizePadded = (*iter)->GetNewSize() + (*iter)->GetNewSize() % 2;
1776                  unsigned long ulDiff = (*iter)->GetNewSize() - (*iter)->GetSize() + 1L; // +1 in case we have to add a pad byte              unsigned long oldSizePadded = (*iter)->GetSize() + (*iter)->GetSize() % 2;
1777                  ulPositiveSizeDiff += ulDiff;              if (newSizePadded > oldSizePadded) ulPositiveSizeDiff += newSizePadded - oldSizePadded;
             }  
1778          }          }
1779    
1780          unsigned long ulWorkingFileSize = GetFileSize();          unsigned long ulWorkingFileSize = GetFileSize();
# Line 1576  namespace RIFF { Line 1790  namespace RIFF {
1790              #if defined(WIN32)              #if defined(WIN32)
1791              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured              DWORD iBytesMoved = 1; // we have to pass it via pointer to the Windows API, thus the correct size must be ensured
1792              #else              #else
1793              int iBytesMoved = 1;              int iBytesMoved = 1;
1794              #endif              #endif
1795              for (unsigned long ulPos = 0; iBytesMoved > 0; ulPos += iBytesMoved) {              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {
1796                  const unsigned long ulToMove = ulFileSize - ulPos;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1797                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  ulPos -= iBytesMoved;
1798                  #if POSIX                  #if POSIX
1799                  lseek(hFileRead, ulPos, SEEK_SET);                  lseek(hFileRead, ulPos, SEEK_SET);
1800                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);                  iBytesMoved = read(hFileRead, pCopyBuffer, iBytesMoved);
# Line 1610  namespace RIFF { Line 1824  namespace RIFF {
1824          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1825    
1826          // forget all resized chunks          // forget all resized chunks
1827          ResizedChunks.clear();          resizedChunks->clear();
1828      }      }
1829    
1830      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1629  namespace RIFF { Line 1843  namespace RIFF {
1843      void File::Save(const String& path) {      void File::Save(const String& path) {
1844          //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
1845    
1846            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1847            if (Layout == layout_flat)
1848                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1849    
1850          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1851          LoadSubChunksRecursively();          LoadSubChunksRecursively();
1852    
1853          if (Filename.length() > 0) SetMode(stream_mode_read);          if (!bIsNewFile) SetMode(stream_mode_read);
1854          // 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
1855          #if POSIX          #if POSIX
1856          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);          hFileWrite = open(path.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
1857          if (hFileWrite < 0) {          if (hFileWrite == -1) {
1858              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1859              throw Exception("Could not open file \"" + path + "\" for writing");              String sError = strerror(errno);
1860                throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
1861          }          }
1862          #elif defined(WIN32)          #elif defined(WIN32)
1863          hFileWrite = CreateFile(          hFileWrite = CreateFile(
1864                           path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,                           path.c_str(), GENERIC_WRITE, FILE_SHARE_READ,
1865                           NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL                           NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL |
1866                             FILE_FLAG_RANDOM_ACCESS, NULL
1867                       );                       );
1868          if (hFileWrite == INVALID_HANDLE_VALUE) {          if (hFileWrite == INVALID_HANDLE_VALUE) {
1869              hFileWrite = hFileRead;              hFileWrite = hFileRead;
# Line 1666  namespace RIFF { Line 1886  namespace RIFF {
1886          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1887    
1888          // forget all resized chunks          // forget all resized chunks
1889          ResizedChunks.clear();          _GET_RESIZED_CHUNKS()->clear();
1890    
1891          if (Filename.length() > 0) {          #if POSIX
1892              #if POSIX          if (hFileWrite) close(hFileWrite);
1893              close(hFileWrite);          #elif defined(WIN32)
1894              #elif defined(WIN32)          if (hFileWrite != INVALID_HANDLE_VALUE) CloseHandle(hFileWrite);
1895              CloseHandle(hFileWrite);          #else
1896              #else          if (hFileWrite) fclose(hFileWrite);
1897              fclose(hFileWrite);          #endif
1898              #endif          hFileWrite = hFileRead;
             hFileWrite = hFileRead;  
         }  
1899    
1900          // associate new file with this File object from now on          // associate new file with this File object from now on
1901          Filename = path;          Filename = path;
1902            bIsNewFile = false;
1903          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1904          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.          SetMode(stream_mode_read_write); // ... so SetMode() has to reopen the file handles.
1905      }      }
# Line 1704  namespace RIFF { Line 1923  namespace RIFF {
1923         #if DEBUG         #if DEBUG
1924         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
1925         #endif // DEBUG         #endif // DEBUG
1926            Cleanup();
1927        }
1928        
1929        /**
1930         * Returns @c true if this file has been created new from scratch and
1931         * has not been stored to disk yet.
1932         */
1933        bool File::IsNew() const {
1934            return bIsNewFile;
1935        }
1936    
1937        void File::Cleanup() {
1938          #if POSIX          #if POSIX
1939          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
1940          #elif defined(WIN32)          #elif defined(WIN32)
# Line 1711  namespace RIFF { Line 1942  namespace RIFF {
1942          #else          #else
1943          if (hFileRead) fclose(hFileRead);          if (hFileRead) fclose(hFileRead);
1944          #endif // POSIX          #endif // POSIX
1945            DeleteChunkList();
1946            pFile = NULL;
1947            //HACK: see _GET_RESIZED_CHUNKS() comment
1948            delete _GET_RESIZED_CHUNKS();
1949      }      }
1950    
1951      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {
1952          ResizedChunks.push_back(pResizedChunk);          _GET_RESIZED_CHUNKS()->insert(pResizedChunk);
1953      }      }
1954    
1955      void File::UnlogResized(Chunk* pResizedChunk) {      void File::UnlogResized(Chunk* pResizedChunk) {
1956          ResizedChunks.remove(pResizedChunk);          _GET_RESIZED_CHUNKS()->erase(pResizedChunk);
1957      }      }
1958    
1959      unsigned long File::GetFileSize() {      unsigned long File::GetFileSize() {

Legend:
Removed from v.1105  
changed lines
  Added in v.2675

  ViewVC Help
Powered by ViewVC