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

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

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

revision 3053 by schoenebeck, Wed Dec 14 18:55:08 2016 UTC revision 3940 by schoenebeck, Fri Jun 18 13:47:46 2021 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-2016 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2021 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 24  Line 24 
24  #include "DLS.h"  #include "DLS.h"
25    
26  #include <algorithm>  #include <algorithm>
27    #include <vector>
28  #include <time.h>  #include <time.h>
29    
30  #ifdef __APPLE__  #ifdef __APPLE__
# Line 121  namespace DLS { Line 122  namespace DLS {
122              artl->GetChunkID() != CHUNK_ID_ARTL) {              artl->GetChunkID() != CHUNK_ID_ARTL) {
123                throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");                throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");
124          }          }
125    
126            artl->SetPos(0);
127    
128          HeaderSize  = artl->ReadUint32();          HeaderSize  = artl->ReadUint32();
129          Connections = artl->ReadUint32();          Connections = artl->ReadUint32();
130          artl->SetPos(HeaderSize);          artl->SetPos(HeaderSize);
# Line 163  namespace DLS { Line 167  namespace DLS {
167          }          }
168      }      }
169    
170        /** @brief Remove all RIFF chunks associated with this Articulation object.
171         *
172         * At the moment Articulation::DeleteChunks() does nothing. It is
173         * recommended to call this method explicitly though from deriving classes's
174         * own overridden implementation of this method to avoid potential future
175         * compatiblity issues.
176         *
177         * See Storage::DeleteChunks() for details.
178         */
179        void Articulation::DeleteChunks() {
180        }
181    
182    
183    
184  // *************** Articulator  ***************  // *************** Articulator  ***************
# Line 173  namespace DLS { Line 189  namespace DLS {
189          pArticulations = NULL;          pArticulations = NULL;
190      }      }
191    
192        /**
193         * Returns Articulation at supplied @a pos position within the articulation
194         * list. If supplied @a pos is out of bounds then @c NULL is returned.
195         *
196         * @param pos - position of sought Articulation in articulation list
197         * @returns pointer address to requested articulation or @c NULL if @a pos
198         *          is out of bounds
199         */
200        Articulation* Articulator::GetArticulation(size_t pos) {
201            if (!pArticulations) LoadArticulations();
202            if (!pArticulations) return NULL;
203            if (pos >= pArticulations->size()) return NULL;
204            return (*pArticulations)[pos];
205        }
206    
207        /**
208         * Returns the first Articulation in the list of articulations. You have to
209         * call this method once before you can use GetNextArticulation().
210         *
211         * @returns  pointer address to first Articulation or NULL if there is none
212         * @see      GetNextArticulation()
213         * @deprecated  This method is not reentrant-safe, use GetArticulation()
214         *              instead.
215         */
216      Articulation* Articulator::GetFirstArticulation() {      Articulation* Articulator::GetFirstArticulation() {
217          if (!pArticulations) LoadArticulations();          if (!pArticulations) LoadArticulations();
218          if (!pArticulations) return NULL;          if (!pArticulations) return NULL;
# Line 180  namespace DLS { Line 220  namespace DLS {
220          return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;          return (ArticulationsIterator != pArticulations->end()) ? *ArticulationsIterator : NULL;
221      }      }
222    
223        /**
224         * Returns the next Articulation from the list of articulations. You have
225         * to call GetFirstArticulation() once before you can use this method. By
226         * calling this method multiple times it iterates through the available
227         * articulations.
228         *
229         * @returns  pointer address to the next Articulation or NULL if end reached
230         * @see      GetFirstArticulation()
231         * @deprecated  This method is not reentrant-safe, use GetArticulation()
232         *              instead.
233         */
234      Articulation* Articulator::GetNextArticulation() {      Articulation* Articulator::GetNextArticulation() {
235          if (!pArticulations) return NULL;          if (!pArticulations) return NULL;
236          ArticulationsIterator++;          ArticulationsIterator++;
# Line 193  namespace DLS { Line 244  namespace DLS {
244          if (lart) {          if (lart) {
245              uint32_t artCkType = (lart->GetListType() == LIST_TYPE_LAR2) ? CHUNK_ID_ART2              uint32_t artCkType = (lart->GetListType() == LIST_TYPE_LAR2) ? CHUNK_ID_ART2
246                                                                           : CHUNK_ID_ARTL;                                                                           : CHUNK_ID_ARTL;
247              RIFF::Chunk* art = lart->GetFirstSubChunk();              size_t i = 0;
248              while (art) {              for (RIFF::Chunk* art = lart->GetSubChunkAt(i); art;
249                     art = lart->GetSubChunkAt(++i))
250                {
251                  if (art->GetChunkID() == artCkType) {                  if (art->GetChunkID() == artCkType) {
252                      if (!pArticulations) pArticulations = new ArticulationList;                      if (!pArticulations) pArticulations = new ArticulationList;
253                      pArticulations->push_back(new Articulation(art));                      pArticulations->push_back(new Articulation(art));
254                  }                  }
                 art = lart->GetNextSubChunk();  
255              }              }
256          }          }
257      }      }
# Line 231  namespace DLS { Line 283  namespace DLS {
283              }              }
284          }          }
285      }      }
286        
287        /** @brief Remove all RIFF chunks associated with this Articulator object.
288         *
289         * See Storage::DeleteChunks() for details.
290         */
291        void Articulator::DeleteChunks() {
292            if (pArticulations) {
293                ArticulationList::iterator iter = pArticulations->begin();
294                ArticulationList::iterator end  = pArticulations->end();
295                for (; iter != end; ++iter) {
296                    (*iter)->DeleteChunks();
297                }
298            }
299        }
300    
301      /**      /**
302       * Not yet implemented in this version, since the .gig format does       * Not yet implemented in this version, since the .gig format does
303       * not need to copy DLS articulators and so far nobody used pure       * not need to copy DLS articulators and so far nobody used pure
# Line 398  namespace DLS { Line 464  namespace DLS {
464          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
465          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
466      }      }
467        
468        /** @brief Remove all RIFF chunks associated with this Info object.
469         *
470         * At the moment Info::DeleteChunks() does nothing. It is
471         * recommended to call this method explicitly though from deriving classes's
472         * own overridden implementation of this method to avoid potential future
473         * compatiblity issues.
474         *
475         * See Storage::DeleteChunks() for details.
476         */
477        void Info::DeleteChunks() {
478        }
479    
480      /**      /**
481       * Make a deep copy of the Info object given by @a orig and assign it to       * Make a deep copy of the Info object given by @a orig and assign it to
482       * this object.       * this object.
# Line 449  namespace DLS { Line 527  namespace DLS {
527    
528          RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);          RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);
529          if (ckDLSID) {          if (ckDLSID) {
530                ckDLSID->SetPos(0);
531    
532              pDLSID = new dlsid_t;              pDLSID = new dlsid_t;
533              ckDLSID->Read(&pDLSID->ulData1, 1, 4);              ckDLSID->Read(&pDLSID->ulData1, 1, 4);
534              ckDLSID->Read(&pDLSID->usData2, 1, 2);              ckDLSID->Read(&pDLSID->usData2, 1, 2);
# Line 463  namespace DLS { Line 543  namespace DLS {
543          if (pInfo)  delete pInfo;          if (pInfo)  delete pInfo;
544      }      }
545    
546        /** @brief Remove all RIFF chunks associated with this Resource object.
547         *
548         * At the moment Resource::DeleteChunks() does nothing. It is recommended
549         * to call this method explicitly though from deriving classes's own
550         * overridden implementation of this method to avoid potential future
551         * compatiblity issues.
552         *
553         * See Storage::DeleteChunks() for details.
554         */
555        void Resource::DeleteChunks() {
556        }
557    
558      /** @brief Update chunks with current Resource data.      /** @brief Update chunks with current Resource data.
559       *       *
560       * Apply Resource data persistently below the previously given resource       * Apply Resource data persistently below the previously given resource
# Line 493  namespace DLS { Line 585  namespace DLS {
585       * Generates a new DLSID for the resource.       * Generates a new DLSID for the resource.
586       */       */
587      void Resource::GenerateDLSID() {      void Resource::GenerateDLSID() {
588  #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)          #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
   
589          if (!pDLSID) pDLSID = new dlsid_t;          if (!pDLSID) pDLSID = new dlsid_t;
590            GenerateDLSID(pDLSID);
591            #endif
592        }
593    
594        void Resource::GenerateDLSID(dlsid_t* pDLSID) {
595  #ifdef WIN32  #ifdef WIN32
   
596          UUID uuid;          UUID uuid;
597          UuidCreate(&uuid);          UuidCreate(&uuid);
598          pDLSID->ulData1 = uuid.Data1;          pDLSID->ulData1 = uuid.Data1;
# Line 522  namespace DLS { Line 616  namespace DLS {
616          pDLSID->abData[5] = uuid.byte13;          pDLSID->abData[5] = uuid.byte13;
617          pDLSID->abData[6] = uuid.byte14;          pDLSID->abData[6] = uuid.byte14;
618          pDLSID->abData[7] = uuid.byte15;          pDLSID->abData[7] = uuid.byte15;
619  #else  #elif defined(HAVE_UUID_GENERATE)
620          uuid_t uuid;          uuid_t uuid;
621          uuid_generate(uuid);          uuid_generate(uuid);
622          pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24;          pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24;
623          pDLSID->usData2 = uuid[4] | uuid[5] << 8;          pDLSID->usData2 = uuid[4] | uuid[5] << 8;
624          pDLSID->usData3 = uuid[6] | uuid[7] << 8;          pDLSID->usData3 = uuid[6] | uuid[7] << 8;
625          memcpy(pDLSID->abData, &uuid[8], 8);          memcpy(pDLSID->abData, &uuid[8], 8);
626  #endif  #else
627    # error "Missing support for uuid generation"
628  #endif  #endif
629      }      }
630            
# Line 551  namespace DLS { Line 646  namespace DLS {
646          pParentList       = ParentList;          pParentList       = ParentList;
647          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
648          if (wsmp) {          if (wsmp) {
649                wsmp->SetPos(0);
650    
651              uiHeaderSize   = wsmp->ReadUint32();              uiHeaderSize   = wsmp->ReadUint32();
652              UnityNote      = wsmp->ReadUint16();              UnityNote      = wsmp->ReadUint16();
653              FineTune       = wsmp->ReadInt16();              FineTune       = wsmp->ReadInt16();
# Line 625  namespace DLS { Line 722  namespace DLS {
722          }          }
723      }      }
724    
725        /** @brief Remove all RIFF chunks associated with this Sampler object.
726         *
727         * At the moment Sampler::DeleteChunks() does nothing. It is
728         * recommended to call this method explicitly though from deriving classes's
729         * own overridden implementation of this method to avoid potential future
730         * compatiblity issues.
731         *
732         * See Storage::DeleteChunks() for details.
733         */
734        void Sampler::DeleteChunks() {
735        }
736    
737      /**      /**
738       * Adds a new sample loop with the provided loop definition.       * Adds a new sample loop with the provided loop definition.
739       *       *
# Line 717  namespace DLS { Line 826  namespace DLS {
826          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
827          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);
828          if (pCkFormat) {          if (pCkFormat) {
829                pCkFormat->SetPos(0);
830    
831              // common fields              // common fields
832              FormatTag              = pCkFormat->ReadUint16();              FormatTag              = pCkFormat->ReadUint16();
833              Channels               = pCkFormat->ReadUint16();              Channels               = pCkFormat->ReadUint16();
# Line 747  namespace DLS { Line 858  namespace DLS {
858    
859      /** @brief Destructor.      /** @brief Destructor.
860       *       *
861       * Removes RIFF chunks associated with this Sample and frees all       * Frees all memory occupied by this sample.
      * memory occupied by this sample.  
862       */       */
863      Sample::~Sample() {      Sample::~Sample() {
864          RIFF::List* pParent = pWaveList->GetParent();          if (pCkData)
865          pParent->DeleteSubChunk(pWaveList);              pCkData->ReleaseChunkData();
866            if (pCkFormat)
867                pCkFormat->ReleaseChunkData();
868      }      }
869        
870        /** @brief Remove all RIFF chunks associated with this Sample object.
871         *
872         * See Storage::DeleteChunks() for details.
873         */
874        void Sample::DeleteChunks() {
875            // handle base class
876            Resource::DeleteChunks();
877    
878            // handle own RIFF chunks
879            if (pWaveList) {
880                RIFF::List* pParent = pWaveList->GetParent();
881                pParent->DeleteSubChunk(pWaveList);
882                pWaveList = NULL;
883            }
884        }
885    
886      /**      /**
887       * Make a deep copy of the Sample object given by @a orig (without the       * Make a deep copy of the Sample object given by @a orig (without the
888       * actual sample waveform data however) and assign it to this object.       * actual sample waveform data however) and assign it to this object.
# Line 999  namespace DLS { Line 1127  namespace DLS {
1127          // articulation information          // articulation information
1128          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
1129          if (rgnh) {          if (rgnh) {
1130                rgnh->SetPos(0);
1131    
1132              rgnh->Read(&KeyRange, 2, 2);              rgnh->Read(&KeyRange, 2, 2);
1133              rgnh->Read(&VelocityRange, 2, 2);              rgnh->Read(&VelocityRange, 2, 2);
1134              FormatOptionFlags = rgnh->ReadUint16();              FormatOptionFlags = rgnh->ReadUint16();
# Line 1021  namespace DLS { Line 1151  namespace DLS {
1151          // sample information          // sample information
1152          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
1153          if (wlnk) {          if (wlnk) {
1154                wlnk->SetPos(0);
1155    
1156              WaveLinkOptionFlags = wlnk->ReadUint16();              WaveLinkOptionFlags = wlnk->ReadUint16();
1157              PhaseGroup          = wlnk->ReadUint16();              PhaseGroup          = wlnk->ReadUint16();
1158              Channel             = wlnk->ReadUint32();              Channel             = wlnk->ReadUint32();
# Line 1039  namespace DLS { Line 1171  namespace DLS {
1171    
1172      /** @brief Destructor.      /** @brief Destructor.
1173       *       *
1174       * Removes RIFF chunks associated with this Region.       * Intended to free up all memory occupied by this Region object. ATM this
1175         * destructor implementation does nothing though.
1176       */       */
1177      Region::~Region() {      Region::~Region() {
1178          RIFF::List* pParent = pCkRegion->GetParent();      }
1179          pParent->DeleteSubChunk(pCkRegion);  
1180        /** @brief Remove all RIFF chunks associated with this Region object.
1181         *
1182         * See Storage::DeleteChunks() for details.
1183         */
1184        void Region::DeleteChunks() {
1185            // handle base classes
1186            Resource::DeleteChunks();
1187            Articulator::DeleteChunks();
1188            Sampler::DeleteChunks();
1189    
1190            // handle own RIFF chunks
1191            if (pCkRegion) {
1192                RIFF::List* pParent = pCkRegion->GetParent();
1193                pParent->DeleteSubChunk(pCkRegion);
1194                pCkRegion = NULL;
1195            }
1196      }      }
1197    
1198      Sample* Region::GetSample() {      Sample* Region::GetSample() {
1199          if (pSample) return pSample;          if (pSample) return pSample;
1200          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1201          uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1202          Sample* sample = file->GetFirstSample();          size_t i = 0;
1203          while (sample) {          for (Sample* sample = file->GetSample(i); sample;
1204                         sample = file->GetSample(++i))
1205            {
1206              if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);              if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
             sample = file->GetNextSample();  
1207          }          }
1208          return NULL;          return NULL;
1209      }      }
# Line 1225  namespace DLS { Line 1375  namespace DLS {
1375          midi_locale_t locale;          midi_locale_t locale;
1376          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1377          if (insh) {          if (insh) {
1378                insh->SetPos(0);
1379    
1380              Regions = insh->ReadUint32();              Regions = insh->ReadUint32();
1381              insh->Read(&locale, 2, 4);              insh->Read(&locale, 2, 4);
1382          } else { // 'insh' chunk missing          } else { // 'insh' chunk missing
# Line 1242  namespace DLS { Line 1394  namespace DLS {
1394          pRegions = NULL;          pRegions = NULL;
1395      }      }
1396    
1397        /**
1398         * Returns Region at supplied @a pos position within the region list of
1399         * this instrument. If supplied @a pos is out of bounds then @c NULL is
1400         * returned.
1401         *
1402         * @param pos - position of sought Region in region list
1403         * @returns pointer address to requested region or @c NULL if @a pos is
1404         *          out of bounds
1405         */
1406        Region* Instrument::GetRegionAt(size_t pos) {
1407            if (!pRegions) LoadRegions();
1408            if (!pRegions) return NULL;
1409            if (pos >= pRegions->size()) return NULL;
1410            return (*pRegions)[pos];
1411        }
1412    
1413        /**
1414         * Returns the first Region of the instrument. You have to call this
1415         * method once before you use GetNextRegion().
1416         *
1417         * @returns  pointer address to first region or NULL if there is none
1418         * @see      GetNextRegion()
1419         * @deprecated  This method is not reentrant-safe, use GetRegionAt()
1420         *              instead.
1421         */
1422      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
1423          if (!pRegions) LoadRegions();          if (!pRegions) LoadRegions();
1424          if (!pRegions) return NULL;          if (!pRegions) return NULL;
# Line 1249  namespace DLS { Line 1426  namespace DLS {
1426          return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;          return (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL;
1427      }      }
1428    
1429        /**
1430         * Returns the next Region of the instrument. You have to call
1431         * GetFirstRegion() once before you can use this method. By calling this
1432         * method multiple times it iterates through the available Regions.
1433         *
1434         * @returns  pointer address to the next region or NULL if end reached
1435         * @see      GetFirstRegion()
1436         * @deprecated  This method is not reentrant-safe, use GetRegionAt()
1437         *              instead.
1438         */
1439      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
1440          if (!pRegions) return NULL;          if (!pRegions) return NULL;
1441          RegionsIterator++;          RegionsIterator++;
# Line 1260  namespace DLS { Line 1447  namespace DLS {
1447          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1448          if (lrgn) {          if (lrgn) {
1449              uint32_t regionCkType = (lrgn->GetSubList(LIST_TYPE_RGN2)) ? LIST_TYPE_RGN2 : LIST_TYPE_RGN; // prefer regions level 2              uint32_t regionCkType = (lrgn->GetSubList(LIST_TYPE_RGN2)) ? LIST_TYPE_RGN2 : LIST_TYPE_RGN; // prefer regions level 2
1450              RIFF::List* rgn = lrgn->GetFirstSubList();              size_t i = 0;
1451              while (rgn) {              for (RIFF::List* rgn = lrgn->GetSubListAt(i); rgn;
1452                     rgn = lrgn->GetSubListAt(++i))
1453                {
1454                  if (rgn->GetListType() == regionCkType) {                  if (rgn->GetListType() == regionCkType) {
1455                      pRegions->push_back(new Region(this, rgn));                      pRegions->push_back(new Region(this, rgn));
1456                  }                  }
                 rgn = lrgn->GetNextSubList();  
1457              }              }
1458          }          }
1459      }      }
# Line 1284  namespace DLS { Line 1472  namespace DLS {
1472      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1473          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1474          lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));          lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1475            for (size_t i = 0; i < pRegions->size(); ++i) {
1476          pRegions->remove(pSrc);              if ((*pRegions)[i] == pSrc) {
1477          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);                  pRegions->erase(pRegions->begin() + i);
1478          pRegions->insert(iter, pSrc);                  RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
1479                    pRegions->insert(iter, pSrc);
1480                }
1481            }
1482      }      }
1483    
1484      void Instrument::DeleteRegion(Region* pRegion) {      void Instrument::DeleteRegion(Region* pRegion) {
# Line 1296  namespace DLS { Line 1487  namespace DLS {
1487          if (iter == pRegions->end()) return;          if (iter == pRegions->end()) return;
1488          pRegions->erase(iter);          pRegions->erase(iter);
1489          Regions = (uint32_t) pRegions->size();          Regions = (uint32_t) pRegions->size();
1490            pRegion->DeleteChunks();
1491          delete pRegion;          delete pRegion;
1492      }      }
1493    
# Line 1329  namespace DLS { Line 1521  namespace DLS {
1521          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
1522          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
1523          for (int i = 0; iter != end; ++iter, ++i) {          for (int i = 0; iter != end; ++iter, ++i) {
1524              // divide local progress into subprogress              if (pProgress) {
1525              progress_t subprogress;                  // divide local progress into subprogress
1526              __divide_progress(pProgress, &subprogress, pRegions->size(), i);                  progress_t subprogress;
1527              // do the actual work                  __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1528              (*iter)->UpdateChunks(&subprogress);                  // do the actual work
1529                    (*iter)->UpdateChunks(&subprogress);
1530                } else
1531                    (*iter)->UpdateChunks(NULL);
1532          }          }
1533          __notify_progress(pProgress, 1.0); // notify done          if (pProgress)
1534                __notify_progress(pProgress, 1.0); // notify done
1535      }      }
1536    
1537      /** @brief Destructor.      /** @brief Destructor.
1538       *       *
1539       * Removes RIFF chunks associated with this Instrument and frees all       * Frees all memory occupied by this instrument.
      * memory occupied by this instrument.  
1540       */       */
1541      Instrument::~Instrument() {      Instrument::~Instrument() {
1542          if (pRegions) {          if (pRegions) {
# Line 1353  namespace DLS { Line 1548  namespace DLS {
1548              }              }
1549              delete pRegions;              delete pRegions;
1550          }          }
         // remove instrument's chunks  
         RIFF::List* pParent = pCkInstrument->GetParent();  
         pParent->DeleteSubChunk(pCkInstrument);  
1551      }      }
1552        
1553        /** @brief Remove all RIFF chunks associated with this Instrument object.
1554         *
1555         * See Storage::DeleteChunks() for details.
1556         */
1557        void Instrument::DeleteChunks() {
1558            // handle base classes
1559            Resource::DeleteChunks();
1560            Articulator::DeleteChunks();
1561    
1562            // handle RIFF chunks of members
1563            if (pRegions) {
1564                RegionList::iterator it  = pRegions->begin();
1565                RegionList::iterator end = pRegions->end();
1566                for (; it != end; ++it)
1567                    (*it)->DeleteChunks();
1568            }
1569    
1570            // handle own RIFF chunks
1571            if (pCkInstrument) {
1572                RIFF::List* pParent = pCkInstrument->GetParent();
1573                pParent->DeleteSubChunk(pCkInstrument);
1574                pCkInstrument = NULL;
1575            }
1576        }
1577    
1578      void Instrument::CopyAssignCore(const Instrument* orig) {      void Instrument::CopyAssignCore(const Instrument* orig) {
1579          // handle base classes          // handle base classes
1580          Resource::CopyAssign(orig);          Resource::CopyAssign(orig);
# Line 1383  namespace DLS { Line 1600  namespace DLS {
1600      void Instrument::CopyAssign(const Instrument* orig) {      void Instrument::CopyAssign(const Instrument* orig) {
1601          CopyAssignCore(orig);          CopyAssignCore(orig);
1602          // delete all regions first          // delete all regions first
1603          while (Regions) DeleteRegion(GetFirstRegion());          while (Regions) DeleteRegion(GetRegionAt(0));
1604          // now recreate and copy regions          // now recreate and copy regions
1605          {          {
1606              RegionList::const_iterator it = orig->pRegions->begin();              RegionList::const_iterator it = orig->pRegions->begin();
# Line 1407  namespace DLS { Line 1624  namespace DLS {
1624       */       */
1625      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1626          pRIFF->SetByteOrder(RIFF::endian_little);          pRIFF->SetByteOrder(RIFF::endian_little);
1627            bOwningRiff = true;
1628          pVersion = new version_t;          pVersion = new version_t;
1629          pVersion->major   = 0;          pVersion->major   = 0;
1630          pVersion->minor   = 0;          pVersion->minor   = 0;
# Line 1437  namespace DLS { Line 1655  namespace DLS {
1655      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1656          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1657          this->pRIFF = pRIFF;          this->pRIFF = pRIFF;
1658            bOwningRiff = false;
1659          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1660          if (ckVersion) {          if (ckVersion) {
1661                ckVersion->SetPos(0);
1662    
1663              pVersion = new version_t;              pVersion = new version_t;
1664              ckVersion->Read(pVersion, 4, 2);              ckVersion->Read(pVersion, 4, 2);
1665          }          }
# Line 1447  namespace DLS { Line 1667  namespace DLS {
1667    
1668          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1669          if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");          if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");
1670            colh->SetPos(0);
1671          Instruments = colh->ReadUint32();          Instruments = colh->ReadUint32();
1672    
1673          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
# Line 1457  namespace DLS { Line 1678  namespace DLS {
1678              WavePoolHeaderSize = 8;              WavePoolHeaderSize = 8;
1679              b64BitWavePoolOffsets = false;              b64BitWavePoolOffsets = false;
1680          } else {          } else {
1681                ptbl->SetPos(0);
1682    
1683              WavePoolHeaderSize = ptbl->ReadUint32();              WavePoolHeaderSize = ptbl->ReadUint32();
1684              WavePoolCount  = ptbl->ReadUint32();              WavePoolCount  = ptbl->ReadUint32();
1685              pWavePoolTable = new uint32_t[WavePoolCount];              pWavePoolTable = new uint32_t[WavePoolCount];
# Line 1509  namespace DLS { Line 1732  namespace DLS {
1732          if (pVersion) delete pVersion;          if (pVersion) delete pVersion;
1733          for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)          for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1734              delete *i;              delete *i;
1735            if (bOwningRiff)
1736                delete pRIFF;
1737        }
1738    
1739        /**
1740         * Returns Sample object of @a index.
1741         *
1742         * @param index - position of sample in sample list (0..n)
1743         * @returns sample object or NULL if index is out of bounds
1744         */
1745        Sample* File::GetSample(size_t index) {
1746            if (!pSamples) LoadSamples();
1747            if (!pSamples) return NULL;
1748            if (index >= pSamples->size()) return NULL;
1749            return (*pSamples)[index];
1750      }      }
1751    
1752        /**
1753         * Returns a pointer to the first <i>Sample</i> object of the file,
1754         * <i>NULL</i> otherwise.
1755         *
1756         * @deprecated  This method is not reentrant-safe, use GetSample()
1757         *              instead.
1758         */
1759      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
1760          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples();
1761          if (!pSamples) return NULL;          if (!pSamples) return NULL;
# Line 1518  namespace DLS { Line 1763  namespace DLS {
1763          return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;          return (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL;
1764      }      }
1765    
1766        /**
1767         * Returns a pointer to the next <i>Sample</i> object of the file,
1768         * <i>NULL</i> otherwise.
1769         *
1770         * @deprecated  This method is not reentrant-safe, use GetSample()
1771         *              instead.
1772         */
1773      Sample* File::GetNextSample() {      Sample* File::GetNextSample() {
1774          if (!pSamples) return NULL;          if (!pSamples) return NULL;
1775          SamplesIterator++;          SamplesIterator++;
# Line 1528  namespace DLS { Line 1780  namespace DLS {
1780          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
1781          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1782          if (wvpl) {          if (wvpl) {
1783              file_offset_t wvplFileOffset = wvpl->GetFilePos();              file_offset_t wvplFileOffset = wvpl->GetFilePos() -
1784              RIFF::List* wave = wvpl->GetFirstSubList();                                             wvpl->GetPos(); // should be zero, but just to be sure
1785              while (wave) {              size_t i = 0;
1786                for (RIFF::List* wave = wvpl->GetSubListAt(i); wave;
1787                     wave = wvpl->GetSubListAt(++i))
1788                {
1789                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1790                      file_offset_t waveFileOffset = wave->GetFilePos();                      file_offset_t waveFileOffset = wave->GetFilePos() -
1791                                                       wave->GetPos(); // should be zero, but just to be sure
1792                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1793                  }                  }
                 wave = wvpl->GetNextSubList();  
1794              }              }
1795          }          }
1796          else { // Seen a dwpl list chunk instead of a wvpl list chunk in some file (officially not DLS compliant)          else { // Seen a dwpl list chunk instead of a wvpl list chunk in some file (officially not DLS compliant)
1797              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1798              if (dwpl) {              if (dwpl) {
1799                  file_offset_t dwplFileOffset = dwpl->GetFilePos();                  file_offset_t dwplFileOffset = dwpl->GetFilePos() -
1800                  RIFF::List* wave = dwpl->GetFirstSubList();                                                 dwpl->GetPos(); // should be zero, but just to be sure
1801                  while (wave) {                  size_t i = 0;
1802                    for (RIFF::List* wave = dwpl->GetSubListAt(i); wave;
1803                         wave = dwpl->GetSubListAt(++i))
1804                    {
1805                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
1806                          file_offset_t waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos() -
1807                                                           wave->GetPos(); // should be zero, but just to be sure
1808                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1809                      }                      }
                     wave = dwpl->GetNextSubList();  
1810                  }                  }
1811              }              }
1812          }          }
# Line 1584  namespace DLS { Line 1842  namespace DLS {
1842          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1843          if (iter == pSamples->end()) return;          if (iter == pSamples->end()) return;
1844          pSamples->erase(iter);          pSamples->erase(iter);
1845            pSample->DeleteChunks();
1846          delete pSample;          delete pSample;
1847      }      }
1848    
# Line 1604  namespace DLS { Line 1863  namespace DLS {
1863          if (!pInstruments) pInstruments = new InstrumentList;          if (!pInstruments) pInstruments = new InstrumentList;
1864          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1865          if (lstInstruments) {          if (lstInstruments) {
1866              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              size_t i = 0;
1867              while (lstInstr) {              for (RIFF::List* lstInstr = lstInstruments->GetSubListAt(i);
1868                     lstInstr; lstInstr = lstInstruments->GetSubListAt(++i))
1869                {
1870                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
1871                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr));
1872                  }                  }
                 lstInstr = lstInstruments->GetNextSubList();  
1873              }              }
1874          }          }
1875      }      }
# Line 1643  namespace DLS { Line 1903  namespace DLS {
1903          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1904          if (iter == pInstruments->end()) return;          if (iter == pInstruments->end()) return;
1905          pInstruments->erase(iter);          pInstruments->erase(iter);
1906            pInstrument->DeleteChunks();
1907          delete pInstrument;          delete pInstrument;
1908      }      }
1909    
1910      /**      /**
1911         * Returns the underlying RIFF::File used for persistency of this DLS::File
1912         * object.
1913         */
1914        RIFF::File* File::GetRiffFile() {
1915            return pRIFF;
1916        }
1917    
1918        /**
1919       * Returns extension file of given index. Extension files are used       * Returns extension file of given index. Extension files are used
1920       * sometimes to circumvent the 2 GB file size limit of the RIFF format and       * sometimes to circumvent the 2 GB file size limit of the RIFF format and
1921       * of certain operating systems in general. In this case, instead of just       * of certain operating systems in general. In this case, instead of just
# Line 1719  namespace DLS { Line 1988  namespace DLS {
1988    
1989          // update instrument's chunks          // update instrument's chunks
1990          if (pInstruments) {          if (pInstruments) {
1991              // divide local progress into subprogress              if (pProgress) {
1992              progress_t subprogress;                  // divide local progress into subprogress
1993              __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress                  progress_t subprogress;
1994                    __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1995    
             // do the actual work  
             InstrumentList::iterator iter = pInstruments->begin();  
             InstrumentList::iterator end  = pInstruments->end();  
             for (int i = 0; iter != end; ++iter, ++i) {  
                 // divide subprogress into sub-subprogress  
                 progress_t subsubprogress;  
                 __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);  
1996                  // do the actual work                  // do the actual work
1997                  (*iter)->UpdateChunks(&subsubprogress);                  InstrumentList::iterator iter = pInstruments->begin();
1998              }                  InstrumentList::iterator end  = pInstruments->end();
1999                    for (int i = 0; iter != end; ++iter, ++i) {
2000                        // divide subprogress into sub-subprogress
2001                        progress_t subsubprogress;
2002                        __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
2003                        // do the actual work
2004                        (*iter)->UpdateChunks(&subsubprogress);
2005                    }
2006    
2007              __notify_progress(&subprogress, 1.0); // notify subprogress done                  __notify_progress(&subprogress, 1.0); // notify subprogress done
2008                } else {
2009                    InstrumentList::iterator iter = pInstruments->begin();
2010                    InstrumentList::iterator end  = pInstruments->end();
2011                    for (int i = 0; iter != end; ++iter, ++i) {
2012                        (*iter)->UpdateChunks(NULL);
2013                    }
2014                }
2015          }          }
2016    
2017          // update 'ptbl' chunk          // update 'ptbl' chunk
# Line 1752  namespace DLS { Line 2029  namespace DLS {
2029    
2030          // update sample's chunks          // update sample's chunks
2031          if (pSamples) {          if (pSamples) {
2032              // divide local progress into subprogress              if (pProgress) {
2033              progress_t subprogress;                  // divide local progress into subprogress
2034              __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress                  progress_t subprogress;
2035                    __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
2036    
             // do the actual work  
             SampleList::iterator iter = pSamples->begin();  
             SampleList::iterator end  = pSamples->end();  
             for (int i = 0; iter != end; ++iter, ++i) {  
                 // divide subprogress into sub-subprogress  
                 progress_t subsubprogress;  
                 __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);  
2037                  // do the actual work                  // do the actual work
2038                  (*iter)->UpdateChunks(&subsubprogress);                  SampleList::iterator iter = pSamples->begin();
2039                    SampleList::iterator end  = pSamples->end();
2040                    for (int i = 0; iter != end; ++iter, ++i) {
2041                        // divide subprogress into sub-subprogress
2042                        progress_t subsubprogress;
2043                        __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
2044                        // do the actual work
2045                        (*iter)->UpdateChunks(&subsubprogress);
2046                    }
2047    
2048                    __notify_progress(&subprogress, 1.0); // notify subprogress done
2049                } else {
2050                    SampleList::iterator iter = pSamples->begin();
2051                    SampleList::iterator end  = pSamples->end();
2052                    for (int i = 0; iter != end; ++iter, ++i) {
2053                        (*iter)->UpdateChunks(NULL);
2054                    }
2055                }
2056            }
2057    
2058            // if there are any extension files, gather which ones are regular
2059            // extension files used as wave pool files (.gx00, .gx01, ... , .gx98)
2060            // and which one is probably a convolution (GigaPulse) file (always to
2061            // be saved as .gx99)
2062            std::list<RIFF::File*> poolFiles;  // < for (.gx00, .gx01, ... , .gx98) files
2063            RIFF::File* pGigaPulseFile = NULL; // < for .gx99 file
2064            if (!ExtensionFiles.empty()) {
2065                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2066                for (; it != ExtensionFiles.end(); ++it) {
2067                    //FIXME: the .gx99 file is always used by GSt for convolution
2068                    // data (GigaPulse); so we should better detect by subchunk
2069                    // whether the extension file is intended for convolution
2070                    // instead of checkking for a file name, because the latter does
2071                    // not work for saving new gigs created from scratch
2072                    const std::string oldName = (*it)->GetFileName();
2073                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2074                    if (isGigaPulseFile)
2075                        pGigaPulseFile = *it;
2076                    else
2077                        poolFiles.push_back(*it);
2078              }              }
2079            }
2080    
2081              __notify_progress(&subprogress, 1.0); // notify subprogress done          // update the 'xfil' chunk which describes all extension files (wave
2082            // pool files) except the .gx99 file
2083            if (!poolFiles.empty()) {
2084                const int n = poolFiles.size();
2085                const int iHeaderSize = 4;
2086                const int iEntrySize = 144;
2087    
2088                // make sure chunk exists, and with correct size
2089                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2090                if (ckXfil)
2091                    ckXfil->Resize(iHeaderSize + n * iEntrySize);
2092                else
2093                    ckXfil = pRIFF->AddSubChunk(CHUNK_ID_XFIL, iHeaderSize + n * iEntrySize);
2094    
2095                uint8_t* pData = (uint8_t*) ckXfil->LoadChunkData();
2096    
2097                // re-assemble the chunk's content
2098                store32(pData, n);
2099                std::list<RIFF::File*>::iterator itExtFile = poolFiles.begin();
2100                for (int i = 0, iOffset = 4; i < n;
2101                     ++itExtFile, ++i, iOffset += iEntrySize)
2102                {
2103                    // update the filename string and 5 byte extension of each extension file
2104                    std::string file = lastPathComponent(
2105                        (*itExtFile)->GetFileName()
2106                    );
2107                    if (file.length() + 6 > 128)
2108                        throw Exception("Fatal error, extension filename length exceeds 122 byte maximum");
2109                    uint8_t* pStrings = &pData[iOffset];
2110                    memset(pStrings, 0, 128);
2111                    memcpy(pStrings, file.c_str(), file.length());
2112                    pStrings += file.length() + 1;
2113                    std::string ext = file.substr(file.length()-5);
2114                    memcpy(pStrings, ext.c_str(), 5);
2115                    // update the dlsid of the extension file
2116                    uint8_t* pId = &pData[iOffset + 128];
2117                    dlsid_t id;
2118                    RIFF::Chunk* ckDLSID = (*itExtFile)->GetSubChunk(CHUNK_ID_DLID);
2119                    if (ckDLSID) {
2120                        ckDLSID->Read(&id.ulData1, 1, 4);
2121                        ckDLSID->Read(&id.usData2, 1, 2);
2122                        ckDLSID->Read(&id.usData3, 1, 2);
2123                        ckDLSID->Read(id.abData, 8, 1);
2124                    } else {
2125                        ckDLSID = (*itExtFile)->AddSubChunk(CHUNK_ID_DLID, 16);
2126                        Resource::GenerateDLSID(&id);
2127                        uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
2128                        store32(&pData[0], id.ulData1);
2129                        store16(&pData[4], id.usData2);
2130                        store16(&pData[6], id.usData3);
2131                        memcpy(&pData[8], id.abData, 8);
2132                    }
2133                    store32(&pId[0], id.ulData1);
2134                    store16(&pId[4], id.usData2);
2135                    store16(&pId[6], id.usData3);
2136                    memcpy(&pId[8], id.abData, 8);
2137                }
2138            } else {
2139                // in case there was a 'xfil' chunk, remove it
2140                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2141                if (ckXfil) pRIFF->DeleteSubChunk(ckXfil);
2142            }
2143    
2144            // update the 'doxf' chunk which describes a .gx99 extension file
2145            // which contains convolution data (GigaPulse)
2146            if (pGigaPulseFile) {
2147                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2148                if (!ckDoxf) ckDoxf = pRIFF->AddSubChunk(CHUNK_ID_DOXF, 148);
2149    
2150                uint8_t* pData = (uint8_t*) ckDoxf->LoadChunkData();
2151    
2152                // update the dlsid from the extension file
2153                uint8_t* pId = &pData[132];
2154                RIFF::Chunk* ckDLSID = pGigaPulseFile->GetSubChunk(CHUNK_ID_DLID);
2155                if (!ckDLSID) { //TODO: auto generate DLS ID if missing
2156                    throw Exception("Fatal error, GigaPulse file does not contain a DLS ID chunk");
2157                } else {
2158                    dlsid_t id;
2159                    // read DLS ID from extension files's DLS ID chunk
2160                    uint8_t* pData = (uint8_t*) ckDLSID->LoadChunkData();
2161                    id.ulData1 = load32(&pData[0]);
2162                    id.usData2 = load16(&pData[4]);
2163                    id.usData3 = load16(&pData[6]);
2164                    memcpy(id.abData, &pData[8], 8);
2165                    // store DLS ID to 'doxf' chunk
2166                    store32(&pId[0], id.ulData1);
2167                    store16(&pId[4], id.usData2);
2168                    store16(&pId[6], id.usData3);
2169                    memcpy(&pId[8], id.abData, 8);
2170                }
2171            } else {
2172                // in case there was a 'doxf' chunk, remove it
2173                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2174                if (ckDoxf) pRIFF->DeleteSubChunk(ckDoxf);
2175          }          }
2176    
2177          // the RIFF file to be written might now been grown >= 4GB or might          // the RIFF file to be written might now been grown >= 4GB or might
# Line 1775  namespace DLS { Line 2179  namespace DLS {
2179          // size and thus accordingly we would need to resize the wave pool          // size and thus accordingly we would need to resize the wave pool
2180          // chunk          // chunk
2181          const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();          const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
2182          const bool bRequires64Bit = (finalFileSize >> 32) != 0;          const bool bRequires64Bit = (finalFileSize >> 32) != 0 || // < native 64 bit gig file
2183                                         poolFiles.size() > 0;        // < 32 bit gig file where the hi 32 bits are used as extension file nr
2184          if (b64BitWavePoolOffsets != bRequires64Bit) {          if (b64BitWavePoolOffsets != bRequires64Bit) {
2185              b64BitWavePoolOffsets = bRequires64Bit;              b64BitWavePoolOffsets = bRequires64Bit;
2186              iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;              iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
# Line 1783  namespace DLS { Line 2188  namespace DLS {
2188              ptbl->Resize(iPtblSize);              ptbl->Resize(iPtblSize);
2189          }          }
2190    
2191          __notify_progress(pProgress, 1.0); // notify done          if (pProgress)
2192                __notify_progress(pProgress, 1.0); // notify done
2193      }      }
2194    
2195      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1801  namespace DLS { Line 2207  namespace DLS {
2207       * @param pProgress - optional: callback function for progress notification       * @param pProgress - optional: callback function for progress notification
2208       */       */
2209      void File::Save(const String& Path, progress_t* pProgress) {      void File::Save(const String& Path, progress_t* pProgress) {
2210          {          // calculate number of tasks to notify progress appropriately
2211            const size_t nExtFiles = ExtensionFiles.size();
2212            const float tasks = 2.f + nExtFiles;
2213    
2214            // save extension files (if required)
2215            if (!ExtensionFiles.empty()) {
2216                // for assembling path of extension files to be saved to
2217                const std::string baseName = pathWithoutExtension(Path);
2218                // save the individual extension files
2219                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2220                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2221                    //FIXME: the .gx99 file is always used by GSt for convolution
2222                    // data (GigaPulse); so we should better detect by subchunk
2223                    // whether the extension file is intended for convolution
2224                    // instead of checkking for a file name, because the latter does
2225                    // not work for saving new gigs created from scratch
2226                    const std::string oldName = (*it)->GetFileName();
2227                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2228                    std::string ext = (isGigaPulseFile) ? ".gx99" : strPrint(".gx%02d", i+1);
2229                    std::string newPath = baseName + ext;
2230                    // save extension file to its new location
2231                    if (pProgress) {
2232                         // divide local progress into subprogress
2233                        progress_t subprogress;
2234                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2235                        // do the actual work
2236                        (*it)->Save(newPath, &subprogress);
2237                    } else
2238                        (*it)->Save(newPath);
2239                }
2240            }
2241    
2242            if (pProgress) {
2243              // divide local progress into subprogress              // divide local progress into subprogress
2244              progress_t subprogress;              progress_t subprogress;
2245              __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress              __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2246              // do the actual work              // do the actual work
2247              UpdateChunks(&subprogress);              UpdateChunks(&subprogress);
2248                        } else
2249          }              UpdateChunks(NULL);
2250          {  
2251            if (pProgress) {
2252              // divide local progress into subprogress              // divide local progress into subprogress
2253              progress_t subprogress;              progress_t subprogress;
2254              __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress              __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2255              // do the actual work              // do the actual work
2256              pRIFF->Save(Path, &subprogress);              pRIFF->Save(Path, &subprogress);
2257          }          } else
2258                pRIFF->Save(Path);
2259    
2260          UpdateFileOffsets();          UpdateFileOffsets();
2261          __notify_progress(pProgress, 1.0); // notify done  
2262            if (pProgress)
2263                __notify_progress(pProgress, 1.0); // notify done
2264      }      }
2265    
2266      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1831  namespace DLS { Line 2274  namespace DLS {
2274       * @throws DLS::Exception  if any kind of DLS specific error occurred       * @throws DLS::Exception  if any kind of DLS specific error occurred
2275       */       */
2276      void File::Save(progress_t* pProgress) {      void File::Save(progress_t* pProgress) {
2277          {          // calculate number of tasks to notify progress appropriately
2278            const size_t nExtFiles = ExtensionFiles.size();
2279            const float tasks = 2.f + nExtFiles;
2280    
2281            // save extension files (if required)
2282            if (!ExtensionFiles.empty()) {
2283                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2284                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2285                    // save extension file
2286                    if (pProgress) {
2287                        // divide local progress into subprogress
2288                        progress_t subprogress;
2289                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2290                        // do the actual work
2291                        (*it)->Save(&subprogress);
2292                    } else
2293                        (*it)->Save();
2294                }
2295            }
2296    
2297            if (pProgress) {
2298              // divide local progress into subprogress              // divide local progress into subprogress
2299              progress_t subprogress;              progress_t subprogress;
2300              __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress              __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2301              // do the actual work              // do the actual work
2302              UpdateChunks(&subprogress);              UpdateChunks(&subprogress);
2303          }          } else
2304          {              UpdateChunks(NULL);
2305    
2306            if (pProgress) {
2307              // divide local progress into subprogress              // divide local progress into subprogress
2308              progress_t subprogress;              progress_t subprogress;
2309              __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress              __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2310              // do the actual work              // do the actual work
2311              pRIFF->Save(&subprogress);              pRIFF->Save(&subprogress);
2312          }          } else
2313                pRIFF->Save();
2314    
2315          UpdateFileOffsets();          UpdateFileOffsets();
2316          __notify_progress(pProgress, 1.0); // notify done  
2317            if (pProgress)
2318                __notify_progress(pProgress, 1.0); // notify done
2319      }      }
2320    
2321      /** @brief Updates all file offsets stored all over the file.      /** @brief Updates all file offsets stored all over the file.
# Line 1940  namespace DLS { Line 2409  namespace DLS {
2409          pWavePoolTable   = new uint32_t[WavePoolCount];          pWavePoolTable   = new uint32_t[WavePoolCount];
2410          pWavePoolTableHi = new uint32_t[WavePoolCount];          pWavePoolTableHi = new uint32_t[WavePoolCount];
2411          if (!pSamples) return;          if (!pSamples) return;
2412          // update offsets int wave pool table          // update offsets in wave pool table
2413          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2414          uint64_t wvplFileOffset = wvpl->GetFilePos();          uint64_t wvplFileOffset = wvpl->GetFilePos() -
2415          if (b64BitWavePoolOffsets) {                                    wvpl->GetPos(); // mandatory, since position might have changed
2416              SampleList::iterator iter = pSamples->begin();          if (!b64BitWavePoolOffsets) { // conventional 32 bit offsets (and no extension files) ...
             SampleList::iterator end  = pSamples->end();  
             for (int i = 0 ; iter != end ; ++iter, i++) {  
                 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());  
                 (*iter)->ullWavePoolOffset = _64BitOffset;  
                 pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);  
                 pWavePoolTable[i]   = (uint32_t) _64BitOffset;  
             }  
         } else { // conventional 32 bit offsets  
2417              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
2418              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
2419              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
2420                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());                  uint64_t _64BitOffset =
2421                        (*iter)->pWaveList->GetFilePos() -
2422                        (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2423                        wvplFileOffset -
2424                        LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2425                  (*iter)->ullWavePoolOffset = _64BitOffset;                  (*iter)->ullWavePoolOffset = _64BitOffset;
2426                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2427              }              }
2428            } else { // a) native 64 bit offsets without extension files or b) 32 bit offsets with extension files ...
2429                if (ExtensionFiles.empty()) { // native 64 bit offsets (and no extension files) [not compatible with GigaStudio] ...
2430                    SampleList::iterator iter = pSamples->begin();
2431                    SampleList::iterator end  = pSamples->end();
2432                    for (int i = 0 ; iter != end ; ++iter, i++) {
2433                        uint64_t _64BitOffset =
2434                            (*iter)->pWaveList->GetFilePos() -
2435                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2436                            wvplFileOffset -
2437                            LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2438                        (*iter)->ullWavePoolOffset = _64BitOffset;
2439                        pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
2440                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2441                    }
2442                } else { // 32 bit offsets with extension files (GigaStudio legacy support) ...
2443                    // the main gig and the extension files may contain wave data
2444                    std::vector<RIFF::File*> poolFiles;
2445                    poolFiles.push_back(pRIFF);
2446                    poolFiles.insert(poolFiles.end(), ExtensionFiles.begin(), ExtensionFiles.end());
2447    
2448                    RIFF::File* pCurPoolFile = NULL;
2449                    int fileNo = 0;
2450                    int waveOffset = 0;
2451                    SampleList::iterator iter = pSamples->begin();
2452                    SampleList::iterator end  = pSamples->end();
2453                    for (int i = 0 ; iter != end ; ++iter, i++) {
2454                        RIFF::File* pPoolFile = (*iter)->pWaveList->GetFile();
2455                        // if this sample is located in the same pool file as the
2456                        // last we reuse the previously computed fileNo and waveOffset
2457                        if (pPoolFile != pCurPoolFile) { // it is a different pool file than the last sample ...
2458                            pCurPoolFile = pPoolFile;
2459    
2460                            std::vector<RIFF::File*>::iterator sIter;
2461                            sIter = std::find(poolFiles.begin(), poolFiles.end(), pPoolFile);
2462                            if (sIter != poolFiles.end())
2463                                fileNo = std::distance(poolFiles.begin(), sIter);
2464                            else
2465                                throw DLS::Exception("Fatal error, unknown pool file");
2466    
2467                            RIFF::List* extWvpl = pCurPoolFile->GetSubList(LIST_TYPE_WVPL);
2468                            if (!extWvpl)
2469                                throw DLS::Exception("Fatal error, pool file has no 'wvpl' list chunk");
2470                            waveOffset =
2471                                extWvpl->GetFilePos() -
2472                                extWvpl->GetPos() + // mandatory, since position might have changed
2473                                LIST_HEADER_SIZE(pCurPoolFile->GetFileOffsetSize());
2474                        }
2475                        uint64_t _64BitOffset =
2476                            (*iter)->pWaveList->GetFilePos() -
2477                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2478                            waveOffset;
2479                        // pWavePoolTableHi stores file number when extension files are in use
2480                        pWavePoolTableHi[i] = (uint32_t) fileNo;
2481                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2482                        (*iter)->ullWavePoolOffset = _64BitOffset;
2483                    }
2484                }
2485          }          }
2486      }      }
2487    
2488    
   
2489  // *************** Exception ***************  // *************** Exception ***************
2490  // *  // *
2491    
2492      Exception::Exception(String Message) : RIFF::Exception(Message) {      Exception::Exception() : RIFF::Exception() {
2493        }
2494    
2495        Exception::Exception(String format, ...) : RIFF::Exception() {
2496            va_list arg;
2497            va_start(arg, format);
2498            Message = assemble(format, arg);
2499            va_end(arg);
2500        }
2501    
2502        Exception::Exception(String format, va_list arg) : RIFF::Exception() {
2503            Message = assemble(format, arg);
2504      }      }
2505    
2506      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.3053  
changed lines
  Added in v.3940

  ViewVC Help
Powered by ViewVC