/[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 809 by schoenebeck, Tue Nov 22 11:26:55 2005 UTC revision 3940 by schoenebeck, Fri Jun 18 13:47:46 2021 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 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 23  Line 23 
23    
24  #include "DLS.h"  #include "DLS.h"
25    
26    #include <algorithm>
27    #include <vector>
28  #include <time.h>  #include <time.h>
29    
30    #ifdef __APPLE__
31    #include <CoreFoundation/CFUUID.h>
32    #elif defined(HAVE_UUID_UUID_H)
33    #include <uuid/uuid.h>
34    #endif
35    
36  #include "helper.h"  #include "helper.h"
37    
38  // macros to decode connection transforms  // macros to decode connection transforms
# Line 45  Line 53 
53  #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x)             ((x) ? 0x8000 : 0)  #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x)             ((x) ? 0x8000 : 0)
54  #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x)             ((x) ? 0x0200 : 0)  #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x)             ((x) ? 0x0200 : 0)
55    
56  #define DRUM_TYPE_MASK                  0x00000001  #define DRUM_TYPE_MASK                  0x80000000
57    
58  #define F_RGN_OPTION_SELFNONEXCLUSIVE   0x0001  #define F_RGN_OPTION_SELFNONEXCLUSIVE   0x0001
59    
# Line 114  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 137  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();
158          memccpy(&pData[0], &HeaderSize, 1, 2);          store16(&pData[0], HeaderSize);
159          memccpy(&pData[2], &Connections, 1, 2);          store16(&pData[2], Connections);
160          for (uint32_t i = 0; i < Connections; i++) {          for (uint32_t i = 0; i < Connections; i++) {
161              Connection::conn_block_t c = pConnections[i].ToConnBlock();              Connection::conn_block_t c = pConnections[i].ToConnBlock();
162              memccpy(&pData[HeaderSize + i * iEntrySize],     &c.source, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize],     c.source);
163              memccpy(&pData[HeaderSize + i * iEntrySize + 2], &c.control, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize + 2], c.control);
164              memccpy(&pData[HeaderSize + i * iEntrySize + 4], &c.destination, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize + 4], c.destination);
165              memccpy(&pData[HeaderSize + i * iEntrySize + 6], &c.transform, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize + 6], c.transform);
166              memccpy(&pData[HeaderSize + i * iEntrySize + 8], &c.scale, 1, 4);              store32(&pData[HeaderSize + i * iEntrySize + 8], c.scale);
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 164  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 171  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 184  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 210  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
303         * not need to copy DLS articulators and so far nobody used pure
304         * DLS instrument AFAIK.
305         */
306        void Articulator::CopyAssign(const Articulator* orig) {
307            //TODO: implement deep copy assignment for this class
308        }
309    
310    
311    
312  // *************** Info  ***************  // *************** Info  ***************
# Line 228  namespace DLS { Line 314  namespace DLS {
314    
315      /** @brief Constructor.      /** @brief Constructor.
316       *       *
317       * Initializes the info strings with values provided by a INFO list chunk.       * Initializes the info strings with values provided by an INFO list chunk.
318       *       *
319       * @param list - pointer to a list chunk which contains a INFO list chunk       * @param list - pointer to a list chunk which contains an INFO list chunk
320       */       */
321      Info::Info(RIFF::List* list) {      Info::Info(RIFF::List* list) {
322            pFixedStringLengths = NULL;
323          pResourceListChunk = list;          pResourceListChunk = list;
324          if (list) {          if (list) {
325              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
# Line 253  namespace DLS { Line 340  namespace DLS {
340                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);
341                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);
342                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);
343                    LoadString(CHUNK_ID_ISBJ, lstINFO, Subject);
344              }              }
345          }          }
346      }      }
347    
348        Info::~Info() {
349        }
350    
351        /**
352         * Forces specific Info fields to be of a fixed length when being saved
353         * to a file. By default the respective RIFF chunk of an Info field
354         * will have a size analogue to its actual string length. With this
355         * method however this behavior can be overridden, allowing to force an
356         * arbitrary fixed size individually for each Info field.
357         *
358         * This method is used as a workaround for the gig format, not for DLS.
359         *
360         * @param lengths - NULL terminated array of string_length_t elements
361         */
362        void Info::SetFixedStringLengths(const string_length_t* lengths) {
363            pFixedStringLengths = lengths;
364        }
365    
366      /** @brief Load given INFO field.      /** @brief Load given INFO field.
367       *       *
368       * Load INFO field from INFO chunk with chunk ID \a ChunkID from INFO       * Load INFO field from INFO chunk with chunk ID \a ChunkID from INFO
# Line 264  namespace DLS { Line 370  namespace DLS {
370       */       */
371      void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {      void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
372          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
373          if (ck) {          ::LoadString(ck, s); // function from helper.h
             // TODO: no check for ZSTR terminated strings yet  
             s = (char*) ck->LoadChunkData();  
             ck->ReleaseChunkData();  
         }  
374      }      }
375    
376      /** @brief Apply given INFO field to the respective chunk.      /** @brief Apply given INFO field to the respective chunk.
# Line 287  namespace DLS { Line 389  namespace DLS {
389       * @param sDefault - default value       * @param sDefault - default value
390       */       */
391      void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) {      void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) {
392          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);          int size = 0;
393          if (ck) { // if chunk exists already, use 's' as value          if (pFixedStringLengths) {
394              ck->Resize(s.size() + 1);              for (int i = 0 ; pFixedStringLengths[i].length ; i++) {
395              char* pData = (char*) ck->LoadChunkData();                  if (pFixedStringLengths[i].chunkId == ChunkID) {
396              memcpy(pData, s.c_str(), s.size() + 1);                      size = pFixedStringLengths[i].length;
397          } else if (s != "" || sDefault != "") { // create chunk                      break;
398              const String& sToSave = (s != "") ? s : sDefault;                  }
399              ck = lstINFO->AddSubChunk(ChunkID, sToSave.size() + 1);              }
             char* pData = (char*) ck->LoadChunkData();  
             memcpy(pData, sToSave.c_str(), sToSave.size() + 1);  
400          }          }
401            RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
402            ::SaveString(ChunkID, ck, lstINFO, s, sDefault, size != 0, size); // function from helper.h
403      }      }
404    
405      /** @brief Update chunks with current info values.      /** @brief Update chunks with current info values.
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
416          RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);          RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
         if (!lstINFO) lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);  
417    
418          // assemble default values in case the respective chunk is missing yet          String defaultName = "";
419          String defaultName = "NONAME";          String defaultCreationDate = "";
420          // get current date          String defaultSoftware = "";
421          time_t now = time(NULL);          String defaultComments = "";
422          tm* pNowBroken = localtime(&now);  
423          String defaultCreationDate = ToString(1900 + pNowBroken->tm_year) + "-" +          uint32_t resourceType = pResourceListChunk->GetListType();
424                                       ToString(pNowBroken->tm_mon + 1)  + "-" +  
425                                       ToString(pNowBroken->tm_mday);          if (!lstINFO) {
426          String defaultSoftware = libraryName() + " " + libraryVersion();              lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
427          String defaultComments = "Created with " + libraryName() + " " + libraryVersion();  
428                // assemble default values
429                defaultName = "NONAME";
430    
431                if (resourceType == RIFF_TYPE_DLS) {
432                    // get current date
433                    time_t now = time(NULL);
434                    tm* pNowBroken = localtime(&now);
435                    char buf[11];
436                    strftime(buf, 11, "%F", pNowBroken);
437                    defaultCreationDate = buf;
438    
439                    defaultComments = "Created with " + libraryName() + " " + libraryVersion();
440                }
441                if (resourceType == RIFF_TYPE_DLS || resourceType == LIST_TYPE_INS)
442                {
443                    defaultSoftware = libraryName() + " " + libraryVersion();
444                }
445            }
446    
447          // save values          // save values
448          SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);  
449          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
450          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
451            SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
452          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
         SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));  
453          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
454          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
455            SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
456          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
457          SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""));          SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""));
         SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));  
         SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));  
         SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);  
458          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
459            SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
460            SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
461            SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""));
462            SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
463          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
464          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
465          SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, 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
482         * this object.
483         *
484         * @param orig - original Info object to be copied from
485         */
486        void Info::CopyAssign(const Info* orig) {
487            Name = orig->Name;
488            ArchivalLocation = orig->ArchivalLocation;
489            CreationDate = orig->CreationDate;
490            Comments = orig->Comments;
491            Product = orig->Product;
492            Copyright = orig->Copyright;
493            Artists = orig->Artists;
494            Genre = orig->Genre;
495            Keywords = orig->Keywords;
496            Engineer = orig->Engineer;
497            Technician = orig->Technician;
498            Software = orig->Software;
499            Medium = orig->Medium;
500            Source = orig->Source;
501            SourceForm = orig->SourceForm;
502            Commissioned = orig->Commissioned;
503            Subject = orig->Subject;
504            //FIXME: hmm, is copying this pointer a good idea?
505            pFixedStringLengths = orig->pFixedStringLengths;
506      }      }
507    
508    
# Line 364  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 378  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 385  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          //TODO: save DLSID  
571            if (pDLSID) {
572                // make sure 'dlid' chunk exists
573                RIFF::Chunk* ckDLSID = pResourceList->GetSubChunk(CHUNK_ID_DLID);
574                if (!ckDLSID) ckDLSID = pResourceList->AddSubChunk(CHUNK_ID_DLID, 16);
575                uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
576                // update 'dlid' chunk
577                store32(&pData[0], pDLSID->ulData1);
578                store16(&pData[4], pDLSID->usData2);
579                store16(&pData[6], pDLSID->usData3);
580                memcpy(&pData[8], pDLSID->abData, 8);
581            }
582      }      }
583    
584        /**
585         * Generates a new DLSID for the resource.
586         */
587        void Resource::GenerateDLSID() {
588            #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
589            if (!pDLSID) pDLSID = new dlsid_t;
590            GenerateDLSID(pDLSID);
591            #endif
592        }
593    
594        void Resource::GenerateDLSID(dlsid_t* pDLSID) {
595    #ifdef WIN32
596            UUID uuid;
597            UuidCreate(&uuid);
598            pDLSID->ulData1 = uuid.Data1;
599            pDLSID->usData2 = uuid.Data2;
600            pDLSID->usData3 = uuid.Data3;
601            memcpy(pDLSID->abData, uuid.Data4, 8);
602    
603    #elif defined(__APPLE__)
604    
605            CFUUIDRef uuidRef = CFUUIDCreate(NULL);
606            CFUUIDBytes uuid = CFUUIDGetUUIDBytes(uuidRef);
607            CFRelease(uuidRef);
608            pDLSID->ulData1 = uuid.byte0 | uuid.byte1 << 8 | uuid.byte2 << 16 | uuid.byte3 << 24;
609            pDLSID->usData2 = uuid.byte4 | uuid.byte5 << 8;
610            pDLSID->usData3 = uuid.byte6 | uuid.byte7 << 8;
611            pDLSID->abData[0] = uuid.byte8;
612            pDLSID->abData[1] = uuid.byte9;
613            pDLSID->abData[2] = uuid.byte10;
614            pDLSID->abData[3] = uuid.byte11;
615            pDLSID->abData[4] = uuid.byte12;
616            pDLSID->abData[5] = uuid.byte13;
617            pDLSID->abData[6] = uuid.byte14;
618            pDLSID->abData[7] = uuid.byte15;
619    #elif defined(HAVE_UUID_GENERATE)
620            uuid_t uuid;
621            uuid_generate(uuid);
622            pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24;
623            pDLSID->usData2 = uuid[4] | uuid[5] << 8;
624            pDLSID->usData3 = uuid[6] | uuid[7] << 8;
625            memcpy(pDLSID->abData, &uuid[8], 8);
626    #else
627    # error "Missing support for uuid generation"
628    #endif
629        }
630        
631        /**
632         * Make a deep copy of the Resource object given by @a orig and assign it
633         * to this object.
634         *
635         * @param orig - original Resource object to be copied from
636         */
637        void Resource::CopyAssign(const Resource* orig) {
638            pInfo->CopyAssign(orig->pInfo);
639        }
640    
641    
642  // *************** Sampler ***************  // *************** Sampler ***************
# Line 400  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 407  namespace DLS { Line 655  namespace DLS {
655              SamplerOptions = wsmp->ReadUint32();              SamplerOptions = wsmp->ReadUint32();
656              SampleLoops    = wsmp->ReadUint32();              SampleLoops    = wsmp->ReadUint32();
657          } else { // 'wsmp' chunk missing          } else { // 'wsmp' chunk missing
658              uiHeaderSize   = 0;              uiHeaderSize   = 20;
659              UnityNote      = 64;              UnityNote      = 60;
660              FineTune       = 0; // +- 0 cents              FineTune       = 0; // +- 0 cents
661              Gain           = 0; // 0 dB              Gain           = 0; // 0 dB
662              SamplerOptions = F_WSMP_NO_COMPRESSION;              SamplerOptions = F_WSMP_NO_COMPRESSION;
# Line 432  namespace DLS { Line 680  namespace DLS {
680          if (pSampleLoops) delete[] pSampleLoops;          if (pSampleLoops) delete[] pSampleLoops;
681      }      }
682    
683        void Sampler::SetGain(int32_t gain) {
684            Gain = gain;
685        }
686    
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;
697          if (!wsmp) {          if (!wsmp) {
698              uiHeaderSize = 20;              wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, wsmpSize);
699              wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, uiHeaderSize + SampleLoops * 16);          } else if (wsmp->GetSize() != wsmpSize) {
700                wsmp->Resize(wsmpSize);
701          }          }
702          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
703          // update headers size          // update headers size
704          memccpy(&pData[0], &uiHeaderSize, 1, 4);          store32(&pData[0], uiHeaderSize);
705          // update respective sampler options bits          // update respective sampler options bits
706          SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION          SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
707                                                     : SamplerOptions & (~F_WSMP_NO_TRUNCATION);                                                     : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
708          SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION          SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
709                                                 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);                                                 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
710            store16(&pData[4], UnityNote);
711            store16(&pData[6], FineTune);
712            store32(&pData[8], Gain);
713            store32(&pData[12], SamplerOptions);
714            store32(&pData[16], SampleLoops);
715          // update loop definitions          // update loop definitions
716          for (uint32_t i = 0; i < SampleLoops; i++) {          for (uint32_t i = 0; i < SampleLoops; i++) {
717              //FIXME: this does not handle extended loop structs correctly              //FIXME: this does not handle extended loop structs correctly
718              memccpy(&pData[uiHeaderSize + i * 16], pSampleLoops + i, 4, 4);              store32(&pData[uiHeaderSize + i * 16], pSampleLoops[i].Size);
719                store32(&pData[uiHeaderSize + i * 16 + 4], pSampleLoops[i].LoopType);
720                store32(&pData[uiHeaderSize + i * 16 + 8], pSampleLoops[i].LoopStart);
721                store32(&pData[uiHeaderSize + i * 16 + 12], pSampleLoops[i].LoopLength);
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.
739         *
740         * @param pLoopDef - points to a loop definition that is to be copied
741         */
742        void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {
743            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
744            // copy old loops array
745            for (int i = 0; i < SampleLoops; i++) {
746                pNewLoops[i] = pSampleLoops[i];
747            }
748            // add the new loop
749            pNewLoops[SampleLoops] = *pLoopDef;
750            // auto correct size field
751            pNewLoops[SampleLoops].Size = sizeof(DLS::sample_loop_t);
752            // free the old array and update the member variables
753            if (SampleLoops) delete[] pSampleLoops;
754            pSampleLoops = pNewLoops;
755            SampleLoops++;
756        }
757    
758        /**
759         * Deletes an existing sample loop.
760         *
761         * @param pLoopDef - pointer to existing loop definition
762         * @throws Exception - if given loop definition does not exist
763         */
764        void Sampler::DeleteSampleLoop(sample_loop_t* pLoopDef) {
765            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1];
766            // copy old loops array (skipping given loop)
767            for (int i = 0, o = 0; i < SampleLoops; i++) {
768                if (&pSampleLoops[i] == pLoopDef) continue;
769                if (o == SampleLoops - 1) {
770                    delete[] pNewLoops;
771                    throw Exception("Could not delete Sample Loop, because it does not exist");
772                }
773                pNewLoops[o] = pSampleLoops[i];
774                o++;
775            }
776            // free the old array and update the member variables
777            if (SampleLoops) delete[] pSampleLoops;
778            pSampleLoops = pNewLoops;
779            SampleLoops--;
780        }
781        
782        /**
783         * Make a deep copy of the Sampler object given by @a orig and assign it
784         * to this object.
785         *
786         * @param orig - original Sampler object to be copied from
787         */
788        void Sampler::CopyAssign(const Sampler* orig) {
789            // copy trivial scalars
790            UnityNote = orig->UnityNote;
791            FineTune = orig->FineTune;
792            Gain = orig->Gain;
793            NoSampleDepthTruncation = orig->NoSampleDepthTruncation;
794            NoSampleCompression = orig->NoSampleCompression;
795            SamplerOptions = orig->SamplerOptions;
796            
797            // copy sample loops
798            if (SampleLoops) delete[] pSampleLoops;
799            pSampleLoops = new sample_loop_t[orig->SampleLoops];
800            memcpy(pSampleLoops, orig->pSampleLoops, orig->SampleLoops * sizeof(sample_loop_t));
801            SampleLoops = orig->SampleLoops;
802        }
803    
804    
805  // *************** Sample ***************  // *************** Sample ***************
# Line 478  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 491  namespace DLS { Line 835  namespace DLS {
835              AverageBytesPerSecond  = pCkFormat->ReadUint32();              AverageBytesPerSecond  = pCkFormat->ReadUint32();
836              BlockAlign             = pCkFormat->ReadUint16();              BlockAlign             = pCkFormat->ReadUint16();
837              // PCM format specific              // PCM format specific
838              if (FormatTag == WAVE_FORMAT_PCM) {              if (FormatTag == DLS_WAVE_FORMAT_PCM) {
839                  BitDepth     = pCkFormat->ReadUint16();                  BitDepth     = pCkFormat->ReadUint16();
840                  FrameSize    = (FormatTag == WAVE_FORMAT_PCM) ? (BitDepth / 8) * Channels                  FrameSize    = (BitDepth / 8) * Channels;
                                                             : 0;  
841              } else { // unsupported sample data format              } else { // unsupported sample data format
842                  BitDepth     = 0;                  BitDepth     = 0;
843                  FrameSize    = 0;                  FrameSize    = 0;
844              }              }
845          } else { // 'fmt' chunk missing          } else { // 'fmt' chunk missing
846              FormatTag              = WAVE_FORMAT_PCM;              FormatTag              = DLS_WAVE_FORMAT_PCM;
847              BitDepth               = 16;              BitDepth               = 16;
848              Channels               = 1;              Channels               = 1;
849              SamplesPerSecond       = 44100;              SamplesPerSecond       = 44100;
# Line 508  namespace DLS { Line 851  namespace DLS {
851              FrameSize              = (BitDepth / 8) * Channels;              FrameSize              = (BitDepth / 8) * Channels;
852              BlockAlign             = FrameSize;              BlockAlign             = FrameSize;
853          }          }
854          SamplesTotal = (pCkData) ? (FormatTag == WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize          SamplesTotal = (pCkData) ? (FormatTag == DLS_WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
855                                                                    : 0                                                                        : 0
856                                   : 0;                                   : 0;
857      }      }
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
888         * actual sample waveform data however) and assign it to this object.
889         *
890         * This is a special internal variant of CopyAssign() which only copies the
891         * most mandatory member variables. It will be called by gig::Sample
892         * descendent instead of CopyAssign() since gig::Sample has its own
893         * implementation to access and copy the actual sample waveform data.
894         *
895         * @param orig - original Sample object to be copied from
896         */
897        void Sample::CopyAssignCore(const Sample* orig) {
898            // handle base classes
899            Resource::CopyAssign(orig);
900            // handle actual own attributes of this class
901            FormatTag = orig->FormatTag;
902            Channels = orig->Channels;
903            SamplesPerSecond = orig->SamplesPerSecond;
904            AverageBytesPerSecond = orig->AverageBytesPerSecond;
905            BlockAlign = orig->BlockAlign;
906            BitDepth = orig->BitDepth;
907            SamplesTotal = orig->SamplesTotal;
908            FrameSize = orig->FrameSize;
909        }
910        
911        /**
912         * Make a deep copy of the Sample object given by @a orig and assign it to
913         * this object.
914         *
915         * @param orig - original Sample object to be copied from
916         */
917        void Sample::CopyAssign(const Sample* orig) {
918            CopyAssignCore(orig);
919            
920            // copy sample waveform data (reading directly from disc)
921            Resize(orig->GetSize());
922            char* buf = (char*) LoadSampleData();
923            Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
924            const file_offset_t restorePos = pOrig->pCkData->GetPos();
925            pOrig->SetPos(0);
926            for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
927                const int iReadAtOnce = 64*1024;
928                file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
929                n = pOrig->Read(&buf[i], n);
930                if (!n) break;
931                todo -= n;
932                i += (n * pOrig->FrameSize);
933            }
934            pOrig->pCkData->SetPos(restorePos);
935      }      }
936    
937      /** @brief Load sample data into RAM.      /** @brief Load sample data into RAM.
# Line 569  namespace DLS { Line 980  namespace DLS {
980       * the RIFF chunk which encapsulates the sample's wave data. The       * the RIFF chunk which encapsulates the sample's wave data. The
981       * returned value is dependant to the current FrameSize value.       * returned value is dependant to the current FrameSize value.
982       *       *
983       * @returns number of sample points or 0 if FormatTag != 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() {      file_offset_t Sample::GetSize() const {
987          if (FormatTag != 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      }      }
990    
# Line 595  namespace DLS { Line 1006  namespace DLS {
1006       * calling File::Save() as this might exceed the current sample's       * calling File::Save() as this might exceed the current sample's
1007       * boundary!       * boundary!
1008       *       *
1009       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
1010       * FormatTag must be 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 != 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 != WAVE_FORMAT_PCM) throw Exception("Sample's format is not 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 619  namespace DLS { Line 1032  namespace DLS {
1032       * bytes). Use this method and <i>Read()</i> if you don't want to load       * bytes). Use this method and <i>Read()</i> if you don't want to load
1033       * the sample into RAM, thus for disk streaming.       * the sample into RAM, thus for disk streaming.
1034       *       *
1035       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
1036       * FormatTag must be WAVE_FORMAT_PCM. Trying to reposition the sample       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to reposition the sample
1037       * with other formats will fail!       * with other formats will fail!
1038       *       *
1039       * @param SampleCount  number of sample points       * @param SampleCount  number of sample points
1040       * @param Whence       to which relation \a SampleCount refers to       * @param Whence       to which relation \a SampleCount refers to
1041       * @returns new position within the sample, 0 if       * @returns new position within the sample, 0 if
1042       *          FormatTag != WAVE_FORMAT_PCM       *          FormatTag != DLS_WAVE_FORMAT_PCM
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 != 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 648  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 != 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      }      }
1068    
# Line 668  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 != 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?
1088      }      }
# Line 678  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       * @throws Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @param pProgress - callback function for progress notification
1095         * @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 != 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
1109          uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
1110          // update 'fmt' chunk          // update 'fmt' chunk
1111          memccpy(&pData[0], &FormatTag, 1, 2);          store16(&pData[0], FormatTag);
1112          memccpy(&pData[2], &Channels,  1, 2);          store16(&pData[2], Channels);
1113          memccpy(&pData[4], &SamplesPerSecond, 1, 4);          store32(&pData[4], SamplesPerSecond);
1114          memccpy(&pData[8], &AverageBytesPerSecond, 1, 4);          store32(&pData[8], AverageBytesPerSecond);
1115          memccpy(&pData[12], &BlockAlign, 1, 2);          store16(&pData[12], BlockAlign);
1116          memccpy(&pData[14], &BitDepth, 1, 2); // assuming PCM format          store16(&pData[14], BitDepth); // assuming PCM format
1117      }      }
1118    
1119    
# Line 710  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 732  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 753  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 783  namespace DLS { Line 1219  namespace DLS {
1219      }      }
1220    
1221      /**      /**
1222         * Modifies the key range of this Region and makes sure the respective
1223         * chunks are in correct order.
1224         *
1225         * @param Low  - lower end of key range
1226         * @param High - upper end of key range
1227         */
1228        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
1229            KeyRange.low  = Low;
1230            KeyRange.high = High;
1231    
1232            // make sure regions are already loaded
1233            Instrument* pInstrument = (Instrument*) GetParent();
1234            if (!pInstrument->pRegions) pInstrument->LoadRegions();
1235            if (!pInstrument->pRegions) return;
1236    
1237            // find the r which is the first one to the right of this region
1238            // at its new position
1239            Region* r = NULL;
1240            Region* prev_region = NULL;
1241            for (
1242                Instrument::RegionList::iterator iter = pInstrument->pRegions->begin();
1243                iter != pInstrument->pRegions->end(); iter++
1244            ) {
1245                if ((*iter)->KeyRange.low > this->KeyRange.low) {
1246                    r = *iter;
1247                    break;
1248                }
1249                prev_region = *iter;
1250            }
1251    
1252            // place this region before r if it's not already there
1253            if (prev_region != this) pInstrument->MoveRegion(this, r);
1254        }
1255    
1256        /**
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, 14);          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
1267          uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();          uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
1268          FormatOptionFlags = (SelfNonExclusive)          FormatOptionFlags = (SelfNonExclusive)
1269                                  ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE                                  ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
1270                                  : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);                                  : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
1271          // update 'rgnh' chunk          // update 'rgnh' chunk
1272          memccpy(&pData[0], &KeyRange, 2, 2);          store16(&pData[0], KeyRange.low);
1273          memccpy(&pData[4], &VelocityRange, 2, 2);          store16(&pData[2], KeyRange.high);
1274          memccpy(&pData[8], &FormatOptionFlags, 1, 2);          store16(&pData[4], VelocityRange.low);
1275          memccpy(&pData[10], &KeyGroup, 1, 2);          store16(&pData[6], VelocityRange.high);
1276          memccpy(&pData[12], &Layer, 1, 2);          store16(&pData[8], FormatOptionFlags);
1277            store16(&pData[10], KeyGroup);
1278          // update chunks of base classes as well          if (rgnh->GetSize() >= 14) store16(&pData[12], Layer);
1279          Resource::UpdateChunks();  
1280          Articulator::UpdateChunks();          // update chunks of base classes as well (but skip Resource,
1281          Sampler::UpdateChunks();          // as a rgn doesn't seem to have dlid and INFO chunks)
1282            Articulator::UpdateChunks(pProgress);
1283            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 831  namespace DLS { Line 1305  namespace DLS {
1305                  }                  }
1306              }              }
1307          }          }
         if (index < 0) throw Exception("Could not save Region, could not find Region's sample");  
1308          WavePoolTableIndex = index;          WavePoolTableIndex = index;
1309          // update 'wlnk' chunk          // update 'wlnk' chunk
1310          memccpy(&pData[0], &WaveLinkOptionFlags, 1, 2);          store16(&pData[0], WaveLinkOptionFlags);
1311          memccpy(&pData[2], &PhaseGroup, 1, 2);          store16(&pData[2], PhaseGroup);
1312          memccpy(&pData[4], &Channel, 1, 4);          store32(&pData[4], Channel);
1313          memccpy(&pData[8], &WavePoolTableIndex, 1, 4);          store32(&pData[8], WavePoolTableIndex);
1314        }
1315        
1316        /**
1317         * Make a (semi) deep copy of the Region object given by @a orig and assign
1318         * it to this object.
1319         *
1320         * Note that the sample pointer referenced by @a orig is simply copied as
1321         * memory address. Thus the respective sample is shared, not duplicated!
1322         *
1323         * @param orig - original Region object to be copied from
1324         */
1325        void Region::CopyAssign(const Region* orig) {
1326            // handle base classes
1327            Resource::CopyAssign(orig);
1328            Articulator::CopyAssign(orig);
1329            Sampler::CopyAssign(orig);
1330            // handle actual own attributes of this class
1331            // (the trivial ones)
1332            VelocityRange = orig->VelocityRange;
1333            KeyGroup = orig->KeyGroup;
1334            Layer = orig->Layer;
1335            SelfNonExclusive = orig->SelfNonExclusive;
1336            PhaseMaster = orig->PhaseMaster;
1337            PhaseGroup = orig->PhaseGroup;
1338            MultiChannel = orig->MultiChannel;
1339            Channel = orig->Channel;
1340            // only take the raw sample reference if the two Region objects are
1341            // part of the same file
1342            if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1343                WavePoolTableIndex = orig->WavePoolTableIndex;
1344                pSample = orig->pSample;
1345            } else {
1346                WavePoolTableIndex = -1;
1347                pSample = NULL;
1348            }
1349            FormatOptionFlags = orig->FormatOptionFlags;
1350            WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1351            // handle the last, a bit sensible attribute
1352            SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1353      }      }
   
1354    
1355    
1356  // *************** Instrument ***************  // *************** Instrument ***************
# Line 864  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 881  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 888  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 895  namespace DLS { Line 1443  namespace DLS {
1443      }      }
1444    
1445      void Instrument::LoadRegions() {      void Instrument::LoadRegions() {
1446            if (!pRegions) pRegions = new RegionList;
1447          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1448          if (!lrgn) throw DLS::Exception("DLS::Instrument doesn't seem to have any Region (mandatory chunks in <ins > chunk not found)");          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              if (rgn->GetListType() == regionCkType) {                   rgn = lrgn->GetSubListAt(++i))
1453                  if (!pRegions) pRegions = new RegionList;              {
1454                  pRegions->push_back(new Region(this, rgn));                  if (rgn->GetListType() == regionCkType) {
1455                        pRegions->push_back(new Region(this, rgn));
1456                    }
1457              }              }
             rgn = lrgn->GetNextSubList();  
1458          }          }
1459      }      }
1460    
1461      Region* Instrument::AddRegion() {      Region* Instrument::AddRegion() {
1462          if (!pRegions) pRegions = new RegionList;          if (!pRegions) LoadRegions();
1463          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1464          if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);          if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
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 = (uint32_t) pRegions->size();
1469          return pNewRegion;          return pNewRegion;
1470      }      }
1471    
1472        void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1473            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1474            lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1475            for (size_t i = 0; i < pRegions->size(); ++i) {
1476                if ((*pRegions)[i] == pSrc) {
1477                    pRegions->erase(pRegions->begin() + i);
1478                    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) {
1485          if (!pRegions) return;          if (!pRegions) return;
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 = (uint32_t) pRegions->size();
1490            pRegion->DeleteChunks();
1491          delete pRegion;          delete pRegion;
1492      }      }
1493    
# Line 930  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);
1514          locale.bank       = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);          locale.bank       = (IsDrum) ? locale.bank | DRUM_TYPE_MASK : locale.bank & (~DRUM_TYPE_MASK);
1515          MIDIBank          = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it          MIDIBank          = MIDI_BANK_MERGE(MIDIBankCoarse, MIDIBankFine); // just a sync, when we're at it
1516          memccpy(&pData[0], &Regions, 1, 4);          store32(&pData[0], Regions);
1517          memccpy(&pData[4], &locale, 2, 4);          store32(&pData[4], locale.bank);
1518            store32(&pData[8], locale.instrument);
1519          // update Region's chunks          // update Region's chunks
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 973  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) {
1579            // handle base classes
1580            Resource::CopyAssign(orig);
1581            Articulator::CopyAssign(orig);
1582            // handle actual own attributes of this class
1583            // (the trivial ones)
1584            IsDrum = orig->IsDrum;
1585            MIDIBank = orig->MIDIBank;
1586            MIDIBankCoarse = orig->MIDIBankCoarse;
1587            MIDIBankFine = orig->MIDIBankFine;
1588            MIDIProgram = orig->MIDIProgram;
1589        }
1590        
1591        /**
1592         * Make a (semi) deep copy of the Instrument object given by @a orig and assign
1593         * it to this object.
1594         *
1595         * Note that all sample pointers referenced by @a orig are simply copied as
1596         * memory address. Thus the respective samples are shared, not duplicated!
1597         *
1598         * @param orig - original Instrument object to be copied from
1599         */
1600        void Instrument::CopyAssign(const Instrument* orig) {
1601            CopyAssignCore(orig);
1602            // delete all regions first
1603            while (Regions) DeleteRegion(GetRegionAt(0));
1604            // now recreate and copy regions
1605            {
1606                RegionList::const_iterator it = orig->pRegions->begin();
1607                for (int i = 0; i < orig->Regions; ++i, ++it) {
1608                    Region* dstRgn = AddRegion();
1609                    //NOTE: Region does semi-deep copy !
1610                    dstRgn->CopyAssign(*it);
1611                }
1612            }
1613        }
1614    
1615    
1616  // *************** File ***************  // *************** File ***************
# Line 990  namespace DLS { Line 1623  namespace DLS {
1623       * a DLS file.       * a DLS file.
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);
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 1020  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 1030  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);
1674          if (!ptbl) throw DLS::Exception("Mandatory <ptbl> chunk not found.");          if (!ptbl) { // pool table is missing - this is probably an ".art" file
1675          WavePoolHeaderSize = ptbl->ReadUint32();              WavePoolCount    = 0;
1676          WavePoolCount  = ptbl->ReadUint32();              pWavePoolTable   = NULL;
1677          pWavePoolTable = new uint32_t[WavePoolCount];              pWavePoolTableHi = NULL;
1678          pWavePoolTableHi = new uint32_t[WavePoolCount];              WavePoolHeaderSize = 8;
1679          ptbl->SetPos(WavePoolHeaderSize);              b64BitWavePoolOffsets = false;
1680            } else {
1681          // Check for 64 bit offsets (used in gig v3 files)              ptbl->SetPos(0);
1682          b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);  
1683          if (b64BitWavePoolOffsets) {              WavePoolHeaderSize = ptbl->ReadUint32();
1684              for (int i = 0 ; i < WavePoolCount ; i++) {              WavePoolCount  = ptbl->ReadUint32();
1685                  pWavePoolTableHi[i] = ptbl->ReadUint32();              pWavePoolTable = new uint32_t[WavePoolCount];
1686                  pWavePoolTable[i] = ptbl->ReadUint32();              pWavePoolTableHi = new uint32_t[WavePoolCount];
1687                  if (pWavePoolTable[i] & 0x80000000)              ptbl->SetPos(WavePoolHeaderSize);
1688                      throw DLS::Exception("Files larger than 2 GB not yet supported");  
1689                // Check for 64 bit offsets (used in gig v3 files)
1690                b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1691                if (b64BitWavePoolOffsets) {
1692                    for (int i = 0 ; i < WavePoolCount ; i++) {
1693                        pWavePoolTableHi[i] = ptbl->ReadUint32();
1694                        pWavePoolTable[i] = ptbl->ReadUint32();
1695                        //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1696                        //if (pWavePoolTable[i] & 0x80000000)
1697                        //    throw DLS::Exception("Files larger than 2 GB not yet supported");
1698                    }
1699                } else { // conventional 32 bit offsets
1700                    ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1701                    for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1702              }              }
         } else { // conventional 32 bit offsets  
             ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));  
             for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;  
1703          }          }
1704    
1705          pSamples     = NULL;          pSamples     = NULL;
# Line 1082  namespace DLS { Line 1730  namespace DLS {
1730          if (pWavePoolTable) delete[] pWavePoolTable;          if (pWavePoolTable) delete[] pWavePoolTable;
1731          if (pWavePoolTableHi) delete[] pWavePoolTableHi;          if (pWavePoolTableHi) delete[] pWavePoolTableHi;
1732          if (pVersion) delete pVersion;          if (pVersion) delete pVersion;
1733            for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1734                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 1091  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 1098  namespace DLS { Line 1777  namespace DLS {
1777      }      }
1778    
1779      void File::LoadSamples() {      void File::LoadSamples() {
1780            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                      if (!pSamples) pSamples = new SampleList;                      file_offset_t waveFileOffset = wave->GetFilePos() -
1791                      unsigned long waveFileOffset = wave->GetFilePos();                                                     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                          if (!pSamples) pSamples = new SampleList;                          file_offset_t waveFileOffset = wave->GetFilePos() -
1807                          unsigned long waveFileOffset = wave->GetFilePos();                                                         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 1140  namespace DLS { Line 1824  namespace DLS {
1824         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
1825         RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);         RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1826         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
        if (!pSamples) pSamples = new SampleList;  
1827         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
1828         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
1829         pSamples->push_back(pSample);         pSamples->push_back(pSample);
# Line 1159  namespace DLS { Line 1842  namespace DLS {
1842          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1843          if (iter == pSamples->end()) return;          if (iter == pSamples->end()) return;
1844          pSamples->erase(iter);          pSamples->erase(iter);
1845            pSample->DeleteChunks();
1846          delete pSample;          delete pSample;
1847      }      }
1848    
# Line 1176  namespace DLS { Line 1860  namespace DLS {
1860      }      }
1861    
1862      void File::LoadInstruments() {      void File::LoadInstruments() {
1863            if (!pInstruments) pInstruments = new InstrumentList;
1864          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1865          if (lstInstruments) {          if (lstInstruments) {
1866              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              size_t i = 0;
1867              while (lstInstr) {              for (RIFF::List* lstInstr = lstInstruments->GetSubListAt(i);
1868                     lstInstr; lstInstr = lstInstruments->GetSubListAt(++i))
1869                {
1870                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
                     if (!pInstruments) pInstruments = new InstrumentList;  
1871                      pInstruments->push_back(new Instrument(this, lstInstr));                      pInstruments->push_back(new Instrument(this, lstInstr));
1872                  }                  }
                 lstInstr = lstInstruments->GetNextSubList();  
1873              }              }
1874          }          }
1875      }      }
# Line 1199  namespace DLS { Line 1884  namespace DLS {
1884      Instrument* File::AddInstrument() {      Instrument* File::AddInstrument() {
1885         if (!pInstruments) LoadInstruments();         if (!pInstruments) LoadInstruments();
1886         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
        if (!pInstruments) pInstruments = new InstrumentList;  
1887         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
1888         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
1889         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
# Line 1219  namespace DLS { Line 1903  namespace DLS {
1903          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1904          if (iter == pInstruments->end()) return;          if (iter == pInstruments->end()) return;
1905          pInstruments->erase(iter);          pInstruments->erase(iter);
1906            pInstrument->DeleteChunks();
1907          delete pInstrument;          delete pInstrument;
1908      }      }
1909    
1910      /**      /**
1911         * Returns the underlying RIFF::File used for persistency of this DLS::File
1912         * object.
1913         */
1914        RIFF::File* File::GetRiffFile() {
1915            return pRIFF;
1916        }
1917    
1918        /**
1919         * Returns extension file of given index. Extension files are used
1920         * sometimes to circumvent the 2 GB file size limit of the RIFF format and
1921         * of certain operating systems in general. In this case, instead of just
1922         * using one file, the content is spread among several files with similar
1923         * file name scheme. This is especially used by some GigaStudio sound
1924         * libraries.
1925         *
1926         * @param index - index of extension file
1927         * @returns sought extension file, NULL if index out of bounds
1928         * @see GetFileName()
1929         */
1930        RIFF::File* File::GetExtensionFile(int index) {
1931            if (index < 0 || index >= ExtensionFiles.size()) return NULL;
1932            std::list<RIFF::File*>::iterator iter = ExtensionFiles.begin();
1933            for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i)
1934                if (i == index) return *iter;
1935            return NULL;
1936        }
1937    
1938        /** @brief File name of this DLS file.
1939         *
1940         * This method returns the file name as it was provided when loading
1941         * the respective DLS file. However in case the File object associates
1942         * an empty, that is new DLS file, which was not yet saved to disk,
1943         * this method will return an empty string.
1944         *
1945         * @see GetExtensionFile()
1946         */
1947        String File::GetFileName() {
1948            return pRIFF->GetFileName();
1949        }
1950        
1951        /**
1952         * You may call this method store a future file name, so you don't have to
1953         * to pass it to the Save() call later on.
1954         */
1955        void File::SetFileName(const String& name) {
1956            pRIFF->SetFileName(name);
1957        }
1958    
1959        /**
1960       * Apply all the DLS file's current instruments, samples and settings to       * Apply all the DLS file's current instruments, samples and settings to
1961       * the respective RIFF chunks. You have to call Save() to make changes       * the respective RIFF chunks. You have to call Save() to make changes
1962       * persistent.       * persistent.
1963       *       *
1964         * @param pProgress - callback function for progress notification
1965       * @throws Exception - on errors       * @throws Exception - on errors
1966       */       */
1967      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
1968          // first update base class's chunks          // first update base class's chunks
1969          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1970    
1971          // if version struct exists, update 'vers' chunk          // if version struct exists, update 'vers' chunk
1972          if (pVersion) {          if (pVersion) {
1973              RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);              RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1974              if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);              if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1975              uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();              uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1976              memccpy(pData, pVersion, 2, 4);              store16(&pData[0], pVersion->minor);
1977                store16(&pData[2], pVersion->major);
1978                store16(&pData[4], pVersion->build);
1979                store16(&pData[6], pVersion->release);
1980          }          }
1981    
1982          // update 'colh' chunk          // update 'colh' chunk
1983          Instruments = (pInstruments) ? pInstruments->size() : 0;          Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
1984          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1985          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1986          uint8_t* pData = (uint8_t*) colh->LoadChunkData();          uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1987          memccpy(pData, &Instruments, 1, 4);          store32(pData, Instruments);
1988    
1989          // update instrument's chunks          // update instrument's chunks
1990          if (pInstruments) {          if (pInstruments) {
1991              InstrumentList::iterator iter = pInstruments->begin();              if (pProgress) {
1992              InstrumentList::iterator end  = pInstruments->end();                  // divide local progress into subprogress
1993              for (; iter != end; ++iter) {                  progress_t subprogress;
1994                  (*iter)->UpdateChunks();                  __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1995    
1996                    // do the actual work
1997                    InstrumentList::iterator iter = pInstruments->begin();
1998                    InstrumentList::iterator end  = pInstruments->end();
1999                    for (int i = 0; iter != end; ++iter, ++i) {
2000                        // divide subprogress into sub-subprogress
2001                        progress_t subsubprogress;
2002                        __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
2003                        // do the actual work
2004                        (*iter)->UpdateChunks(&subsubprogress);
2005                    }
2006    
2007                    __notify_progress(&subprogress, 1.0); // notify subprogress done
2008                } else {
2009                    InstrumentList::iterator iter = pInstruments->begin();
2010                    InstrumentList::iterator end  = pInstruments->end();
2011                    for (int i = 0; iter != end; ++iter, ++i) {
2012                        (*iter)->UpdateChunks(NULL);
2013                    }
2014              }              }
2015          }          }
2016    
2017          // update 'ptbl' chunk          // update 'ptbl' chunk
2018          const int iSamples = (pSamples) ? pSamples->size() : 0;          const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
2019          const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2020          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2021          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*/);
2022          const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;          int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2023          ptbl->Resize(iPtblSize);          ptbl->Resize(iPtblSize);
2024          pData = (uint8_t*) ptbl->LoadChunkData();          pData = (uint8_t*) ptbl->LoadChunkData();
2025          WavePoolCount = iSamples;          WavePoolCount = iSamples;
2026          memccpy(&pData[4], &WavePoolCount, 1, 4);          store32(&pData[4], WavePoolCount);
2027          // we actually update the sample offsets in the pool table when we Save()          // we actually update the sample offsets in the pool table when we Save()
2028          memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);          memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
2029    
2030          // update sample's chunks          // update sample's chunks
2031          if (pSamples) {          if (pSamples) {
2032              SampleList::iterator iter = pSamples->begin();              if (pProgress) {
2033              SampleList::iterator end  = pSamples->end();                  // divide local progress into subprogress
2034              for (; iter != end; ++iter) {                  progress_t subprogress;
2035                  (*iter)->UpdateChunks();                  __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
2036    
2037                    // do the actual work
2038                    SampleList::iterator iter = pSamples->begin();
2039                    SampleList::iterator end  = pSamples->end();
2040                    for (int i = 0; iter != end; ++iter, ++i) {
2041                        // divide subprogress into sub-subprogress
2042                        progress_t subsubprogress;
2043                        __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
2044                        // do the actual work
2045                        (*iter)->UpdateChunks(&subsubprogress);
2046                    }
2047    
2048                    __notify_progress(&subprogress, 1.0); // notify subprogress done
2049                } else {
2050                    SampleList::iterator iter = pSamples->begin();
2051                    SampleList::iterator end  = pSamples->end();
2052                    for (int i = 0; iter != end; ++iter, ++i) {
2053                        (*iter)->UpdateChunks(NULL);
2054                    }
2055              }              }
2056          }          }
2057    
2058            // if there are any extension files, gather which ones are regular
2059            // extension files used as wave pool files (.gx00, .gx01, ... , .gx98)
2060            // and which one is probably a convolution (GigaPulse) file (always to
2061            // be saved as .gx99)
2062            std::list<RIFF::File*> poolFiles;  // < for (.gx00, .gx01, ... , .gx98) files
2063            RIFF::File* pGigaPulseFile = NULL; // < for .gx99 file
2064            if (!ExtensionFiles.empty()) {
2065                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2066                for (; it != ExtensionFiles.end(); ++it) {
2067                    //FIXME: the .gx99 file is always used by GSt for convolution
2068                    // data (GigaPulse); so we should better detect by subchunk
2069                    // whether the extension file is intended for convolution
2070                    // instead of checkking for a file name, because the latter does
2071                    // not work for saving new gigs created from scratch
2072                    const std::string oldName = (*it)->GetFileName();
2073                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2074                    if (isGigaPulseFile)
2075                        pGigaPulseFile = *it;
2076                    else
2077                        poolFiles.push_back(*it);
2078                }
2079            }
2080    
2081            // update the 'xfil' chunk which describes all extension files (wave
2082            // pool files) except the .gx99 file
2083            if (!poolFiles.empty()) {
2084                const int n = poolFiles.size();
2085                const int iHeaderSize = 4;
2086                const int iEntrySize = 144;
2087    
2088                // make sure chunk exists, and with correct size
2089                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2090                if (ckXfil)
2091                    ckXfil->Resize(iHeaderSize + n * iEntrySize);
2092                else
2093                    ckXfil = pRIFF->AddSubChunk(CHUNK_ID_XFIL, iHeaderSize + n * iEntrySize);
2094    
2095                uint8_t* pData = (uint8_t*) ckXfil->LoadChunkData();
2096    
2097                // re-assemble the chunk's content
2098                store32(pData, n);
2099                std::list<RIFF::File*>::iterator itExtFile = poolFiles.begin();
2100                for (int i = 0, iOffset = 4; i < n;
2101                     ++itExtFile, ++i, iOffset += iEntrySize)
2102                {
2103                    // update the filename string and 5 byte extension of each extension file
2104                    std::string file = lastPathComponent(
2105                        (*itExtFile)->GetFileName()
2106                    );
2107                    if (file.length() + 6 > 128)
2108                        throw Exception("Fatal error, extension filename length exceeds 122 byte maximum");
2109                    uint8_t* pStrings = &pData[iOffset];
2110                    memset(pStrings, 0, 128);
2111                    memcpy(pStrings, file.c_str(), file.length());
2112                    pStrings += file.length() + 1;
2113                    std::string ext = file.substr(file.length()-5);
2114                    memcpy(pStrings, ext.c_str(), 5);
2115                    // update the dlsid of the extension file
2116                    uint8_t* pId = &pData[iOffset + 128];
2117                    dlsid_t id;
2118                    RIFF::Chunk* ckDLSID = (*itExtFile)->GetSubChunk(CHUNK_ID_DLID);
2119                    if (ckDLSID) {
2120                        ckDLSID->Read(&id.ulData1, 1, 4);
2121                        ckDLSID->Read(&id.usData2, 1, 2);
2122                        ckDLSID->Read(&id.usData3, 1, 2);
2123                        ckDLSID->Read(id.abData, 8, 1);
2124                    } else {
2125                        ckDLSID = (*itExtFile)->AddSubChunk(CHUNK_ID_DLID, 16);
2126                        Resource::GenerateDLSID(&id);
2127                        uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
2128                        store32(&pData[0], id.ulData1);
2129                        store16(&pData[4], id.usData2);
2130                        store16(&pData[6], id.usData3);
2131                        memcpy(&pData[8], id.abData, 8);
2132                    }
2133                    store32(&pId[0], id.ulData1);
2134                    store16(&pId[4], id.usData2);
2135                    store16(&pId[6], id.usData3);
2136                    memcpy(&pId[8], id.abData, 8);
2137                }
2138            } else {
2139                // in case there was a 'xfil' chunk, remove it
2140                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2141                if (ckXfil) pRIFF->DeleteSubChunk(ckXfil);
2142            }
2143    
2144            // update the 'doxf' chunk which describes a .gx99 extension file
2145            // which contains convolution data (GigaPulse)
2146            if (pGigaPulseFile) {
2147                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2148                if (!ckDoxf) ckDoxf = pRIFF->AddSubChunk(CHUNK_ID_DOXF, 148);
2149    
2150                uint8_t* pData = (uint8_t*) ckDoxf->LoadChunkData();
2151    
2152                // update the dlsid from the extension file
2153                uint8_t* pId = &pData[132];
2154                RIFF::Chunk* ckDLSID = pGigaPulseFile->GetSubChunk(CHUNK_ID_DLID);
2155                if (!ckDLSID) { //TODO: auto generate DLS ID if missing
2156                    throw Exception("Fatal error, GigaPulse file does not contain a DLS ID chunk");
2157                } else {
2158                    dlsid_t id;
2159                    // read DLS ID from extension files's DLS ID chunk
2160                    uint8_t* pData = (uint8_t*) ckDLSID->LoadChunkData();
2161                    id.ulData1 = load32(&pData[0]);
2162                    id.usData2 = load16(&pData[4]);
2163                    id.usData3 = load16(&pData[6]);
2164                    memcpy(id.abData, &pData[8], 8);
2165                    // store DLS ID to 'doxf' chunk
2166                    store32(&pId[0], id.ulData1);
2167                    store16(&pId[4], id.usData2);
2168                    store16(&pId[6], id.usData3);
2169                    memcpy(&pId[8], id.abData, 8);
2170                }
2171            } else {
2172                // in case there was a 'doxf' chunk, remove it
2173                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2174                if (ckDoxf) pRIFF->DeleteSubChunk(ckDoxf);
2175            }
2176    
2177            // the RIFF file to be written might now been grown >= 4GB or might
2178            // been shrunk < 4GB, so we might need to update the wave pool offset
2179            // size and thus accordingly we would need to resize the wave pool
2180            // chunk
2181            const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
2182            const bool bRequires64Bit = (finalFileSize >> 32) != 0 || // < native 64 bit gig file
2183                                         poolFiles.size() > 0;        // < 32 bit gig file where the hi 32 bits are used as extension file nr
2184            if (b64BitWavePoolOffsets != bRequires64Bit) {
2185                b64BitWavePoolOffsets = bRequires64Bit;
2186                iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2187                iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2188                ptbl->Resize(iPtblSize);
2189            }
2190    
2191            if (pProgress)
2192                __notify_progress(pProgress, 1.0); // notify done
2193      }      }
2194    
2195      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1292  namespace DLS { Line 2204  namespace DLS {
2204       * the new file (given by \a Path) afterwards.       * the new file (given by \a Path) afterwards.
2205       *       *
2206       * @param Path - path and file name where everything should be written to       * @param Path - path and file name where everything should be written to
2207         * @param pProgress - optional: callback function for progress notification
2208       */       */
2209      void File::Save(const String& Path) {      void File::Save(const String& Path, progress_t* pProgress) {
2210          UpdateChunks();          // calculate number of tasks to notify progress appropriately
2211          pRIFF->Save(Path);          const size_t nExtFiles = ExtensionFiles.size();
2212          __UpdateWavePoolTableChunk();          const float tasks = 2.f + nExtFiles;
2213    
2214            // save extension files (if required)
2215            if (!ExtensionFiles.empty()) {
2216                // for assembling path of extension files to be saved to
2217                const std::string baseName = pathWithoutExtension(Path);
2218                // save the individual extension files
2219                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2220                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2221                    //FIXME: the .gx99 file is always used by GSt for convolution
2222                    // data (GigaPulse); so we should better detect by subchunk
2223                    // whether the extension file is intended for convolution
2224                    // instead of checkking for a file name, because the latter does
2225                    // not work for saving new gigs created from scratch
2226                    const std::string oldName = (*it)->GetFileName();
2227                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2228                    std::string ext = (isGigaPulseFile) ? ".gx99" : strPrint(".gx%02d", i+1);
2229                    std::string newPath = baseName + ext;
2230                    // save extension file to its new location
2231                    if (pProgress) {
2232                         // divide local progress into subprogress
2233                        progress_t subprogress;
2234                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2235                        // do the actual work
2236                        (*it)->Save(newPath, &subprogress);
2237                    } else
2238                        (*it)->Save(newPath);
2239                }
2240            }
2241    
2242            if (pProgress) {
2243                // divide local progress into subprogress
2244                progress_t subprogress;
2245                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2246                // do the actual work
2247                UpdateChunks(&subprogress);
2248            } else
2249                UpdateChunks(NULL);
2250    
2251            if (pProgress) {
2252                // divide local progress into subprogress
2253                progress_t subprogress;
2254                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2255                // do the actual work
2256                pRIFF->Save(Path, &subprogress);
2257            } else
2258                pRIFF->Save(Path);
2259    
2260            UpdateFileOffsets();
2261    
2262            if (pProgress)
2263                __notify_progress(pProgress, 1.0); // notify done
2264      }      }
2265    
2266      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1305  namespace DLS { Line 2269  namespace DLS {
2269       * 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
2270       * have at the end of the saving process.       * have at the end of the saving process.
2271       *       *
2272       * @throws RIFF::Exception if any kind of IO error occured       * @param pProgress - optional: callback function for progress notification
2273       * @throws DLS::Exception  if any kind of DLS specific error occured       * @throws RIFF::Exception if any kind of IO error occurred
2274         * @throws DLS::Exception  if any kind of DLS specific error occurred
2275         */
2276        void File::Save(progress_t* pProgress) {
2277            // calculate number of tasks to notify progress appropriately
2278            const size_t nExtFiles = ExtensionFiles.size();
2279            const float tasks = 2.f + nExtFiles;
2280    
2281            // save extension files (if required)
2282            if (!ExtensionFiles.empty()) {
2283                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2284                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2285                    // save extension file
2286                    if (pProgress) {
2287                        // divide local progress into subprogress
2288                        progress_t subprogress;
2289                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2290                        // do the actual work
2291                        (*it)->Save(&subprogress);
2292                    } else
2293                        (*it)->Save();
2294                }
2295            }
2296    
2297            if (pProgress) {
2298                // divide local progress into subprogress
2299                progress_t subprogress;
2300                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2301                // do the actual work
2302                UpdateChunks(&subprogress);
2303            } else
2304                UpdateChunks(NULL);
2305    
2306            if (pProgress) {
2307                // divide local progress into subprogress
2308                progress_t subprogress;
2309                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2310                // do the actual work
2311                pRIFF->Save(&subprogress);
2312            } else
2313                pRIFF->Save();
2314    
2315            UpdateFileOffsets();
2316    
2317            if (pProgress)
2318                __notify_progress(pProgress, 1.0); // notify done
2319        }
2320    
2321        /** @brief Updates all file offsets stored all over the file.
2322         *
2323         * This virtual method is called whenever the overall file layout has been
2324         * changed (i.e. file or individual RIFF chunks have been resized). It is
2325         * then the responsibility of this method to update all file offsets stored
2326         * in the file format. For example samples are referenced by instruments by
2327         * file offsets. The gig format also stores references to instrument
2328         * scripts as file offsets, and thus it overrides this method to update
2329         * those file offsets as well.
2330       */       */
2331      void File::Save() {      void File::UpdateFileOffsets() {
         UpdateChunks();  
         pRIFF->Save();  
2332          __UpdateWavePoolTableChunk();          __UpdateWavePoolTableChunk();
2333      }      }
2334    
# Line 1348  namespace DLS { Line 2366  namespace DLS {
2366          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2367          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2368          // check if 'ptbl' chunk is large enough          // check if 'ptbl' chunk is large enough
2369          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2370          const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;          const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
2371          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
2372          // save the 'ptbl' chunk's current read/write position          // save the 'ptbl' chunk's current read/write position
2373          unsigned long ulOriginalPos = ptbl->GetPos();          file_offset_t ullOriginalPos = ptbl->GetPos();
2374          // update headers          // update headers
2375          ptbl->SetPos(0);          ptbl->SetPos(0);
2376          ptbl->WriteUint32(&WavePoolHeaderSize);          uint32_t tmp = WavePoolHeaderSize;
2377          ptbl->WriteUint32(&WavePoolCount);          ptbl->WriteUint32(&tmp);
2378            tmp = WavePoolCount;
2379            ptbl->WriteUint32(&tmp);
2380          // update offsets          // update offsets
2381          ptbl->SetPos(WavePoolHeaderSize);          ptbl->SetPos(WavePoolHeaderSize);
2382          if (b64BitWavePoolOffsets) {          if (b64BitWavePoolOffsets) {
2383              for (int i = 0 ; i < WavePoolCount ; i++) {              for (int i = 0 ; i < WavePoolCount ; i++) {
2384                  ptbl->WriteUint32(&pWavePoolTableHi[i]);                  tmp = pWavePoolTableHi[i];
2385                  ptbl->WriteUint32(&pWavePoolTable[i]);                  ptbl->WriteUint32(&tmp);
2386                    tmp = pWavePoolTable[i];
2387                    ptbl->WriteUint32(&tmp);
2388              }              }
2389          } else { // conventional 32 bit offsets          } else { // conventional 32 bit offsets
2390              for (int i = 0 ; i < WavePoolCount ; i++)              for (int i = 0 ; i < WavePoolCount ; i++) {
2391                  ptbl->WriteUint32(&pWavePoolTable[i]);                  tmp = pWavePoolTable[i];
2392                    ptbl->WriteUint32(&tmp);
2393                }
2394          }          }
2395          // restore 'ptbl' chunk's original read/write position          // restore 'ptbl' chunk's original read/write position
2396          ptbl->SetPos(ulOriginalPos);          ptbl->SetPos(ullOriginalPos);
2397      }      }
2398    
2399      /**      /**
# Line 1378  namespace DLS { Line 2402  namespace DLS {
2402       * exists already.       * exists already.
2403       */       */
2404      void File::__UpdateWavePoolTable() {      void File::__UpdateWavePoolTable() {
2405          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2406          // resize wave pool table arrays          // resize wave pool table arrays
2407          if (pWavePoolTable)   delete[] pWavePoolTable;          if (pWavePoolTable)   delete[] pWavePoolTable;
2408          if (pWavePoolTableHi) delete[] pWavePoolTableHi;          if (pWavePoolTableHi) delete[] pWavePoolTableHi;
2409          pWavePoolTable   = new uint32_t[WavePoolCount];          pWavePoolTable   = new uint32_t[WavePoolCount];
2410          pWavePoolTableHi = new uint32_t[WavePoolCount];          pWavePoolTableHi = new uint32_t[WavePoolCount];
2411          if (!pSamples) return;          if (!pSamples) return;
2412          // update offsets int wave pool table          // update offsets in wave pool table
2413          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2414          uint64_t wvplFileOffset = wvpl->GetFilePos();          uint64_t wvplFileOffset = wvpl->GetFilePos() -
2415          if (b64BitWavePoolOffsets) {                                    wvpl->GetPos(); // mandatory, since position might have changed
2416            if (!b64BitWavePoolOffsets) { // conventional 32 bit offsets (and no extension files) ...
2417              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
2418              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
2419              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
2420                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset =
2421                  (*iter)->ulWavePoolOffset = _64BitOffset;                      (*iter)->pWaveList->GetFilePos() -
2422                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);                      (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2423                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;                      wvplFileOffset -
2424              }                      LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2425          } 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;  
2426                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2427              }              }
2428            } else { // a) native 64 bit offsets without extension files or b) 32 bit offsets with extension files ...
2429                if (ExtensionFiles.empty()) { // native 64 bit offsets (and no extension files) [not compatible with GigaStudio] ...
2430                    SampleList::iterator iter = pSamples->begin();
2431                    SampleList::iterator end  = pSamples->end();
2432                    for (int i = 0 ; iter != end ; ++iter, i++) {
2433                        uint64_t _64BitOffset =
2434                            (*iter)->pWaveList->GetFilePos() -
2435                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2436                            wvplFileOffset -
2437                            LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2438                        (*iter)->ullWavePoolOffset = _64BitOffset;
2439                        pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
2440                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2441                    }
2442                } else { // 32 bit offsets with extension files (GigaStudio legacy support) ...
2443                    // the main gig and the extension files may contain wave data
2444                    std::vector<RIFF::File*> poolFiles;
2445                    poolFiles.push_back(pRIFF);
2446                    poolFiles.insert(poolFiles.end(), ExtensionFiles.begin(), ExtensionFiles.end());
2447    
2448                    RIFF::File* pCurPoolFile = NULL;
2449                    int fileNo = 0;
2450                    int waveOffset = 0;
2451                    SampleList::iterator iter = pSamples->begin();
2452                    SampleList::iterator end  = pSamples->end();
2453                    for (int i = 0 ; iter != end ; ++iter, i++) {
2454                        RIFF::File* pPoolFile = (*iter)->pWaveList->GetFile();
2455                        // if this sample is located in the same pool file as the
2456                        // last we reuse the previously computed fileNo and waveOffset
2457                        if (pPoolFile != pCurPoolFile) { // it is a different pool file than the last sample ...
2458                            pCurPoolFile = pPoolFile;
2459    
2460                            std::vector<RIFF::File*>::iterator sIter;
2461                            sIter = std::find(poolFiles.begin(), poolFiles.end(), pPoolFile);
2462                            if (sIter != poolFiles.end())
2463                                fileNo = std::distance(poolFiles.begin(), sIter);
2464                            else
2465                                throw DLS::Exception("Fatal error, unknown pool file");
2466    
2467                            RIFF::List* extWvpl = pCurPoolFile->GetSubList(LIST_TYPE_WVPL);
2468                            if (!extWvpl)
2469                                throw DLS::Exception("Fatal error, pool file has no 'wvpl' list chunk");
2470                            waveOffset =
2471                                extWvpl->GetFilePos() -
2472                                extWvpl->GetPos() + // mandatory, since position might have changed
2473                                LIST_HEADER_SIZE(pCurPoolFile->GetFileOffsetSize());
2474                        }
2475                        uint64_t _64BitOffset =
2476                            (*iter)->pWaveList->GetFilePos() -
2477                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2478                            waveOffset;
2479                        // pWavePoolTableHi stores file number when extension files are in use
2480                        pWavePoolTableHi[i] = (uint32_t) fileNo;
2481                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2482                        (*iter)->ullWavePoolOffset = _64BitOffset;
2483                    }
2484                }
2485          }          }
2486      }      }
2487    
2488    
   
2489  // *************** Exception ***************  // *************** Exception ***************
2490  // *  // *
2491    
2492      Exception::Exception(String Message) : RIFF::Exception(Message) {      Exception::Exception() : RIFF::Exception() {
2493        }
2494    
2495        Exception::Exception(String format, ...) : RIFF::Exception() {
2496            va_list arg;
2497            va_start(arg, format);
2498            Message = assemble(format, arg);
2499            va_end(arg);
2500        }
2501    
2502        Exception::Exception(String format, va_list arg) : RIFF::Exception() {
2503            Message = assemble(format, arg);
2504      }      }
2505    
2506      void Exception::PrintMessage() {      void Exception::PrintMessage() {

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

  ViewVC Help
Powered by ViewVC