/[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 1885 by persson, Thu Apr 16 18:25:31 2009 UTC revision 2703 by schoenebeck, Tue Jan 13 15:28:37 2015 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-2009 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2015 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 22  Line 22 
22   ***************************************************************************/   ***************************************************************************/
23    
24  #include <algorithm>  #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 **************
# Line 49  namespace RIFF { Line 54  namespace RIFF {
54    
55    
56    
57    // *************** progress_t ***************
58    // *
59    
60        progress_t::progress_t() {
61            callback    = NULL;
62            custom      = NULL;
63            __range_min = 0.0f;
64            __range_max = 1.0f;
65        }
66    
67    
68    
69  // *************** Chunk **************  // *************** Chunk **************
70  // *  // *
71    
# Line 280  namespace RIFF { Line 297  namespace RIFF {
297         #if DEBUG         #if DEBUG
298         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;         std::cout << "Chunk::Read(void*,ulong,ulong)" << std::endl;
299         #endif // DEBUG         #endif // DEBUG
300          if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)          //if (ulStartPos == 0) return 0; // is only 0 if this is a new chunk, so nothing to read (yet)
301          if (ulPos >= CurrentChunkSize) return 0;          if (ulPos >= CurrentChunkSize) return 0;
302          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;          if (ulPos + WordCount * WordSize >= CurrentChunkSize) WordCount = (CurrentChunkSize - ulPos) / WordSize;
303          #if POSIX          #if POSIX
304          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;          if (lseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET) < 0) return 0;
305          unsigned long readWords = read(pFile->hFileRead, pData, WordCount * WordSize);          ssize_t readWords = read(pFile->hFileRead, pData, WordCount * WordSize);
306          if (readWords < 1) return 0;          if (readWords < 1) {
307                #if DEBUG
308                std::cerr << "POSIX read() failed: " << strerror(errno) << std::endl << std::flush;
309                #endif // DEBUG
310                return 0;
311            }
312          readWords /= WordSize;          readWords /= WordSize;
313          #elif defined(WIN32)          #elif defined(WIN32)
314          if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;          if (SetFilePointer(pFile->hFileRead, ulStartPos + ulPos, NULL/*32 bit*/, FILE_BEGIN) == INVALID_SET_FILE_POINTER) return 0;
# Line 296  namespace RIFF { Line 318  namespace RIFF {
318          readWords /= WordSize;          readWords /= WordSize;
319          #else // standard C functions          #else // standard C functions
320          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;          if (fseek(pFile->hFileRead, ulStartPos + ulPos, SEEK_SET)) return 0;
321          unsigned long readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);          size_t readWords = fread(pData, WordSize, WordCount, pFile->hFileRead);
322          #endif // POSIX          #endif // POSIX
323          if (!pFile->bEndianNative && WordSize != 1) {          if (!pFile->bEndianNative && WordSize != 1) {
324              switch (WordSize) {              switch (WordSize) {
# Line 594  namespace RIFF { Line 616  namespace RIFF {
616      }      }
617    
618      /**      /**
619         * Reads a null-padded string of size characters and copies it
620         * into the string \a s. The position within the chunk will
621         * automatically be incremented.
622         *
623         * @param s                 destination string
624         * @param size              number of characters to read
625         * @throws RIFF::Exception  if an error occured or less than
626         *                          \a size characters could be read!
627         */
628        void Chunk::ReadString(String& s, int size) {
629            char* buf = new char[size];
630            ReadSceptical(buf, 1, size);
631            s.assign(buf, std::find(buf, buf + size, '\0'));
632            delete[] buf;
633        }
634    
635        /**
636       * Writes \a WordCount number of 32 Bit unsigned integer words from the       * Writes \a WordCount number of 32 Bit unsigned integer words from the
637       * 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
638       * actual "physical" file. The position within the chunk will       * actual "physical" file. The position within the chunk will
# Line 733  namespace RIFF { Line 772  namespace RIFF {
772       * @see ReleaseChunkData()       * @see ReleaseChunkData()
773       */       */
774      void* Chunk::LoadChunkData() {      void* Chunk::LoadChunkData() {
775          if (!pChunkData && pFile->Filename != "" && ulStartPos != 0) {          if (!pChunkData && pFile->Filename != "" /*&& ulStartPos != 0*/) {
776              #if POSIX              #if POSIX
777              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;              if (lseek(pFile->hFileRead, ulStartPos, SEEK_SET) == -1) return NULL;
778              #elif defined(WIN32)              #elif defined(WIN32)
# Line 817  namespace RIFF { Line 856  namespace RIFF {
856       *                     chunk should be written to       *                     chunk should be written to
857       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ulCurrentDataOffset - offset of current (old) data within
858       *                              the file       *                              the file
859         * @param pProgress - optional: callback function for progress notification
860       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
861       *          \a ulWritePos incremented by this chunk's new size       *          \a ulWritePos incremented by this chunk's new size
862       *          (including its header size of course)       *          (including its header size of course)
863       */       */
864      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long Chunk::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset, progress_t* pProgress) {
865          const unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
866          ulWritePos += CHUNK_HEADER_SIZE;          ulWritePos += CHUNK_HEADER_SIZE;
867    
# Line 860  namespace RIFF { Line 900  namespace RIFF {
900              #else              #else
901              int iBytesMoved = 1;              int iBytesMoved = 1;
902              #endif              #endif
903              for (unsigned long ulOffset = 0; iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {              for (unsigned long ulOffset = 0; ulToMove > 0 && iBytesMoved > 0; ulOffset += iBytesMoved, ulToMove -= iBytesMoved) {
904                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;                  iBytesMoved = (ulToMove < 4096) ? ulToMove : 4096;
905                  #if POSIX                  #if POSIX
906                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);                  lseek(pFile->hFileRead, ulStartPos + ulCurrentDataOffset + ulOffset, SEEK_SET);
# Line 887  namespace RIFF { Line 927  namespace RIFF {
927          CurrentChunkSize = NewChunkSize;          CurrentChunkSize = NewChunkSize;
928          WriteHeader(ulOriginalPos);          WriteHeader(ulOriginalPos);
929    
930            __notify_progress(pProgress, 1.0); // notify done
931    
932          // update chunk's position pointers          // update chunk's position pointers
933          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;          ulStartPos = ulOriginalPos + CHUNK_HEADER_SIZE;
934          ulPos      = 0;          ulPos      = 0;
# Line 1173  namespace RIFF { Line 1215  namespace RIFF {
1215          return pNewChunk;          return pNewChunk;
1216      }      }
1217    
1218      /** @brief Moves a sub chunk.      /** @brief Moves a sub chunk witin this list.
1219       *       *
1220       * Moves a sub chunk from one position in a list to another       * Moves a sub chunk from one position in this list to another
1221       * position in the same list. The pSrc chunk is placed before the       * position in the same list. The pSrc chunk is placed before the
1222       * pDst chunk.       * pDst chunk.
1223       *       *
# Line 1191  namespace RIFF { Line 1233  namespace RIFF {
1233          pSubChunks->insert(iter, pSrc);          pSubChunks->insert(iter, pSrc);
1234      }      }
1235    
1236        /** @brief Moves a sub chunk from this list to another list.
1237         *
1238         * Moves a sub chunk from this list list to the end of another
1239         * list.
1240         *
1241         * @param pSrc - sub chunk to be moved
1242         * @param pDst - destination list where the chunk shall be moved to
1243         */
1244        void List::MoveSubChunk(Chunk* pSrc, List* pNewParent) {
1245            if (pNewParent == this || !pNewParent) return;
1246            if (!pSubChunks) LoadSubChunks();
1247            if (!pNewParent->pSubChunks) pNewParent->LoadSubChunks();
1248            pSubChunks->remove(pSrc);
1249            pNewParent->pSubChunks->push_back(pSrc);
1250            // update chunk id map of this List
1251            if ((*pSubChunksMap)[pSrc->GetChunkID()] == pSrc) {
1252                pSubChunksMap->erase(pSrc->GetChunkID());
1253                // try to find another chunk of the same chunk ID
1254                ChunkList::iterator iter = pSubChunks->begin();
1255                ChunkList::iterator end  = pSubChunks->end();
1256                for (; iter != end; ++iter) {
1257                    if ((*iter)->GetChunkID() == pSrc->GetChunkID()) {
1258                        (*pSubChunksMap)[pSrc->GetChunkID()] = *iter;
1259                        break; // we're done, stop search
1260                    }
1261                }
1262            }
1263            // update chunk id map of other list
1264            if (!(*pNewParent->pSubChunksMap)[pSrc->GetChunkID()])
1265                (*pNewParent->pSubChunksMap)[pSrc->GetChunkID()] = pSrc;
1266        }
1267    
1268      /** @brief Creates a new list sub chunk.      /** @brief Creates a new list sub chunk.
1269       *       *
1270       * 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 1282  namespace RIFF { Line 1356  namespace RIFF {
1356          #endif // POSIX          #endif // POSIX
1357      }      }
1358    
1359      void List::LoadSubChunks() {      void List::LoadSubChunks(progress_t* pProgress) {
1360         #if DEBUG         #if DEBUG
1361         std::cout << "List::LoadSubChunks()";         std::cout << "List::LoadSubChunks()";
1362         #endif // DEBUG         #endif // DEBUG
# Line 1317  namespace RIFF { Line 1391  namespace RIFF {
1391              }              }
1392              SetPos(uiOriginalPos); // restore position before this call              SetPos(uiOriginalPos); // restore position before this call
1393          }          }
1394            __notify_progress(pProgress, 1.0); // notify done
1395      }      }
1396    
1397      void List::LoadSubChunksRecursively() {      void List::LoadSubChunksRecursively(progress_t* pProgress) {
1398          for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList())          const int n = CountSubLists();
1399              pList->LoadSubChunksRecursively();          int i = 0;
1400            for (List* pList = GetFirstSubList(); pList; pList = GetNextSubList(), ++i) {
1401                // divide local progress into subprogress
1402                progress_t subprogress;
1403                __divide_progress(pProgress, &subprogress, n, i);
1404                // do the actual work
1405                pList->LoadSubChunksRecursively(&subprogress);
1406            }
1407            __notify_progress(pProgress, 1.0); // notify done
1408      }      }
1409    
1410      /** @brief Write list chunk persistently e.g. to disk.      /** @brief Write list chunk persistently e.g. to disk.
# Line 1334  namespace RIFF { Line 1417  namespace RIFF {
1417       *                     list chunk should be written to       *                     list chunk should be written to
1418       * @param ulCurrentDataOffset - offset of current (old) data within       * @param ulCurrentDataOffset - offset of current (old) data within
1419       *                              the file       *                              the file
1420         * @param pProgress - optional: callback function for progress notification
1421       * @returns new write position in the "physical" file, that is       * @returns new write position in the "physical" file, that is
1422       *          \a ulWritePos incremented by this list chunk's new size       *          \a ulWritePos incremented by this list chunk's new size
1423       *          (including its header size of course)       *          (including its header size of course)
1424       */       */
1425      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset) {      unsigned long List::WriteChunk(unsigned long ulWritePos, unsigned long ulCurrentDataOffset, progress_t* pProgress) {
1426          const unsigned long ulOriginalPos = ulWritePos;          const unsigned long ulOriginalPos = ulWritePos;
1427          ulWritePos += LIST_HEADER_SIZE;          ulWritePos += LIST_HEADER_SIZE;
1428    
# Line 1347  namespace RIFF { Line 1431  namespace RIFF {
1431    
1432          // write all subchunks (including sub list chunks) recursively          // write all subchunks (including sub list chunks) recursively
1433          if (pSubChunks) {          if (pSubChunks) {
1434              for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter) {              int i = 0;
1435                  ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset);              const int n = pSubChunks->size();
1436                for (ChunkList::iterator iter = pSubChunks->begin(), end = pSubChunks->end(); iter != end; ++iter, ++i) {
1437                    // divide local progress into subprogress for loading current Instrument
1438                    progress_t subprogress;
1439                    __divide_progress(pProgress, &subprogress, n, i);
1440                    // do the actual work
1441                    ulWritePos = (*iter)->WriteChunk(ulWritePos, ulCurrentDataOffset, &subprogress);
1442              }              }
1443          }          }
1444    
# Line 1359  namespace RIFF { Line 1449  namespace RIFF {
1449          // offset of this list chunk in new written file may have changed          // offset of this list chunk in new written file may have changed
1450          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;          ulStartPos = ulOriginalPos + LIST_HEADER_SIZE;
1451    
1452             __notify_progress(pProgress, 1.0); // notify done
1453    
1454          return ulWritePos;          return ulWritePos;
1455      }      }
1456    
# Line 1397  namespace RIFF { Line 1489  namespace RIFF {
1489       * @param FileType - four-byte identifier of the RIFF file type       * @param FileType - four-byte identifier of the RIFF file type
1490       * @see AddSubChunk(), AddSubList(), SetByteOrder()       * @see AddSubChunk(), AddSubList(), SetByteOrder()
1491       */       */
1492      File::File(uint32_t FileType) : List(this) {      File::File(uint32_t FileType)
1493            : List(this), bIsNewFile(true), Layout(layout_standard)
1494        {
1495          #if defined(WIN32)          #if defined(WIN32)
1496          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;          hFileRead = hFileWrite = INVALID_HANDLE_VALUE;
1497          #else          #else
# Line 1417  namespace RIFF { Line 1511  namespace RIFF {
1511       * @throws RIFF::Exception if error occured while trying to load the       * @throws RIFF::Exception if error occured while trying to load the
1512       *                         given RIFF file       *                         given RIFF file
1513       */       */
1514      File::File(const String& path) : List(this), Filename(path) {      File::File(const String& path)
1515        #if DEBUG          : List(this), Filename(path), bIsNewFile(false), Layout(layout_standard)
1516        std::cout << "File::File("<<path<<")" << std::endl;      {
1517        #endif // DEBUG         #if DEBUG
1518           std::cout << "File::File("<<path<<")" << std::endl;
1519           #endif // DEBUG
1520          bEndianNative = true;          bEndianNative = true;
1521            try {
1522                __openExistingFile(path);
1523                if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {
1524                    throw RIFF::Exception("Not a RIFF file");
1525                }
1526            }
1527            catch (...) {
1528                Cleanup();
1529                throw;
1530            }
1531        }
1532    
1533        /** @brief Load existing RIFF-like file.
1534         *
1535         * Loads an existing file, which is not a "real" RIFF file, but similar to
1536         * an ordinary RIFF file.
1537         *
1538         * A "real" RIFF file contains at top level a List chunk either with chunk
1539         * ID "RIFF" or "RIFX". The simple constructor above expects this to be
1540         * case, and if it finds the toplevel List chunk to have another chunk ID
1541         * than one of those two expected ones, it would throw an Exception and
1542         * would refuse to load the file accordingly.
1543         *
1544         * Since there are however a lot of file formats which use the same simple
1545         * principles of the RIFF format, with another toplevel List chunk ID
1546         * though, you can use this alternative constructor here to be able to load
1547         * and handle those files in the same way as you would do with "real" RIFF
1548         * files.
1549         *
1550         * @param path - path and file name of the RIFF-alike file to be opened
1551         * @param FileType - expected toplevel List chunk ID (this is the very
1552         *                   first chunk found in the file)
1553         * @param Endian - whether the file uses little endian or big endian layout
1554         * @param layout - general file structure type
1555         * @throws RIFF::Exception if error occured while trying to load the
1556         *                         given RIFF-alike file
1557         */
1558        File::File(const String& path, uint32_t FileType, endian_t Endian, layout_t layout)
1559            : List(this), Filename(path), bIsNewFile(false), Layout(layout)
1560        {
1561            SetByteOrder(Endian);
1562            try {
1563                __openExistingFile(path, &FileType);
1564            }
1565            catch (...) {
1566                Cleanup();
1567                throw;
1568            }
1569        }
1570    
1571        /**
1572         * Opens an already existing RIFF file or RIFF-alike file. This method
1573         * shall only be called once (in a File class constructor).
1574         *
1575         * @param path - path and file name of the RIFF file or RIFF-alike file to
1576         *               be opened
1577         * @param FileType - (optional) expected chunk ID of first chunk in file
1578         * @throws RIFF::Exception if error occured while trying to load the
1579         *                         given RIFF file or RIFF-alike file
1580         */
1581        void File::__openExistingFile(const String& path, uint32_t* FileType) {
1582            ResizedChunks.clear();
1583          #if POSIX          #if POSIX
1584          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);          hFileRead = hFileWrite = open(path.c_str(), O_RDONLY | O_NONBLOCK);
1585          if (hFileRead <= 0) {          if (hFileRead == -1) {
1586              hFileRead = hFileWrite = 0;              hFileRead = hFileWrite = 0;
1587              throw RIFF::Exception("Can't open \"" + path + "\"");              String sError = strerror(errno);
1588                throw RIFF::Exception("Can't open \"" + path + "\": " + sError);
1589          }          }
1590          #elif defined(WIN32)          #elif defined(WIN32)
1591          hFileRead = hFileWrite = CreateFile(          hFileRead = hFileWrite = CreateFile(
# Line 1445  namespace RIFF { Line 1604  namespace RIFF {
1604          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");          if (!hFileRead) throw RIFF::Exception("Can't open \"" + path + "\"");
1605          #endif // POSIX          #endif // POSIX
1606          Mode = stream_mode_read;          Mode = stream_mode_read;
1607          ulStartPos = RIFF_HEADER_SIZE;          switch (Layout) {
1608          ReadHeader(0);              case layout_standard: // this is a normal RIFF file
1609          if (ChunkID != CHUNK_ID_RIFF && ChunkID != CHUNK_ID_RIFX) {                  ulStartPos = RIFF_HEADER_SIZE;
1610              throw RIFF::Exception("Not a RIFF file");                  ReadHeader(0);
1611                    if (FileType && ChunkID != *FileType)
1612                        throw RIFF::Exception("Invalid file container ID");
1613                    break;
1614                case layout_flat: // non-standard RIFF-alike file
1615                    ulStartPos = 0;
1616                    NewChunkSize = CurrentChunkSize = GetFileSize();
1617                    if (FileType) {
1618                        uint32_t ckid;
1619                        if (Read(&ckid, 4, 1) != 4) {
1620                            throw RIFF::Exception("Invalid file header ID (premature end of header)");
1621                        } else if (ckid != *FileType) {
1622                            String s = " (expected '" + convertToString(*FileType) + "' but got '" + convertToString(ckid) + "')";
1623                            throw RIFF::Exception("Invalid file header ID" + s);
1624                        }
1625                        SetPos(0); // reset to first byte of file
1626                    }
1627                    LoadSubChunks();
1628                    break;
1629          }          }
1630      }      }
1631    
1632      String File::GetFileName() {      String File::GetFileName() {
1633          return Filename;          return Filename;
1634      }      }
1635        
1636        void File::SetFileName(const String& path) {
1637            Filename = path;
1638        }
1639    
1640      stream_mode_t File::GetMode() {      stream_mode_t File::GetMode() {
1641          return Mode;          return Mode;
1642      }      }
1643    
1644        layout_t File::GetLayout() const {
1645            return Layout;
1646        }
1647    
1648      /** @brief Change file access mode.      /** @brief Change file access mode.
1649       *       *
1650       * 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 1477  namespace RIFF { Line 1662  namespace RIFF {
1662                      #if POSIX                      #if POSIX
1663                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1664                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1665                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1666                          hFileRead = hFileWrite = 0;                          hFileRead = hFileWrite = 0;
1667                          throw Exception("Could not (re)open file \"" + Filename + "\" in read mode");                          String sError = strerror(errno);
1668                            throw Exception("Could not (re)open file \"" + Filename + "\" in read mode: " + sError);
1669                      }                      }
1670                      #elif defined(WIN32)                      #elif defined(WIN32)
1671                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1506  namespace RIFF { Line 1692  namespace RIFF {
1692                      #if POSIX                      #if POSIX
1693                      if (hFileRead) close(hFileRead);                      if (hFileRead) close(hFileRead);
1694                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);                      hFileRead = hFileWrite = open(Filename.c_str(), O_RDWR | O_NONBLOCK);
1695                      if (hFileRead < 0) {                      if (hFileRead == -1) {
1696                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);                          hFileRead = hFileWrite = open(Filename.c_str(), O_RDONLY | O_NONBLOCK);
1697                          throw Exception("Could not open file \"" + Filename + "\" in read+write mode");                          String sError = strerror(errno);
1698                            throw Exception("Could not open file \"" + Filename + "\" in read+write mode: " + sError);
1699                      }                      }
1700                      #elif defined(WIN32)                      #elif defined(WIN32)
1701                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);                      if (hFileRead != INVALID_HANDLE_VALUE) CloseHandle(hFileRead);
# Line 1588  namespace RIFF { Line 1775  namespace RIFF {
1775       * than it will have at the end of the saving process, in case chunks       * than it will have at the end of the saving process, in case chunks
1776       * were grown.       * were grown.
1777       *       *
1778         * @param pProgress - optional: callback function for progress notification
1779       * @throws RIFF::Exception if there is an empty chunk or empty list       * @throws RIFF::Exception if there is an empty chunk or empty list
1780       *                         chunk or any kind of IO error occured       *                         chunk or any kind of IO error occured
1781       */       */
1782      void File::Save() {      void File::Save(progress_t* pProgress) {
1783            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1784            if (Layout == layout_flat)
1785                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1786    
1787          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1788          LoadSubChunksRecursively();          {
1789                // divide progress into subprogress
1790                progress_t subprogress;
1791                __divide_progress(pProgress, &subprogress, 3.f, 0.f); // arbitrarily subdivided into 1/3 of total progress
1792                // do the actual work
1793                LoadSubChunksRecursively(&subprogress);
1794                // notify subprogress done
1795                __notify_progress(&subprogress, 1.f);
1796            }
1797    
1798          // reopen file in write mode          // reopen file in write mode
1799          SetMode(stream_mode_read_write);          SetMode(stream_mode_read_write);
# Line 1620  namespace RIFF { Line 1820  namespace RIFF {
1820    
1821          // if there are positive size changes...          // if there are positive size changes...
1822          if (ulPositiveSizeDiff > 0) {          if (ulPositiveSizeDiff > 0) {
1823                // divide progress into subprogress
1824                progress_t subprogress;
1825                __divide_progress(pProgress, &subprogress, 3.f, 1.f); // arbitrarily subdivided into 1/3 of total progress
1826    
1827              // ... we enlarge this file first ...              // ... we enlarge this file first ...
1828              ulWorkingFileSize += ulPositiveSizeDiff;              ulWorkingFileSize += ulPositiveSizeDiff;
1829              ResizeFile(ulWorkingFileSize);              ResizeFile(ulWorkingFileSize);
# Line 1631  namespace RIFF { Line 1835  namespace RIFF {
1835              #else              #else
1836              int iBytesMoved = 1;              int iBytesMoved = 1;
1837              #endif              #endif
1838              for (unsigned long ulPos = ulFileSize; iBytesMoved > 0; ) {              for (unsigned long ulPos = ulFileSize, iNotif = 0; iBytesMoved > 0; ++iNotif) {
1839                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;                  iBytesMoved = (ulPos < 4096) ? ulPos : 4096;
1840                  ulPos -= iBytesMoved;                  ulPos -= iBytesMoved;
1841                  #if POSIX                  #if POSIX
# Line 1650  namespace RIFF { Line 1854  namespace RIFF {
1854                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);                  fseek(hFileWrite, ulPos + ulPositiveSizeDiff, SEEK_SET);
1855                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);                  iBytesMoved = fwrite(pCopyBuffer, 1, iBytesMoved, hFileWrite);
1856                  #endif                  #endif
1857                    if (!(iNotif % 8) && iBytesMoved > 0)
1858                        __notify_progress(&subprogress, float(ulFileSize - ulPos) / float(ulFileSize));
1859              }              }
1860              delete[] pCopyBuffer;              delete[] pCopyBuffer;
1861              if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");              if (iBytesMoved < 0) throw Exception("Could not modify file while trying to enlarge it");
1862    
1863                __notify_progress(&subprogress, 1.f); // notify subprogress done
1864          }          }
1865    
1866          // rebuild / rewrite complete RIFF tree          // rebuild / rewrite complete RIFF tree ...
1867          unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff);  
1868            // divide progress into subprogress
1869            progress_t subprogress;
1870            __divide_progress(pProgress, &subprogress, 3.f, 2.f); // arbitrarily subdivided into 1/3 of total progress
1871            // do the actual work
1872            unsigned long ulTotalSize  = WriteChunk(0, ulPositiveSizeDiff, &subprogress);
1873          unsigned long ulActualSize = __GetFileSize(hFileWrite);          unsigned long ulActualSize = __GetFileSize(hFileWrite);
1874            // notify subprogress done
1875            __notify_progress(&subprogress, 1.f);
1876    
1877          // resize file to the final size          // resize file to the final size
1878          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);          if (ulTotalSize < ulActualSize) ResizeFile(ulTotalSize);
1879    
1880          // forget all resized chunks          // forget all resized chunks
1881          ResizedChunks.clear();          ResizedChunks.clear();
1882    
1883            __notify_progress(pProgress, 1.0); // notify done
1884      }      }
1885    
1886      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1678  namespace RIFF { Line 1895  namespace RIFF {
1895       * the new file (given by \a path) afterwards.       * the new file (given by \a path) afterwards.
1896       *       *
1897       * @param path - path and file name where everything should be written to       * @param path - path and file name where everything should be written to
1898         * @param pProgress - optional: callback function for progress notification
1899       */       */
1900      void File::Save(const String& path) {      void File::Save(const String& path, progress_t* pProgress) {
1901          //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
1902    
1903            //TODO: implementation for the case where first chunk is not a global container (List chunk) is not implemented yet (i.e. Korg files)
1904            if (Layout == layout_flat)
1905                throw Exception("Saving a RIFF file with layout_flat is not implemented yet");
1906    
1907          // make sure the RIFF tree is built (from the original file)          // make sure the RIFF tree is built (from the original file)
1908          LoadSubChunksRecursively();          {
1909                // divide progress into subprogress
1910                progress_t subprogress;
1911                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 1/2 of total progress
1912                // do the actual work
1913                LoadSubChunksRecursively(&subprogress);
1914                // notify subprogress done
1915                __notify_progress(&subprogress, 1.f);
1916            }
1917    
1918          if (Filename.length() > 0) SetMode(stream_mode_read);          if (!bIsNewFile) SetMode(stream_mode_read);
1919          // 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
1920          #if POSIX          #if POSIX
1921          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);
1922          if (hFileWrite < 0) {          if (hFileWrite == -1) {
1923              hFileWrite = hFileRead;              hFileWrite = hFileRead;
1924              throw Exception("Could not open file \"" + path + "\" for writing");              String sError = strerror(errno);
1925                throw Exception("Could not open file \"" + path + "\" for writing: " + sError);
1926          }          }
1927          #elif defined(WIN32)          #elif defined(WIN32)
1928          hFileWrite = CreateFile(          hFileWrite = CreateFile(
# Line 1713  namespace RIFF { Line 1944  namespace RIFF {
1944          Mode = stream_mode_read_write;          Mode = stream_mode_read_write;
1945    
1946          // write complete RIFF tree to the other (new) file          // write complete RIFF tree to the other (new) file
1947          unsigned long ulTotalSize  = WriteChunk(0, 0);          unsigned long ulTotalSize;
1948            {
1949                // divide progress into subprogress
1950                progress_t subprogress;
1951                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 1/2 of total progress
1952                // do the actual work
1953                ulTotalSize = WriteChunk(0, 0, &subprogress);
1954                // notify subprogress done
1955                __notify_progress(&subprogress, 1.f);
1956            }
1957          unsigned long ulActualSize = __GetFileSize(hFileWrite);          unsigned long ulActualSize = __GetFileSize(hFileWrite);
1958    
1959          // resize file to the final size (if the file was originally larger)          // resize file to the final size (if the file was originally larger)
# Line 1733  namespace RIFF { Line 1973  namespace RIFF {
1973    
1974          // associate new file with this File object from now on          // associate new file with this File object from now on
1975          Filename = path;          Filename = path;
1976            bIsNewFile = false;
1977          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...          Mode = (stream_mode_t) -1;       // Just set it to an undefined mode ...
1978          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.
1979    
1980            __notify_progress(pProgress, 1.0); // notify done
1981      }      }
1982    
1983      void File::ResizeFile(unsigned long ulNewSize) {      void File::ResizeFile(unsigned long ulNewSize) {
# Line 1756  namespace RIFF { Line 1999  namespace RIFF {
1999         #if DEBUG         #if DEBUG
2000         std::cout << "File::~File()" << std::endl;         std::cout << "File::~File()" << std::endl;
2001         #endif // DEBUG         #endif // DEBUG
2002            Cleanup();
2003        }
2004        
2005        /**
2006         * Returns @c true if this file has been created new from scratch and
2007         * has not been stored to disk yet.
2008         */
2009        bool File::IsNew() const {
2010            return bIsNewFile;
2011        }
2012    
2013        void File::Cleanup() {
2014          #if POSIX          #if POSIX
2015          if (hFileRead) close(hFileRead);          if (hFileRead) close(hFileRead);
2016          #elif defined(WIN32)          #elif defined(WIN32)
# Line 1765  namespace RIFF { Line 2020  namespace RIFF {
2020          #endif // POSIX          #endif // POSIX
2021          DeleteChunkList();          DeleteChunkList();
2022          pFile = NULL;          pFile = NULL;
2023            ResizedChunks.clear();
2024      }      }
2025    
2026      void File::LogAsResized(Chunk* pResizedChunk) {      void File::LogAsResized(Chunk* pResizedChunk) {

Legend:
Removed from v.1885  
changed lines
  Added in v.2703

  ViewVC Help
Powered by ViewVC