/[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 2482 by schoenebeck, Mon Nov 25 02:22:38 2013 UTC revision 3941 by schoenebeck, Fri Jun 18 14:06:20 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-2013 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 144  namespace DLS { Line 148  namespace DLS {
148      /**      /**
149       * Apply articulation connections to the respective RIFF chunks. You       * Apply articulation connections to the respective RIFF chunks. You
150       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
151         *
152         * @param pProgress - callback function for progress notification
153       */       */
154      void Articulation::UpdateChunks() {      void Articulation::UpdateChunks(progress_t* pProgress) {
155          const int iEntrySize = 12; // 12 bytes per connection block          const int iEntrySize = 12; // 12 bytes per connection block
156          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
157          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
# Line 161  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 171  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 178  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 191  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 217  namespace DLS { Line 271  namespace DLS {
271      /**      /**
272       * Apply all articulations to the respective RIFF chunks. You have to       * Apply all articulations to the respective RIFF chunks. You have to
273       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
274         *
275         * @param pProgress - callback function for progress notification
276       */       */
277      void Articulator::UpdateChunks() {      void Articulator::UpdateChunks(progress_t* pProgress) {
278          if (pArticulations) {          if (pArticulations) {
279              ArticulationList::iterator iter = pArticulations->begin();              ArticulationList::iterator iter = pArticulations->begin();
280              ArticulationList::iterator end  = pArticulations->end();              ArticulationList::iterator end  = pArticulations->end();
281              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
282                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
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 336  namespace DLS { Line 406  namespace DLS {
406       *       *
407       * Apply current INFO field values to the respective INFO chunks. You       * Apply current INFO field values to the respective INFO chunks. You
408       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
409         *
410         * @param pProgress - callback function for progress notification
411       */       */
412      void Info::UpdateChunks() {      void Info::UpdateChunks(progress_t* pProgress) {
413          if (!pResourceListChunk) return;          if (!pResourceListChunk) return;
414    
415          // make sure INFO list chunk exists          // make sure INFO list chunk exists
# Line 392  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 443  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 457  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 464  namespace DLS { Line 562  namespace DLS {
562       * will not be applied at the moment (yet).       * will not be applied at the moment (yet).
563       *       *
564       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
565         *
566         * @param pProgress - callback function for progress notification
567       */       */
568      void Resource::UpdateChunks() {      void Resource::UpdateChunks(progress_t* pProgress) {
569          pInfo->UpdateChunks();          pInfo->UpdateChunks(pProgress);
570    
571          if (pDLSID) {          if (pDLSID) {
572              // make sure 'dlid' chunk exists              // make sure 'dlid' chunk exists
# Line 485  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 514  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 543  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 582  namespace DLS { Line 687  namespace DLS {
687      /**      /**
688       * Apply all sample player options to the respective RIFF chunk. You       * Apply all sample player options to the respective RIFF chunk. You
689       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
690         *
691         * @param pProgress - callback function for progress notification
692       */       */
693      void Sampler::UpdateChunks() {      void Sampler::UpdateChunks(progress_t* pProgress) {
694          // make sure 'wsmp' chunk exists          // make sure 'wsmp' chunk exists
695          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
696          int wsmpSize = uiHeaderSize + SampleLoops * 16;          int wsmpSize = uiHeaderSize + SampleLoops * 16;
# Line 615  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 701  namespace DLS { Line 820  namespace DLS {
820       * @param WavePoolOffset - offset of this sample data from wave pool       * @param WavePoolOffset - offset of this sample data from wave pool
821       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
822       */       */
823      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : Resource(pFile, waveList) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset) : Resource(pFile, waveList) {
824          pWaveList = waveList;          pWaveList = waveList;
825          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;          ullWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE(waveList->GetFile()->GetFileOffsetSize());
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 737  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 783  namespace DLS { Line 921  namespace DLS {
921          Resize(orig->GetSize());          Resize(orig->GetSize());
922          char* buf = (char*) LoadSampleData();          char* buf = (char*) LoadSampleData();
923          Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now          Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
924          const unsigned long restorePos = pOrig->pCkData->GetPos();          const file_offset_t restorePos = pOrig->pCkData->GetPos();
925          pOrig->SetPos(0);          pOrig->SetPos(0);
926          for (unsigned long todo = pOrig->GetSize(), i = 0; todo; ) {          for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
927              const int iReadAtOnce = 64*1024;              const int iReadAtOnce = 64*1024;
928              unsigned long n = (iReadAtOnce < todo) ? iReadAtOnce : todo;              file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
929              n = pOrig->Read(&buf[i], n);              n = pOrig->Read(&buf[i], n);
930              if (!n) break;              if (!n) break;
931              todo -= n;              todo -= n;
# Line 845  namespace DLS { Line 983  namespace DLS {
983       * @returns number of sample points or 0 if FormatTag != DLS_WAVE_FORMAT_PCM       * @returns number of sample points or 0 if FormatTag != DLS_WAVE_FORMAT_PCM
984       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
985       */       */
986      unsigned long Sample::GetSize() const {      file_offset_t Sample::GetSize() const {
987          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
988          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
989      }      }
# Line 872  namespace DLS { Line 1010  namespace DLS {
1010       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
1011       * other formats will fail!       * other formats will fail!
1012       *       *
1013       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
1014       *                   greater than zero)       *                  greater than zero)
1015       * @throws Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM
1016       * @throws Exception if \a iNewSize is less than 1       * @throws Exception if \a NewSize is less than 1 or unrealistic large
1017       * @see File::Save(), FrameSize, FormatTag       * @see File::Save(), FrameSize, FormatTag
1018       */       */
1019      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
1020          if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");          if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");
1021          if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");          if (NewSize < 1) throw Exception("Sample size must be at least one sample point");
1022          const int iSizeInBytes = iNewSize * FrameSize;          if ((NewSize >> 48) != 0)
1023                throw Exception("Unrealistic high DLS sample size detected");
1024            const file_offset_t sizeInBytes = NewSize * FrameSize;
1025          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
1026          if (pCkData) pCkData->Resize(iSizeInBytes);          if (pCkData) pCkData->Resize(sizeInBytes);
1027          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, sizeInBytes);
1028      }      }
1029    
1030      /**      /**
# Line 903  namespace DLS { Line 1043  namespace DLS {
1043       * @throws Exception if no data RIFF chunk was created for the sample yet       * @throws Exception if no data RIFF chunk was created for the sample yet
1044       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
1045       */       */
1046      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
1047          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
1048          if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");          if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
1049          unsigned long orderedBytes = SampleCount * FrameSize;          file_offset_t orderedBytes = SampleCount * FrameSize;
1050          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
1051          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
1052                                          : result / FrameSize;                                          : result / FrameSize;
1053      }      }
# Line 921  namespace DLS { Line 1061  namespace DLS {
1061       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1062       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1063       */       */
1064      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
1065          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
1066          return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?          return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
1067      }      }
# Line 941  namespace DLS { Line 1081  namespace DLS {
1081       * @throws Exception if current sample size is too small       * @throws Exception if current sample size is too small
1082       * @see LoadSampleData()       * @see LoadSampleData()
1083       */       */
1084      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1085          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
1086          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1087          return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?          return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
# Line 951  namespace DLS { Line 1091  namespace DLS {
1091       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
1092       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
1093       *       *
1094         * @param pProgress - callback function for progress notification
1095       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
1096       *                   was provided yet       *                   was provided yet
1097       */       */
1098      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
1099          if (FormatTag != DLS_WAVE_FORMAT_PCM)          if (FormatTag != DLS_WAVE_FORMAT_PCM)
1100              throw Exception("Could not save sample, only PCM format is supported");              throw Exception("Could not save sample, only PCM format is supported");
1101          // we refuse to do anything if not sample wave form was provided yet          // we refuse to do anything if not sample wave form was provided yet
1102          if (!pCkData)          if (!pCkData)
1103              throw Exception("Could not save sample, there is no sample data to save");              throw Exception("Could not save sample, there is no sample data to save");
1104          // update chunks of base class as well          // update chunks of base class as well
1105          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1106          // make sure 'fmt' chunk exists          // make sure 'fmt' chunk exists
1107          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
1108          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
# Line 983  namespace DLS { Line 1124  namespace DLS {
1124      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {
1125          pCkRegion = rgnList;          pCkRegion = rgnList;
1126    
1127          // articulation informations          // 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 1005  namespace DLS { Line 1148  namespace DLS {
1148          }          }
1149          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
1150    
1151          // sample informations          // 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 1026  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          unsigned long 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              if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);                       sample = file->GetSample(++i))
1205              sample = file->GetNextSample();          {
1206                if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1207          }          }
1208          return NULL;          return NULL;
1209      }      }
# Line 1094  namespace DLS { Line 1257  namespace DLS {
1257       * Apply Region settings to the respective RIFF chunks. You have to       * Apply Region settings to the respective RIFF chunks. You have to
1258       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
1259       *       *
1260         * @param pProgress - callback function for progress notification
1261       * @throws Exception - if the Region's sample could not be found       * @throws Exception - if the Region's sample could not be found
1262       */       */
1263      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
1264          // make sure 'rgnh' chunk exists          // make sure 'rgnh' chunk exists
1265          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1266          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
# Line 1115  namespace DLS { Line 1279  namespace DLS {
1279    
1280          // update chunks of base classes as well (but skip Resource,          // update chunks of base classes as well (but skip Resource,
1281          // as a rgn doesn't seem to have dlid and INFO chunks)          // as a rgn doesn't seem to have dlid and INFO chunks)
1282          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1283          Sampler::UpdateChunks();          Sampler::UpdateChunks(pProgress);
1284    
1285          // make sure 'wlnk' chunk exists          // make sure 'wlnk' chunk exists
1286          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
# Line 1211  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 1228  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 1235  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 1246  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 1263  namespace DLS { Line 1465  namespace DLS {
1465          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1466          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
1467          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
1468          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1469          return pNewRegion;          return pNewRegion;
1470      }      }
1471    
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, 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 1281  namespace DLS { Line 1486  namespace DLS {
1486          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1487          if (iter == pRegions->end()) return;          if (iter == pRegions->end()) return;
1488          pRegions->erase(iter);          pRegions->erase(iter);
1489          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1490            pRegion->DeleteChunks();
1491          delete pRegion;          delete pRegion;
1492      }      }
1493    
# Line 1289  namespace DLS { Line 1495  namespace DLS {
1495       * Apply Instrument with all its Regions to the respective RIFF chunks.       * Apply Instrument with all its Regions to the respective RIFF chunks.
1496       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
1497       *       *
1498         * @param pProgress - callback function for progress notification
1499       * @throws Exception - on errors       * @throws Exception - on errors
1500       */       */
1501      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
1502          // first update base classes' chunks          // first update base classes' chunks
1503          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1504          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1505          // make sure 'insh' chunk exists          // make sure 'insh' chunk exists
1506          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1507          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1508          uint8_t* pData = (uint8_t*) insh->LoadChunkData();          uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1509          // update 'insh' chunk          // update 'insh' chunk
1510          Regions = (pRegions) ? pRegions->size() : 0;          Regions = (pRegions) ? uint32_t(pRegions->size()) : 0;
1511          midi_locale_t locale;          midi_locale_t locale;
1512          locale.instrument = MIDIProgram;          locale.instrument = MIDIProgram;
1513          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
# Line 1313  namespace DLS { Line 1520  namespace DLS {
1520          if (!pRegions) return;          if (!pRegions) return;
1521          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
1522          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
1523          for (; iter != end; ++iter) {          for (int i = 0; iter != end; ++iter, ++i) {
1524              (*iter)->UpdateChunks();              if (pProgress) {
1525                    // divide local progress into subprogress
1526                    progress_t subprogress;
1527                    __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1528                    // do the actual work
1529                    (*iter)->UpdateChunks(&subprogress);
1530                } else
1531                    (*iter)->UpdateChunks(NULL);
1532          }          }
1533            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 1333  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 1363  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 1387  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 1417  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 1427  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 1437  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 1449  namespace DLS { Line 1692  namespace DLS {
1692                  for (int i = 0 ; i < WavePoolCount ; i++) {                  for (int i = 0 ; i < WavePoolCount ; i++) {
1693                      pWavePoolTableHi[i] = ptbl->ReadUint32();                      pWavePoolTableHi[i] = ptbl->ReadUint32();
1694                      pWavePoolTable[i] = ptbl->ReadUint32();                      pWavePoolTable[i] = ptbl->ReadUint32();
1695                      if (pWavePoolTable[i] & 0x80000000)                      //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1696                          throw DLS::Exception("Files larger than 2 GB not yet supported");                      //if (pWavePoolTable[i] & 0x80000000)
1697                        //    throw DLS::Exception("Files larger than 2 GB not yet supported");
1698                  }                  }
1699              } else { // conventional 32 bit offsets              } else { // conventional 32 bit offsets
1700                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
# Line 1488  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 1497  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 1507  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              unsigned long 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                      unsigned long 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                  unsigned long 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                          unsigned long 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 1563  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    
1849        /**
1850         * Returns the instrument with the given @a index from the list of
1851         * instruments of this file.
1852         *
1853         * @param index - number of the sought instrument (0..n)
1854         * @returns  sought instrument or NULL if there's no such instrument
1855         */
1856        Instrument* File::GetInstrument(size_t index) {
1857            if (!pInstruments) LoadInstruments();
1858            if (!pInstruments) return NULL;
1859            if (index >= pInstruments->size()) return NULL;
1860            return (*pInstruments)[index];
1861        }
1862    
1863        /**
1864         * Returns a pointer to the first <i>Instrument</i> object of the file,
1865         * <i>NULL</i> otherwise.
1866         *
1867         * @deprecated  This method is not reentrant-safe, use GetInstrument()
1868         *              instead.
1869         */
1870      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
1871          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
1872          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
# Line 1573  namespace DLS { Line 1874  namespace DLS {
1874          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;
1875      }      }
1876    
1877        /**
1878         * Returns a pointer to the next <i>Instrument</i> object of the file,
1879         * <i>NULL</i> otherwise.
1880         *
1881         * @deprecated  This method is not reentrant-safe, use GetInstrument()
1882         *              instead.
1883         */
1884      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
1885          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
1886          InstrumentsIterator++;          InstrumentsIterator++;
# Line 1583  namespace DLS { Line 1891  namespace DLS {
1891          if (!pInstruments) pInstruments = new InstrumentList;          if (!pInstruments) pInstruments = new InstrumentList;
1892          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1893          if (lstInstruments) {          if (lstInstruments) {
1894              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              size_t i = 0;
1895              while (lstInstr) {              for (RIFF::List* lstInstr = lstInstruments->GetSubListAt(i);
1896                     lstInstr; lstInstr = lstInstruments->GetSubListAt(++i))
1897                {
1898                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
1899                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr));
1900                  }                  }
                 lstInstr = lstInstruments->GetNextSubList();  
1901              }              }
1902          }          }
1903      }      }
# Line 1622  namespace DLS { Line 1931  namespace DLS {
1931          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1932          if (iter == pInstruments->end()) return;          if (iter == pInstruments->end()) return;
1933          pInstruments->erase(iter);          pInstruments->erase(iter);
1934            pInstrument->DeleteChunks();
1935          delete pInstrument;          delete pInstrument;
1936      }      }
1937    
1938      /**      /**
1939         * Returns the underlying RIFF::File used for persistency of this DLS::File
1940         * object.
1941         */
1942        RIFF::File* File::GetRiffFile() {
1943            return pRIFF;
1944        }
1945    
1946        /**
1947       * Returns extension file of given index. Extension files are used       * Returns extension file of given index. Extension files are used
1948       * 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
1949       * 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 1671  namespace DLS { Line 1989  namespace DLS {
1989       * the respective RIFF chunks. You have to call Save() to make changes       * the respective RIFF chunks. You have to call Save() to make changes
1990       * persistent.       * persistent.
1991       *       *
1992         * @param pProgress - callback function for progress notification
1993       * @throws Exception - on errors       * @throws Exception - on errors
1994       */       */
1995      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
1996          // first update base class's chunks          // first update base class's chunks
1997          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1998    
1999          // if version struct exists, update 'vers' chunk          // if version struct exists, update 'vers' chunk
2000          if (pVersion) {          if (pVersion) {
# Line 1689  namespace DLS { Line 2008  namespace DLS {
2008          }          }
2009    
2010          // update 'colh' chunk          // update 'colh' chunk
2011          Instruments = (pInstruments) ? pInstruments->size() : 0;          Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
2012          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
2013          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
2014          uint8_t* pData = (uint8_t*) colh->LoadChunkData();          uint8_t* pData = (uint8_t*) colh->LoadChunkData();
# Line 1697  namespace DLS { Line 2016  namespace DLS {
2016    
2017          // update instrument's chunks          // update instrument's chunks
2018          if (pInstruments) {          if (pInstruments) {
2019              InstrumentList::iterator iter = pInstruments->begin();              if (pProgress) {
2020              InstrumentList::iterator end  = pInstruments->end();                  // divide local progress into subprogress
2021              for (; iter != end; ++iter) {                  progress_t subprogress;
2022                  (*iter)->UpdateChunks();                  __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
2023    
2024                    // do the actual work
2025                    InstrumentList::iterator iter = pInstruments->begin();
2026                    InstrumentList::iterator end  = pInstruments->end();
2027                    for (int i = 0; iter != end; ++iter, ++i) {
2028                        // divide subprogress into sub-subprogress
2029                        progress_t subsubprogress;
2030                        __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
2031                        // do the actual work
2032                        (*iter)->UpdateChunks(&subsubprogress);
2033                    }
2034    
2035                    __notify_progress(&subprogress, 1.0); // notify subprogress done
2036                } else {
2037                    InstrumentList::iterator iter = pInstruments->begin();
2038                    InstrumentList::iterator end  = pInstruments->end();
2039                    for (int i = 0; iter != end; ++iter, ++i) {
2040                        (*iter)->UpdateChunks(NULL);
2041                    }
2042              }              }
2043          }          }
2044    
2045          // update 'ptbl' chunk          // update 'ptbl' chunk
2046          const int iSamples = (pSamples) ? pSamples->size() : 0;          const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
2047          const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2048          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2049          if (!ptbl)   ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);          if (!ptbl)   ptbl = pRIFF->AddSubChunk(CHUNK_ID_PTBL, 1 /*anything, we'll resize*/);
2050          const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;          int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2051          ptbl->Resize(iPtblSize);          ptbl->Resize(iPtblSize);
2052          pData = (uint8_t*) ptbl->LoadChunkData();          pData = (uint8_t*) ptbl->LoadChunkData();
2053          WavePoolCount = iSamples;          WavePoolCount = iSamples;
# Line 1719  namespace DLS { Line 2057  namespace DLS {
2057    
2058          // update sample's chunks          // update sample's chunks
2059          if (pSamples) {          if (pSamples) {
2060              SampleList::iterator iter = pSamples->begin();              if (pProgress) {
2061              SampleList::iterator end  = pSamples->end();                  // divide local progress into subprogress
2062              for (; iter != end; ++iter) {                  progress_t subprogress;
2063                  (*iter)->UpdateChunks();                  __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
2064    
2065                    // do the actual work
2066                    SampleList::iterator iter = pSamples->begin();
2067                    SampleList::iterator end  = pSamples->end();
2068                    for (int i = 0; iter != end; ++iter, ++i) {
2069                        // divide subprogress into sub-subprogress
2070                        progress_t subsubprogress;
2071                        __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
2072                        // do the actual work
2073                        (*iter)->UpdateChunks(&subsubprogress);
2074                    }
2075    
2076                    __notify_progress(&subprogress, 1.0); // notify subprogress done
2077                } else {
2078                    SampleList::iterator iter = pSamples->begin();
2079                    SampleList::iterator end  = pSamples->end();
2080                    for (int i = 0; iter != end; ++iter, ++i) {
2081                        (*iter)->UpdateChunks(NULL);
2082                    }
2083                }
2084            }
2085    
2086            // if there are any extension files, gather which ones are regular
2087            // extension files used as wave pool files (.gx00, .gx01, ... , .gx98)
2088            // and which one is probably a convolution (GigaPulse) file (always to
2089            // be saved as .gx99)
2090            std::list<RIFF::File*> poolFiles;  // < for (.gx00, .gx01, ... , .gx98) files
2091            RIFF::File* pGigaPulseFile = NULL; // < for .gx99 file
2092            if (!ExtensionFiles.empty()) {
2093                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2094                for (; it != ExtensionFiles.end(); ++it) {
2095                    //FIXME: the .gx99 file is always used by GSt for convolution
2096                    // data (GigaPulse); so we should better detect by subchunk
2097                    // whether the extension file is intended for convolution
2098                    // instead of checkking for a file name, because the latter does
2099                    // not work for saving new gigs created from scratch
2100                    const std::string oldName = (*it)->GetFileName();
2101                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2102                    if (isGigaPulseFile)
2103                        pGigaPulseFile = *it;
2104                    else
2105                        poolFiles.push_back(*it);
2106                }
2107            }
2108    
2109            // update the 'xfil' chunk which describes all extension files (wave
2110            // pool files) except the .gx99 file
2111            if (!poolFiles.empty()) {
2112                const int n = poolFiles.size();
2113                const int iHeaderSize = 4;
2114                const int iEntrySize = 144;
2115    
2116                // make sure chunk exists, and with correct size
2117                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2118                if (ckXfil)
2119                    ckXfil->Resize(iHeaderSize + n * iEntrySize);
2120                else
2121                    ckXfil = pRIFF->AddSubChunk(CHUNK_ID_XFIL, iHeaderSize + n * iEntrySize);
2122    
2123                uint8_t* pData = (uint8_t*) ckXfil->LoadChunkData();
2124    
2125                // re-assemble the chunk's content
2126                store32(pData, n);
2127                std::list<RIFF::File*>::iterator itExtFile = poolFiles.begin();
2128                for (int i = 0, iOffset = 4; i < n;
2129                     ++itExtFile, ++i, iOffset += iEntrySize)
2130                {
2131                    // update the filename string and 5 byte extension of each extension file
2132                    std::string file = lastPathComponent(
2133                        (*itExtFile)->GetFileName()
2134                    );
2135                    if (file.length() + 6 > 128)
2136                        throw Exception("Fatal error, extension filename length exceeds 122 byte maximum");
2137                    uint8_t* pStrings = &pData[iOffset];
2138                    memset(pStrings, 0, 128);
2139                    memcpy(pStrings, file.c_str(), file.length());
2140                    pStrings += file.length() + 1;
2141                    std::string ext = file.substr(file.length()-5);
2142                    memcpy(pStrings, ext.c_str(), 5);
2143                    // update the dlsid of the extension file
2144                    uint8_t* pId = &pData[iOffset + 128];
2145                    dlsid_t id;
2146                    RIFF::Chunk* ckDLSID = (*itExtFile)->GetSubChunk(CHUNK_ID_DLID);
2147                    if (ckDLSID) {
2148                        ckDLSID->Read(&id.ulData1, 1, 4);
2149                        ckDLSID->Read(&id.usData2, 1, 2);
2150                        ckDLSID->Read(&id.usData3, 1, 2);
2151                        ckDLSID->Read(id.abData, 8, 1);
2152                    } else {
2153                        ckDLSID = (*itExtFile)->AddSubChunk(CHUNK_ID_DLID, 16);
2154                        Resource::GenerateDLSID(&id);
2155                        uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
2156                        store32(&pData[0], id.ulData1);
2157                        store16(&pData[4], id.usData2);
2158                        store16(&pData[6], id.usData3);
2159                        memcpy(&pData[8], id.abData, 8);
2160                    }
2161                    store32(&pId[0], id.ulData1);
2162                    store16(&pId[4], id.usData2);
2163                    store16(&pId[6], id.usData3);
2164                    memcpy(&pId[8], id.abData, 8);
2165                }
2166            } else {
2167                // in case there was a 'xfil' chunk, remove it
2168                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2169                if (ckXfil) pRIFF->DeleteSubChunk(ckXfil);
2170            }
2171    
2172            // update the 'doxf' chunk which describes a .gx99 extension file
2173            // which contains convolution data (GigaPulse)
2174            if (pGigaPulseFile) {
2175                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2176                if (!ckDoxf) ckDoxf = pRIFF->AddSubChunk(CHUNK_ID_DOXF, 148);
2177    
2178                uint8_t* pData = (uint8_t*) ckDoxf->LoadChunkData();
2179    
2180                // update the dlsid from the extension file
2181                uint8_t* pId = &pData[132];
2182                RIFF::Chunk* ckDLSID = pGigaPulseFile->GetSubChunk(CHUNK_ID_DLID);
2183                if (!ckDLSID) { //TODO: auto generate DLS ID if missing
2184                    throw Exception("Fatal error, GigaPulse file does not contain a DLS ID chunk");
2185                } else {
2186                    dlsid_t id;
2187                    // read DLS ID from extension files's DLS ID chunk
2188                    uint8_t* pData = (uint8_t*) ckDLSID->LoadChunkData();
2189                    id.ulData1 = load32(&pData[0]);
2190                    id.usData2 = load16(&pData[4]);
2191                    id.usData3 = load16(&pData[6]);
2192                    memcpy(id.abData, &pData[8], 8);
2193                    // store DLS ID to 'doxf' chunk
2194                    store32(&pId[0], id.ulData1);
2195                    store16(&pId[4], id.usData2);
2196                    store16(&pId[6], id.usData3);
2197                    memcpy(&pId[8], id.abData, 8);
2198              }              }
2199            } else {
2200                // in case there was a 'doxf' chunk, remove it
2201                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2202                if (ckDoxf) pRIFF->DeleteSubChunk(ckDoxf);
2203            }
2204    
2205            // the RIFF file to be written might now been grown >= 4GB or might
2206            // been shrunk < 4GB, so we might need to update the wave pool offset
2207            // size and thus accordingly we would need to resize the wave pool
2208            // chunk
2209            const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
2210            const bool bRequires64Bit = (finalFileSize >> 32) != 0 || // < native 64 bit gig file
2211                                         poolFiles.size() > 0;        // < 32 bit gig file where the hi 32 bits are used as extension file nr
2212            if (b64BitWavePoolOffsets != bRequires64Bit) {
2213                b64BitWavePoolOffsets = bRequires64Bit;
2214                iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2215                iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2216                ptbl->Resize(iPtblSize);
2217          }          }
2218    
2219            if (pProgress)
2220                __notify_progress(pProgress, 1.0); // notify done
2221      }      }
2222    
2223      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1739  namespace DLS { Line 2232  namespace DLS {
2232       * the new file (given by \a Path) afterwards.       * the new file (given by \a Path) afterwards.
2233       *       *
2234       * @param Path - path and file name where everything should be written to       * @param Path - path and file name where everything should be written to
2235         * @param pProgress - optional: callback function for progress notification
2236       */       */
2237      void File::Save(const String& Path) {      void File::Save(const String& Path, progress_t* pProgress) {
2238          UpdateChunks();          // calculate number of tasks to notify progress appropriately
2239          pRIFF->Save(Path);          const size_t nExtFiles = ExtensionFiles.size();
2240          __UpdateWavePoolTableChunk();          const float tasks = 2.f + nExtFiles;
2241    
2242            // save extension files (if required)
2243            if (!ExtensionFiles.empty()) {
2244                // for assembling path of extension files to be saved to
2245                const std::string baseName = pathWithoutExtension(Path);
2246                // save the individual extension files
2247                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2248                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2249                    //FIXME: the .gx99 file is always used by GSt for convolution
2250                    // data (GigaPulse); so we should better detect by subchunk
2251                    // whether the extension file is intended for convolution
2252                    // instead of checkking for a file name, because the latter does
2253                    // not work for saving new gigs created from scratch
2254                    const std::string oldName = (*it)->GetFileName();
2255                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2256                    std::string ext = (isGigaPulseFile) ? ".gx99" : strPrint(".gx%02d", i+1);
2257                    std::string newPath = baseName + ext;
2258                    // save extension file to its new location
2259                    if (pProgress) {
2260                         // divide local progress into subprogress
2261                        progress_t subprogress;
2262                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2263                        // do the actual work
2264                        (*it)->Save(newPath, &subprogress);
2265                    } else
2266                        (*it)->Save(newPath);
2267                }
2268            }
2269    
2270            if (pProgress) {
2271                // divide local progress into subprogress
2272                progress_t subprogress;
2273                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2274                // do the actual work
2275                UpdateChunks(&subprogress);
2276            } else
2277                UpdateChunks(NULL);
2278    
2279            if (pProgress) {
2280                // divide local progress into subprogress
2281                progress_t subprogress;
2282                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2283                // do the actual work
2284                pRIFF->Save(Path, &subprogress);
2285            } else
2286                pRIFF->Save(Path);
2287    
2288            UpdateFileOffsets();
2289    
2290            if (pProgress)
2291                __notify_progress(pProgress, 1.0); // notify done
2292      }      }
2293    
2294      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1752  namespace DLS { Line 2297  namespace DLS {
2297       * file. The file might temporarily grow to a higher size than it will       * file. The file might temporarily grow to a higher size than it will
2298       * have at the end of the saving process.       * have at the end of the saving process.
2299       *       *
2300       * @throws RIFF::Exception if any kind of IO error occured       * @param pProgress - optional: callback function for progress notification
2301       * @throws DLS::Exception  if any kind of DLS specific error occured       * @throws RIFF::Exception if any kind of IO error occurred
2302         * @throws DLS::Exception  if any kind of DLS specific error occurred
2303         */
2304        void File::Save(progress_t* pProgress) {
2305            // calculate number of tasks to notify progress appropriately
2306            const size_t nExtFiles = ExtensionFiles.size();
2307            const float tasks = 2.f + nExtFiles;
2308    
2309            // save extension files (if required)
2310            if (!ExtensionFiles.empty()) {
2311                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2312                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2313                    // save extension file
2314                    if (pProgress) {
2315                        // divide local progress into subprogress
2316                        progress_t subprogress;
2317                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2318                        // do the actual work
2319                        (*it)->Save(&subprogress);
2320                    } else
2321                        (*it)->Save();
2322                }
2323            }
2324    
2325            if (pProgress) {
2326                // divide local progress into subprogress
2327                progress_t subprogress;
2328                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2329                // do the actual work
2330                UpdateChunks(&subprogress);
2331            } else
2332                UpdateChunks(NULL);
2333    
2334            if (pProgress) {
2335                // divide local progress into subprogress
2336                progress_t subprogress;
2337                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2338                // do the actual work
2339                pRIFF->Save(&subprogress);
2340            } else
2341                pRIFF->Save();
2342    
2343            UpdateFileOffsets();
2344    
2345            if (pProgress)
2346                __notify_progress(pProgress, 1.0); // notify done
2347        }
2348    
2349        /** @brief Updates all file offsets stored all over the file.
2350         *
2351         * This virtual method is called whenever the overall file layout has been
2352         * changed (i.e. file or individual RIFF chunks have been resized). It is
2353         * then the responsibility of this method to update all file offsets stored
2354         * in the file format. For example samples are referenced by instruments by
2355         * file offsets. The gig format also stores references to instrument
2356         * scripts as file offsets, and thus it overrides this method to update
2357         * those file offsets as well.
2358       */       */
2359      void File::Save() {      void File::UpdateFileOffsets() {
         UpdateChunks();  
         pRIFF->Save();  
2360          __UpdateWavePoolTableChunk();          __UpdateWavePoolTableChunk();
2361      }      }
2362    
# Line 1795  namespace DLS { Line 2394  namespace DLS {
2394          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2395          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2396          // check if 'ptbl' chunk is large enough          // check if 'ptbl' chunk is large enough
2397          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2398          const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;          const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
2399          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
2400          // save the 'ptbl' chunk's current read/write position          // save the 'ptbl' chunk's current read/write position
2401          unsigned long ulOriginalPos = ptbl->GetPos();          file_offset_t ullOriginalPos = ptbl->GetPos();
2402          // update headers          // update headers
2403          ptbl->SetPos(0);          ptbl->SetPos(0);
2404          uint32_t tmp = WavePoolHeaderSize;          uint32_t tmp = WavePoolHeaderSize;
# Line 1822  namespace DLS { Line 2421  namespace DLS {
2421              }              }
2422          }          }
2423          // restore 'ptbl' chunk's original read/write position          // restore 'ptbl' chunk's original read/write position
2424          ptbl->SetPos(ulOriginalPos);          ptbl->SetPos(ullOriginalPos);
2425      }      }
2426    
2427      /**      /**
# Line 1831  namespace DLS { Line 2430  namespace DLS {
2430       * exists already.       * exists already.
2431       */       */
2432      void File::__UpdateWavePoolTable() {      void File::__UpdateWavePoolTable() {
2433          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2434          // resize wave pool table arrays          // resize wave pool table arrays
2435          if (pWavePoolTable)   delete[] pWavePoolTable;          if (pWavePoolTable)   delete[] pWavePoolTable;
2436          if (pWavePoolTableHi) delete[] pWavePoolTableHi;          if (pWavePoolTableHi) delete[] pWavePoolTableHi;
2437          pWavePoolTable   = new uint32_t[WavePoolCount];          pWavePoolTable   = new uint32_t[WavePoolCount];
2438          pWavePoolTableHi = new uint32_t[WavePoolCount];          pWavePoolTableHi = new uint32_t[WavePoolCount];
2439          if (!pSamples) return;          if (!pSamples) return;
2440          // update offsets int wave pool table          // update offsets in wave pool table
2441          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2442          uint64_t wvplFileOffset = wvpl->GetFilePos();          uint64_t wvplFileOffset = wvpl->GetFilePos() -
2443          if (b64BitWavePoolOffsets) {                                    wvpl->GetPos(); // mandatory, since position might have changed
2444            if (!b64BitWavePoolOffsets) { // conventional 32 bit offsets (and no extension files) ...
2445              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
2446              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
2447              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
2448                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset =
2449                  (*iter)->ulWavePoolOffset = _64BitOffset;                      (*iter)->pWaveList->GetFilePos() -
2450                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);                      (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2451                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;                      wvplFileOffset -
2452              }                      LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2453          } else { // conventional 32 bit offsets                  (*iter)->ullWavePoolOffset = _64BitOffset;
             SampleList::iterator iter = pSamples->begin();  
             SampleList::iterator end  = pSamples->end();  
             for (int i = 0 ; iter != end ; ++iter, i++) {  
                 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;  
                 (*iter)->ulWavePoolOffset = _64BitOffset;  
2454                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2455              }              }
2456            } else { // a) native 64 bit offsets without extension files or b) 32 bit offsets with extension files ...
2457                if (ExtensionFiles.empty()) { // native 64 bit offsets (and no extension files) [not compatible with GigaStudio] ...
2458                    SampleList::iterator iter = pSamples->begin();
2459                    SampleList::iterator end  = pSamples->end();
2460                    for (int i = 0 ; iter != end ; ++iter, i++) {
2461                        uint64_t _64BitOffset =
2462                            (*iter)->pWaveList->GetFilePos() -
2463                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2464                            wvplFileOffset -
2465                            LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2466                        (*iter)->ullWavePoolOffset = _64BitOffset;
2467                        pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
2468                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2469                    }
2470                } else { // 32 bit offsets with extension files (GigaStudio legacy support) ...
2471                    // the main gig and the extension files may contain wave data
2472                    std::vector<RIFF::File*> poolFiles;
2473                    poolFiles.push_back(pRIFF);
2474                    poolFiles.insert(poolFiles.end(), ExtensionFiles.begin(), ExtensionFiles.end());
2475    
2476                    RIFF::File* pCurPoolFile = NULL;
2477                    int fileNo = 0;
2478                    int waveOffset = 0;
2479                    SampleList::iterator iter = pSamples->begin();
2480                    SampleList::iterator end  = pSamples->end();
2481                    for (int i = 0 ; iter != end ; ++iter, i++) {
2482                        RIFF::File* pPoolFile = (*iter)->pWaveList->GetFile();
2483                        // if this sample is located in the same pool file as the
2484                        // last we reuse the previously computed fileNo and waveOffset
2485                        if (pPoolFile != pCurPoolFile) { // it is a different pool file than the last sample ...
2486                            pCurPoolFile = pPoolFile;
2487    
2488                            std::vector<RIFF::File*>::iterator sIter;
2489                            sIter = std::find(poolFiles.begin(), poolFiles.end(), pPoolFile);
2490                            if (sIter != poolFiles.end())
2491                                fileNo = std::distance(poolFiles.begin(), sIter);
2492                            else
2493                                throw DLS::Exception("Fatal error, unknown pool file");
2494    
2495                            RIFF::List* extWvpl = pCurPoolFile->GetSubList(LIST_TYPE_WVPL);
2496                            if (!extWvpl)
2497                                throw DLS::Exception("Fatal error, pool file has no 'wvpl' list chunk");
2498                            waveOffset =
2499                                extWvpl->GetFilePos() -
2500                                extWvpl->GetPos() + // mandatory, since position might have changed
2501                                LIST_HEADER_SIZE(pCurPoolFile->GetFileOffsetSize());
2502                        }
2503                        uint64_t _64BitOffset =
2504                            (*iter)->pWaveList->GetFilePos() -
2505                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2506                            waveOffset;
2507                        // pWavePoolTableHi stores file number when extension files are in use
2508                        pWavePoolTableHi[i] = (uint32_t) fileNo;
2509                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2510                        (*iter)->ullWavePoolOffset = _64BitOffset;
2511                    }
2512                }
2513          }          }
2514      }      }
2515    
2516    
   
2517  // *************** Exception ***************  // *************** Exception ***************
2518  // *  // *
2519    
2520      Exception::Exception(String Message) : RIFF::Exception(Message) {      Exception::Exception() : RIFF::Exception() {
2521        }
2522    
2523        Exception::Exception(String format, ...) : RIFF::Exception() {
2524            va_list arg;
2525            va_start(arg, format);
2526            Message = assemble(format, arg);
2527            va_end(arg);
2528        }
2529    
2530        Exception::Exception(String format, va_list arg) : RIFF::Exception() {
2531            Message = assemble(format, arg);
2532      }      }
2533    
2534      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.2482  
changed lines
  Added in v.3941

  ViewVC Help
Powered by ViewVC