/[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 834 by persson, Mon Feb 6 17:58:21 2006 UTC revision 3478 by schoenebeck, Thu Feb 21 20:10:08 2019 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-2019 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 210  namespace DLS { Line 235  namespace DLS {
235      /**      /**
236       * Apply all articulations to the respective RIFF chunks. You have to       * Apply all articulations to the respective RIFF chunks. You have to
237       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
238         *
239         * @param pProgress - callback function for progress notification
240       */       */
241      void Articulator::UpdateChunks() {      void Articulator::UpdateChunks(progress_t* pProgress) {
242          if (pArticulations) {          if (pArticulations) {
243              ArticulationList::iterator iter = pArticulations->begin();              ArticulationList::iterator iter = pArticulations->begin();
244              ArticulationList::iterator end  = pArticulations->end();              ArticulationList::iterator end  = pArticulations->end();
245              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
246                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
247              }              }
248          }          }
249      }      }
250    
251        /** @brief Remove all RIFF chunks associated with this Articulator object.
252         *
253         * See Storage::DeleteChunks() for details.
254         */
255        void Articulator::DeleteChunks() {
256            if (pArticulations) {
257                ArticulationList::iterator iter = pArticulations->begin();
258                ArticulationList::iterator end  = pArticulations->end();
259                for (; iter != end; ++iter) {
260                    (*iter)->DeleteChunks();
261                }
262            }
263        }
264    
265        /**
266         * Not yet implemented in this version, since the .gig format does
267         * not need to copy DLS articulators and so far nobody used pure
268         * DLS instrument AFAIK.
269         */
270        void Articulator::CopyAssign(const Articulator* orig) {
271            //TODO: implement deep copy assignment for this class
272        }
273    
274    
275    
276  // *************** Info  ***************  // *************** Info  ***************
# Line 228  namespace DLS { Line 278  namespace DLS {
278    
279      /** @brief Constructor.      /** @brief Constructor.
280       *       *
281       * Initializes the info strings with values provided by a INFO list chunk.       * Initializes the info strings with values provided by an INFO list chunk.
282       *       *
283       * @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
284       */       */
285      Info::Info(RIFF::List* list) {      Info::Info(RIFF::List* list) {
286            pFixedStringLengths = NULL;
287          pResourceListChunk = list;          pResourceListChunk = list;
288          if (list) {          if (list) {
289              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
# Line 253  namespace DLS { Line 304  namespace DLS {
304                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);
305                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);
306                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);
307                    LoadString(CHUNK_ID_ISBJ, lstINFO, Subject);
308              }              }
309          }          }
310      }      }
# Line 260  namespace DLS { Line 312  namespace DLS {
312      Info::~Info() {      Info::~Info() {
313      }      }
314    
315        /**
316         * Forces specific Info fields to be of a fixed length when being saved
317         * to a file. By default the respective RIFF chunk of an Info field
318         * will have a size analogue to its actual string length. With this
319         * method however this behavior can be overridden, allowing to force an
320         * arbitrary fixed size individually for each Info field.
321         *
322         * This method is used as a workaround for the gig format, not for DLS.
323         *
324         * @param lengths - NULL terminated array of string_length_t elements
325         */
326        void Info::SetFixedStringLengths(const string_length_t* lengths) {
327            pFixedStringLengths = lengths;
328        }
329    
330      /** @brief Load given INFO field.      /** @brief Load given INFO field.
331       *       *
332       * 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 267  namespace DLS { Line 334  namespace DLS {
334       */       */
335      void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {      void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
336          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
337          if (ck) {          ::LoadString(ck, s); // function from helper.h
             // TODO: no check for ZSTR terminated strings yet  
             s.assign((char*) ck->LoadChunkData(), ck->GetSize());  
             ck->ReleaseChunkData();  
         }  
338      }      }
339    
340      /** @brief Apply given INFO field to the respective chunk.      /** @brief Apply given INFO field to the respective chunk.
# Line 290  namespace DLS { Line 353  namespace DLS {
353       * @param sDefault - default value       * @param sDefault - default value
354       */       */
355      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) {
356          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);          int size = 0;
357          if (ck) { // if chunk exists already, use 's' as value          if (pFixedStringLengths) {
358              ck->Resize(s.size() + 1);              for (int i = 0 ; pFixedStringLengths[i].length ; i++) {
359              char* pData = (char*) ck->LoadChunkData();                  if (pFixedStringLengths[i].chunkId == ChunkID) {
360              memcpy(pData, s.c_str(), s.size() + 1);                      size = pFixedStringLengths[i].length;
361          } else if (s != "" || sDefault != "") { // create chunk                      break;
362              const String& sToSave = (s != "") ? s : sDefault;                  }
363              ck = lstINFO->AddSubChunk(ChunkID, sToSave.size() + 1);              }
             char* pData = (char*) ck->LoadChunkData();  
             memcpy(pData, sToSave.c_str(), sToSave.size() + 1);  
364          }          }
365            RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
366            ::SaveString(ChunkID, ck, lstINFO, s, sDefault, size != 0, size); // function from helper.h
367      }      }
368    
369      /** @brief Update chunks with current info values.      /** @brief Update chunks with current info values.
370       *       *
371       * Apply current INFO field values to the respective INFO chunks. You       * Apply current INFO field values to the respective INFO chunks. You
372       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
373         *
374         * @param pProgress - callback function for progress notification
375       */       */
376      void Info::UpdateChunks() {      void Info::UpdateChunks(progress_t* pProgress) {
377          if (!pResourceListChunk) return;          if (!pResourceListChunk) return;
378    
379          // make sure INFO list chunk exists          // make sure INFO list chunk exists
380          RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);          RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
         if (!lstINFO) lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);  
381    
382          // assemble default values in case the respective chunk is missing yet          String defaultName = "";
383          String defaultName = "NONAME";          String defaultCreationDate = "";
384          // get current date          String defaultSoftware = "";
385          time_t now = time(NULL);          String defaultComments = "";
386          tm* pNowBroken = localtime(&now);  
387          String defaultCreationDate = ToString(1900 + pNowBroken->tm_year) + "-" +          uint32_t resourceType = pResourceListChunk->GetListType();
388                                       ToString(pNowBroken->tm_mon + 1)  + "-" +  
389                                       ToString(pNowBroken->tm_mday);          if (!lstINFO) {
390          String defaultSoftware = libraryName() + " " + libraryVersion();              lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
391          String defaultComments = "Created with " + libraryName() + " " + libraryVersion();  
392                // assemble default values
393                defaultName = "NONAME";
394    
395                if (resourceType == RIFF_TYPE_DLS) {
396                    // get current date
397                    time_t now = time(NULL);
398                    tm* pNowBroken = localtime(&now);
399                    char buf[11];
400                    strftime(buf, 11, "%F", pNowBroken);
401                    defaultCreationDate = buf;
402    
403                    defaultComments = "Created with " + libraryName() + " " + libraryVersion();
404                }
405                if (resourceType == RIFF_TYPE_DLS || resourceType == LIST_TYPE_INS)
406                {
407                    defaultSoftware = libraryName() + " " + libraryVersion();
408                }
409            }
410    
411          // save values          // save values
412          SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);  
413          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
414          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
415            SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
416          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
         SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));  
417          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
418          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
419            SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
420          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
421          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);  
422          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
423            SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
424            SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
425            SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""));
426            SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
427          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
428          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
429          SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
430        }
431    
432        /** @brief Remove all RIFF chunks associated with this Info object.
433         *
434         * At the moment Info::DeleteChunks() does nothing. It is
435         * recommended to call this method explicitly though from deriving classes's
436         * own overridden implementation of this method to avoid potential future
437         * compatiblity issues.
438         *
439         * See Storage::DeleteChunks() for details.
440         */
441        void Info::DeleteChunks() {
442        }
443    
444        /**
445         * Make a deep copy of the Info object given by @a orig and assign it to
446         * this object.
447         *
448         * @param orig - original Info object to be copied from
449         */
450        void Info::CopyAssign(const Info* orig) {
451            Name = orig->Name;
452            ArchivalLocation = orig->ArchivalLocation;
453            CreationDate = orig->CreationDate;
454            Comments = orig->Comments;
455            Product = orig->Product;
456            Copyright = orig->Copyright;
457            Artists = orig->Artists;
458            Genre = orig->Genre;
459            Keywords = orig->Keywords;
460            Engineer = orig->Engineer;
461            Technician = orig->Technician;
462            Software = orig->Software;
463            Medium = orig->Medium;
464            Source = orig->Source;
465            SourceForm = orig->SourceForm;
466            Commissioned = orig->Commissioned;
467            Subject = orig->Subject;
468            //FIXME: hmm, is copying this pointer a good idea?
469            pFixedStringLengths = orig->pFixedStringLengths;
470      }      }
471    
472    
# Line 367  namespace DLS { Line 491  namespace DLS {
491    
492          RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);          RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);
493          if (ckDLSID) {          if (ckDLSID) {
494                ckDLSID->SetPos(0);
495    
496              pDLSID = new dlsid_t;              pDLSID = new dlsid_t;
497              ckDLSID->Read(&pDLSID->ulData1, 1, 4);              ckDLSID->Read(&pDLSID->ulData1, 1, 4);
498              ckDLSID->Read(&pDLSID->usData2, 1, 2);              ckDLSID->Read(&pDLSID->usData2, 1, 2);
# Line 381  namespace DLS { Line 507  namespace DLS {
507          if (pInfo)  delete pInfo;          if (pInfo)  delete pInfo;
508      }      }
509    
510        /** @brief Remove all RIFF chunks associated with this Resource object.
511         *
512         * At the moment Resource::DeleteChunks() does nothing. It is recommended
513         * to call this method explicitly though from deriving classes's own
514         * overridden implementation of this method to avoid potential future
515         * compatiblity issues.
516         *
517         * See Storage::DeleteChunks() for details.
518         */
519        void Resource::DeleteChunks() {
520        }
521    
522      /** @brief Update chunks with current Resource data.      /** @brief Update chunks with current Resource data.
523       *       *
524       * Apply Resource data persistently below the previously given resource       * Apply Resource data persistently below the previously given resource
# Line 388  namespace DLS { Line 526  namespace DLS {
526       * will not be applied at the moment (yet).       * will not be applied at the moment (yet).
527       *       *
528       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
529         *
530         * @param pProgress - callback function for progress notification
531       */       */
532      void Resource::UpdateChunks() {      void Resource::UpdateChunks(progress_t* pProgress) {
533          pInfo->UpdateChunks();          pInfo->UpdateChunks(pProgress);
534          //TODO: save DLSID  
535            if (pDLSID) {
536                // make sure 'dlid' chunk exists
537                RIFF::Chunk* ckDLSID = pResourceList->GetSubChunk(CHUNK_ID_DLID);
538                if (!ckDLSID) ckDLSID = pResourceList->AddSubChunk(CHUNK_ID_DLID, 16);
539                uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
540                // update 'dlid' chunk
541                store32(&pData[0], pDLSID->ulData1);
542                store16(&pData[4], pDLSID->usData2);
543                store16(&pData[6], pDLSID->usData3);
544                memcpy(&pData[8], pDLSID->abData, 8);
545            }
546      }      }
547    
548        /**
549         * Generates a new DLSID for the resource.
550         */
551        void Resource::GenerateDLSID() {
552            #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
553            if (!pDLSID) pDLSID = new dlsid_t;
554            GenerateDLSID(pDLSID);
555            #endif
556        }
557    
558        void Resource::GenerateDLSID(dlsid_t* pDLSID) {
559    #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
560    #ifdef WIN32
561            UUID uuid;
562            UuidCreate(&uuid);
563            pDLSID->ulData1 = uuid.Data1;
564            pDLSID->usData2 = uuid.Data2;
565            pDLSID->usData3 = uuid.Data3;
566            memcpy(pDLSID->abData, uuid.Data4, 8);
567    
568    #elif defined(__APPLE__)
569    
570            CFUUIDRef uuidRef = CFUUIDCreate(NULL);
571            CFUUIDBytes uuid = CFUUIDGetUUIDBytes(uuidRef);
572            CFRelease(uuidRef);
573            pDLSID->ulData1 = uuid.byte0 | uuid.byte1 << 8 | uuid.byte2 << 16 | uuid.byte3 << 24;
574            pDLSID->usData2 = uuid.byte4 | uuid.byte5 << 8;
575            pDLSID->usData3 = uuid.byte6 | uuid.byte7 << 8;
576            pDLSID->abData[0] = uuid.byte8;
577            pDLSID->abData[1] = uuid.byte9;
578            pDLSID->abData[2] = uuid.byte10;
579            pDLSID->abData[3] = uuid.byte11;
580            pDLSID->abData[4] = uuid.byte12;
581            pDLSID->abData[5] = uuid.byte13;
582            pDLSID->abData[6] = uuid.byte14;
583            pDLSID->abData[7] = uuid.byte15;
584    #else
585            uuid_t uuid;
586            uuid_generate(uuid);
587            pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24;
588            pDLSID->usData2 = uuid[4] | uuid[5] << 8;
589            pDLSID->usData3 = uuid[6] | uuid[7] << 8;
590            memcpy(pDLSID->abData, &uuid[8], 8);
591    #endif
592    #endif
593        }
594        
595        /**
596         * Make a deep copy of the Resource object given by @a orig and assign it
597         * to this object.
598         *
599         * @param orig - original Resource object to be copied from
600         */
601        void Resource::CopyAssign(const Resource* orig) {
602            pInfo->CopyAssign(orig->pInfo);
603        }
604    
605    
606  // *************** Sampler ***************  // *************** Sampler ***************
# Line 403  namespace DLS { Line 610  namespace DLS {
610          pParentList       = ParentList;          pParentList       = ParentList;
611          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
612          if (wsmp) {          if (wsmp) {
613                wsmp->SetPos(0);
614    
615              uiHeaderSize   = wsmp->ReadUint32();              uiHeaderSize   = wsmp->ReadUint32();
616              UnityNote      = wsmp->ReadUint16();              UnityNote      = wsmp->ReadUint16();
617              FineTune       = wsmp->ReadInt16();              FineTune       = wsmp->ReadInt16();
# Line 410  namespace DLS { Line 619  namespace DLS {
619              SamplerOptions = wsmp->ReadUint32();              SamplerOptions = wsmp->ReadUint32();
620              SampleLoops    = wsmp->ReadUint32();              SampleLoops    = wsmp->ReadUint32();
621          } else { // 'wsmp' chunk missing          } else { // 'wsmp' chunk missing
622              uiHeaderSize   = 0;              uiHeaderSize   = 20;
623              UnityNote      = 64;              UnityNote      = 60;
624              FineTune       = 0; // +- 0 cents              FineTune       = 0; // +- 0 cents
625              Gain           = 0; // 0 dB              Gain           = 0; // 0 dB
626              SamplerOptions = F_WSMP_NO_COMPRESSION;              SamplerOptions = F_WSMP_NO_COMPRESSION;
# Line 435  namespace DLS { Line 644  namespace DLS {
644          if (pSampleLoops) delete[] pSampleLoops;          if (pSampleLoops) delete[] pSampleLoops;
645      }      }
646    
647        void Sampler::SetGain(int32_t gain) {
648            Gain = gain;
649        }
650    
651      /**      /**
652       * Apply all sample player options to the respective RIFF chunk. You       * Apply all sample player options to the respective RIFF chunk. You
653       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
654         *
655         * @param pProgress - callback function for progress notification
656       */       */
657      void Sampler::UpdateChunks() {      void Sampler::UpdateChunks(progress_t* pProgress) {
658          // make sure 'wsmp' chunk exists          // make sure 'wsmp' chunk exists
659          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
660            int wsmpSize = uiHeaderSize + SampleLoops * 16;
661          if (!wsmp) {          if (!wsmp) {
662              uiHeaderSize = 20;              wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, wsmpSize);
663              wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, uiHeaderSize + SampleLoops * 16);          } else if (wsmp->GetSize() != wsmpSize) {
664                wsmp->Resize(wsmpSize);
665          }          }
666          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
667          // update headers size          // update headers size
668          memccpy(&pData[0], &uiHeaderSize, 1, 4);          store32(&pData[0], uiHeaderSize);
669          // update respective sampler options bits          // update respective sampler options bits
670          SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION          SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
671                                                     : SamplerOptions & (~F_WSMP_NO_TRUNCATION);                                                     : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
672          SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION          SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
673                                                 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);                                                 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
674            store16(&pData[4], UnityNote);
675            store16(&pData[6], FineTune);
676            store32(&pData[8], Gain);
677            store32(&pData[12], SamplerOptions);
678            store32(&pData[16], SampleLoops);
679          // update loop definitions          // update loop definitions
680          for (uint32_t i = 0; i < SampleLoops; i++) {          for (uint32_t i = 0; i < SampleLoops; i++) {
681              //FIXME: this does not handle extended loop structs correctly              //FIXME: this does not handle extended loop structs correctly
682              memccpy(&pData[uiHeaderSize + i * 16], pSampleLoops + i, 4, 4);              store32(&pData[uiHeaderSize + i * 16], pSampleLoops[i].Size);
683                store32(&pData[uiHeaderSize + i * 16 + 4], pSampleLoops[i].LoopType);
684                store32(&pData[uiHeaderSize + i * 16 + 8], pSampleLoops[i].LoopStart);
685                store32(&pData[uiHeaderSize + i * 16 + 12], pSampleLoops[i].LoopLength);
686          }          }
687      }      }
688    
689        /** @brief Remove all RIFF chunks associated with this Sampler object.
690         *
691         * At the moment Sampler::DeleteChunks() does nothing. It is
692         * recommended to call this method explicitly though from deriving classes's
693         * own overridden implementation of this method to avoid potential future
694         * compatiblity issues.
695         *
696         * See Storage::DeleteChunks() for details.
697         */
698        void Sampler::DeleteChunks() {
699        }
700    
701        /**
702         * Adds a new sample loop with the provided loop definition.
703         *
704         * @param pLoopDef - points to a loop definition that is to be copied
705         */
706        void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {
707            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
708            // copy old loops array
709            for (int i = 0; i < SampleLoops; i++) {
710                pNewLoops[i] = pSampleLoops[i];
711            }
712            // add the new loop
713            pNewLoops[SampleLoops] = *pLoopDef;
714            // auto correct size field
715            pNewLoops[SampleLoops].Size = sizeof(DLS::sample_loop_t);
716            // free the old array and update the member variables
717            if (SampleLoops) delete[] pSampleLoops;
718            pSampleLoops = pNewLoops;
719            SampleLoops++;
720        }
721    
722        /**
723         * Deletes an existing sample loop.
724         *
725         * @param pLoopDef - pointer to existing loop definition
726         * @throws Exception - if given loop definition does not exist
727         */
728        void Sampler::DeleteSampleLoop(sample_loop_t* pLoopDef) {
729            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1];
730            // copy old loops array (skipping given loop)
731            for (int i = 0, o = 0; i < SampleLoops; i++) {
732                if (&pSampleLoops[i] == pLoopDef) continue;
733                if (o == SampleLoops - 1) {
734                    delete[] pNewLoops;
735                    throw Exception("Could not delete Sample Loop, because it does not exist");
736                }
737                pNewLoops[o] = pSampleLoops[i];
738                o++;
739            }
740            // free the old array and update the member variables
741            if (SampleLoops) delete[] pSampleLoops;
742            pSampleLoops = pNewLoops;
743            SampleLoops--;
744        }
745        
746        /**
747         * Make a deep copy of the Sampler object given by @a orig and assign it
748         * to this object.
749         *
750         * @param orig - original Sampler object to be copied from
751         */
752        void Sampler::CopyAssign(const Sampler* orig) {
753            // copy trivial scalars
754            UnityNote = orig->UnityNote;
755            FineTune = orig->FineTune;
756            Gain = orig->Gain;
757            NoSampleDepthTruncation = orig->NoSampleDepthTruncation;
758            NoSampleCompression = orig->NoSampleCompression;
759            SamplerOptions = orig->SamplerOptions;
760            
761            // copy sample loops
762            if (SampleLoops) delete[] pSampleLoops;
763            pSampleLoops = new sample_loop_t[orig->SampleLoops];
764            memcpy(pSampleLoops, orig->pSampleLoops, orig->SampleLoops * sizeof(sample_loop_t));
765            SampleLoops = orig->SampleLoops;
766        }
767    
768    
769  // *************** Sample ***************  // *************** Sample ***************
# Line 481  namespace DLS { Line 784  namespace DLS {
784       * @param WavePoolOffset - offset of this sample data from wave pool       * @param WavePoolOffset - offset of this sample data from wave pool
785       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
786       */       */
787      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) {
788          pWaveList = waveList;          pWaveList = waveList;
789          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;          ullWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE(waveList->GetFile()->GetFileOffsetSize());
790          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
791          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);
792          if (pCkFormat) {          if (pCkFormat) {
793                pCkFormat->SetPos(0);
794    
795              // common fields              // common fields
796              FormatTag              = pCkFormat->ReadUint16();              FormatTag              = pCkFormat->ReadUint16();
797              Channels               = pCkFormat->ReadUint16();              Channels               = pCkFormat->ReadUint16();
# Line 494  namespace DLS { Line 799  namespace DLS {
799              AverageBytesPerSecond  = pCkFormat->ReadUint32();              AverageBytesPerSecond  = pCkFormat->ReadUint32();
800              BlockAlign             = pCkFormat->ReadUint16();              BlockAlign             = pCkFormat->ReadUint16();
801              // PCM format specific              // PCM format specific
802              if (FormatTag == WAVE_FORMAT_PCM) {              if (FormatTag == DLS_WAVE_FORMAT_PCM) {
803                  BitDepth     = pCkFormat->ReadUint16();                  BitDepth     = pCkFormat->ReadUint16();
804                  FrameSize    = (FormatTag == WAVE_FORMAT_PCM) ? (BitDepth / 8) * Channels                  FrameSize    = (BitDepth / 8) * Channels;
                                                             : 0;  
805              } else { // unsupported sample data format              } else { // unsupported sample data format
806                  BitDepth     = 0;                  BitDepth     = 0;
807                  FrameSize    = 0;                  FrameSize    = 0;
808              }              }
809          } else { // 'fmt' chunk missing          } else { // 'fmt' chunk missing
810              FormatTag              = WAVE_FORMAT_PCM;              FormatTag              = DLS_WAVE_FORMAT_PCM;
811              BitDepth               = 16;              BitDepth               = 16;
812              Channels               = 1;              Channels               = 1;
813              SamplesPerSecond       = 44100;              SamplesPerSecond       = 44100;
# Line 511  namespace DLS { Line 815  namespace DLS {
815              FrameSize              = (BitDepth / 8) * Channels;              FrameSize              = (BitDepth / 8) * Channels;
816              BlockAlign             = FrameSize;              BlockAlign             = FrameSize;
817          }          }
818          SamplesTotal = (pCkData) ? (FormatTag == WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize          SamplesTotal = (pCkData) ? (FormatTag == DLS_WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
819                                                                    : 0                                                                        : 0
820                                   : 0;                                   : 0;
821      }      }
822    
823      /** @brief Destructor.      /** @brief Destructor.
824       *       *
825       * Removes RIFF chunks associated with this Sample and frees all       * Frees all memory occupied by this sample.
      * memory occupied by this sample.  
826       */       */
827      Sample::~Sample() {      Sample::~Sample() {
828          RIFF::List* pParent = pWaveList->GetParent();          if (pCkData)
829          pParent->DeleteSubChunk(pWaveList);              pCkData->ReleaseChunkData();
830            if (pCkFormat)
831                pCkFormat->ReleaseChunkData();
832        }
833    
834        /** @brief Remove all RIFF chunks associated with this Sample object.
835         *
836         * See Storage::DeleteChunks() for details.
837         */
838        void Sample::DeleteChunks() {
839            // handle base class
840            Resource::DeleteChunks();
841    
842            // handle own RIFF chunks
843            if (pWaveList) {
844                RIFF::List* pParent = pWaveList->GetParent();
845                pParent->DeleteSubChunk(pWaveList);
846                pWaveList = NULL;
847            }
848        }
849    
850        /**
851         * Make a deep copy of the Sample object given by @a orig (without the
852         * actual sample waveform data however) and assign it to this object.
853         *
854         * This is a special internal variant of CopyAssign() which only copies the
855         * most mandatory member variables. It will be called by gig::Sample
856         * descendent instead of CopyAssign() since gig::Sample has its own
857         * implementation to access and copy the actual sample waveform data.
858         *
859         * @param orig - original Sample object to be copied from
860         */
861        void Sample::CopyAssignCore(const Sample* orig) {
862            // handle base classes
863            Resource::CopyAssign(orig);
864            // handle actual own attributes of this class
865            FormatTag = orig->FormatTag;
866            Channels = orig->Channels;
867            SamplesPerSecond = orig->SamplesPerSecond;
868            AverageBytesPerSecond = orig->AverageBytesPerSecond;
869            BlockAlign = orig->BlockAlign;
870            BitDepth = orig->BitDepth;
871            SamplesTotal = orig->SamplesTotal;
872            FrameSize = orig->FrameSize;
873        }
874        
875        /**
876         * Make a deep copy of the Sample object given by @a orig and assign it to
877         * this object.
878         *
879         * @param orig - original Sample object to be copied from
880         */
881        void Sample::CopyAssign(const Sample* orig) {
882            CopyAssignCore(orig);
883            
884            // copy sample waveform data (reading directly from disc)
885            Resize(orig->GetSize());
886            char* buf = (char*) LoadSampleData();
887            Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
888            const file_offset_t restorePos = pOrig->pCkData->GetPos();
889            pOrig->SetPos(0);
890            for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
891                const int iReadAtOnce = 64*1024;
892                file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
893                n = pOrig->Read(&buf[i], n);
894                if (!n) break;
895                todo -= n;
896                i += (n * pOrig->FrameSize);
897            }
898            pOrig->pCkData->SetPos(restorePos);
899      }      }
900    
901      /** @brief Load sample data into RAM.      /** @brief Load sample data into RAM.
# Line 572  namespace DLS { Line 944  namespace DLS {
944       * the RIFF chunk which encapsulates the sample's wave data. The       * the RIFF chunk which encapsulates the sample's wave data. The
945       * returned value is dependant to the current FrameSize value.       * returned value is dependant to the current FrameSize value.
946       *       *
947       * @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
948       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
949       */       */
950      unsigned long Sample::GetSize() {      file_offset_t Sample::GetSize() const {
951          if (FormatTag != WAVE_FORMAT_PCM) return 0;          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
952          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
953      }      }
954    
# Line 598  namespace DLS { Line 970  namespace DLS {
970       * calling File::Save() as this might exceed the current sample's       * calling File::Save() as this might exceed the current sample's
971       * boundary!       * boundary!
972       *       *
973       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
974       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
975       * other formats will fail!       * other formats will fail!
976       *       *
977       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
978       *                   greater than zero)       *                  greater than zero)
979       * @throws Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM
980       * @throws Exception if \a iNewSize is less than 1       * @throws Exception if \a NewSize is less than 1 or unrealistic large
981       * @see File::Save(), FrameSize, FormatTag       * @see File::Save(), FrameSize, FormatTag
982       */       */
983      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
984          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");
985          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");
986          const int iSizeInBytes = iNewSize * FrameSize;          if ((NewSize >> 48) != 0)
987                throw Exception("Unrealistic high DLS sample size detected");
988            const file_offset_t sizeInBytes = NewSize * FrameSize;
989          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
990          if (pCkData) pCkData->Resize(iSizeInBytes);          if (pCkData) pCkData->Resize(sizeInBytes);
991          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, sizeInBytes);
992      }      }
993    
994      /**      /**
# Line 622  namespace DLS { Line 996  namespace DLS {
996       * 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
997       * the sample into RAM, thus for disk streaming.       * the sample into RAM, thus for disk streaming.
998       *       *
999       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
1000       * FormatTag must be WAVE_FORMAT_PCM. Trying to reposition the sample       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to reposition the sample
1001       * with other formats will fail!       * with other formats will fail!
1002       *       *
1003       * @param SampleCount  number of sample points       * @param SampleCount  number of sample points
1004       * @param Whence       to which relation \a SampleCount refers to       * @param Whence       to which relation \a SampleCount refers to
1005       * @returns new position within the sample, 0 if       * @returns new position within the sample, 0 if
1006       *          FormatTag != WAVE_FORMAT_PCM       *          FormatTag != DLS_WAVE_FORMAT_PCM
1007       * @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
1008       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
1009       */       */
1010      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) {
1011          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
1012          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");
1013          unsigned long orderedBytes = SampleCount * FrameSize;          file_offset_t orderedBytes = SampleCount * FrameSize;
1014          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
1015          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
1016                                          : result / FrameSize;                                          : result / FrameSize;
1017      }      }
# Line 651  namespace DLS { Line 1025  namespace DLS {
1025       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1026       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1027       */       */
1028      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
1029          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
1030          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?
1031      }      }
1032    
# Line 671  namespace DLS { Line 1045  namespace DLS {
1045       * @throws Exception if current sample size is too small       * @throws Exception if current sample size is too small
1046       * @see LoadSampleData()       * @see LoadSampleData()
1047       */       */
1048      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1049          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
1050          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");
1051          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?
1052      }      }
# Line 681  namespace DLS { Line 1055  namespace DLS {
1055       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
1056       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
1057       *       *
1058       * @throws Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @param pProgress - callback function for progress notification
1059         * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
1060       *                   was provided yet       *                   was provided yet
1061       */       */
1062      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
1063          if (FormatTag != WAVE_FORMAT_PCM)          if (FormatTag != DLS_WAVE_FORMAT_PCM)
1064              throw Exception("Could not save sample, only PCM format is supported");              throw Exception("Could not save sample, only PCM format is supported");
1065          // 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
1066          if (!pCkData)          if (!pCkData)
1067              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");
1068          // update chunks of base class as well          // update chunks of base class as well
1069          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1070          // make sure 'fmt' chunk exists          // make sure 'fmt' chunk exists
1071          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
1072          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
1073          uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
1074          // update 'fmt' chunk          // update 'fmt' chunk
1075          memccpy(&pData[0], &FormatTag, 1, 2);          store16(&pData[0], FormatTag);
1076          memccpy(&pData[2], &Channels,  1, 2);          store16(&pData[2], Channels);
1077          memccpy(&pData[4], &SamplesPerSecond, 1, 4);          store32(&pData[4], SamplesPerSecond);
1078          memccpy(&pData[8], &AverageBytesPerSecond, 1, 4);          store32(&pData[8], AverageBytesPerSecond);
1079          memccpy(&pData[12], &BlockAlign, 1, 2);          store16(&pData[12], BlockAlign);
1080          memccpy(&pData[14], &BitDepth, 1, 2); // assuming PCM format          store16(&pData[14], BitDepth); // assuming PCM format
1081      }      }
1082    
1083    
# Line 713  namespace DLS { Line 1088  namespace DLS {
1088      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) {
1089          pCkRegion = rgnList;          pCkRegion = rgnList;
1090    
1091          // articulation informations          // articulation information
1092          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
1093          if (rgnh) {          if (rgnh) {
1094                rgnh->SetPos(0);
1095    
1096              rgnh->Read(&KeyRange, 2, 2);              rgnh->Read(&KeyRange, 2, 2);
1097              rgnh->Read(&VelocityRange, 2, 2);              rgnh->Read(&VelocityRange, 2, 2);
1098              FormatOptionFlags = rgnh->ReadUint16();              FormatOptionFlags = rgnh->ReadUint16();
# Line 735  namespace DLS { Line 1112  namespace DLS {
1112          }          }
1113          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
1114    
1115          // sample informations          // sample information
1116          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
1117          if (wlnk) {          if (wlnk) {
1118                wlnk->SetPos(0);
1119    
1120              WaveLinkOptionFlags = wlnk->ReadUint16();              WaveLinkOptionFlags = wlnk->ReadUint16();
1121              PhaseGroup          = wlnk->ReadUint16();              PhaseGroup          = wlnk->ReadUint16();
1122              Channel             = wlnk->ReadUint32();              Channel             = wlnk->ReadUint32();
# Line 756  namespace DLS { Line 1135  namespace DLS {
1135    
1136      /** @brief Destructor.      /** @brief Destructor.
1137       *       *
1138       * Removes RIFF chunks associated with this Region.       * Intended to free up all memory occupied by this Region object. ATM this
1139         * destructor implementation does nothing though.
1140       */       */
1141      Region::~Region() {      Region::~Region() {
1142          RIFF::List* pParent = pCkRegion->GetParent();      }
1143          pParent->DeleteSubChunk(pCkRegion);  
1144        /** @brief Remove all RIFF chunks associated with this Region object.
1145         *
1146         * See Storage::DeleteChunks() for details.
1147         */
1148        void Region::DeleteChunks() {
1149            // handle base classes
1150            Resource::DeleteChunks();
1151            Articulator::DeleteChunks();
1152            Sampler::DeleteChunks();
1153    
1154            // handle own RIFF chunks
1155            if (pCkRegion) {
1156                RIFF::List* pParent = pCkRegion->GetParent();
1157                pParent->DeleteSubChunk(pCkRegion);
1158                pCkRegion = NULL;
1159            }
1160      }      }
1161    
1162      Sample* Region::GetSample() {      Sample* Region::GetSample() {
1163          if (pSample) return pSample;          if (pSample) return pSample;
1164          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1165          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1166          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample();
1167          while (sample) {          while (sample) {
1168              if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);              if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1169              sample = file->GetNextSample();              sample = file->GetNextSample();
1170          }          }
1171          return NULL;          return NULL;
# Line 786  namespace DLS { Line 1182  namespace DLS {
1182      }      }
1183    
1184      /**      /**
1185         * Modifies the key range of this Region and makes sure the respective
1186         * chunks are in correct order.
1187         *
1188         * @param Low  - lower end of key range
1189         * @param High - upper end of key range
1190         */
1191        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
1192            KeyRange.low  = Low;
1193            KeyRange.high = High;
1194    
1195            // make sure regions are already loaded
1196            Instrument* pInstrument = (Instrument*) GetParent();
1197            if (!pInstrument->pRegions) pInstrument->LoadRegions();
1198            if (!pInstrument->pRegions) return;
1199    
1200            // find the r which is the first one to the right of this region
1201            // at its new position
1202            Region* r = NULL;
1203            Region* prev_region = NULL;
1204            for (
1205                Instrument::RegionList::iterator iter = pInstrument->pRegions->begin();
1206                iter != pInstrument->pRegions->end(); iter++
1207            ) {
1208                if ((*iter)->KeyRange.low > this->KeyRange.low) {
1209                    r = *iter;
1210                    break;
1211                }
1212                prev_region = *iter;
1213            }
1214    
1215            // place this region before r if it's not already there
1216            if (prev_region != this) pInstrument->MoveRegion(this, r);
1217        }
1218    
1219        /**
1220       * Apply Region settings to the respective RIFF chunks. You have to       * Apply Region settings to the respective RIFF chunks. You have to
1221       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
1222       *       *
1223         * @param pProgress - callback function for progress notification
1224       * @throws Exception - if the Region's sample could not be found       * @throws Exception - if the Region's sample could not be found
1225       */       */
1226      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
1227          // make sure 'rgnh' chunk exists          // make sure 'rgnh' chunk exists
1228          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1229          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, 14);          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
1230          uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();          uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
1231          FormatOptionFlags = (SelfNonExclusive)          FormatOptionFlags = (SelfNonExclusive)
1232                                  ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE                                  ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
1233                                  : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);                                  : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
1234          // update 'rgnh' chunk          // update 'rgnh' chunk
1235          memccpy(&pData[0], &KeyRange, 2, 2);          store16(&pData[0], KeyRange.low);
1236          memccpy(&pData[4], &VelocityRange, 2, 2);          store16(&pData[2], KeyRange.high);
1237          memccpy(&pData[8], &FormatOptionFlags, 1, 2);          store16(&pData[4], VelocityRange.low);
1238          memccpy(&pData[10], &KeyGroup, 1, 2);          store16(&pData[6], VelocityRange.high);
1239          memccpy(&pData[12], &Layer, 1, 2);          store16(&pData[8], FormatOptionFlags);
1240            store16(&pData[10], KeyGroup);
1241          // update chunks of base classes as well          if (rgnh->GetSize() >= 14) store16(&pData[12], Layer);
1242          Resource::UpdateChunks();  
1243          Articulator::UpdateChunks();          // update chunks of base classes as well (but skip Resource,
1244          Sampler::UpdateChunks();          // as a rgn doesn't seem to have dlid and INFO chunks)
1245            Articulator::UpdateChunks(pProgress);
1246            Sampler::UpdateChunks(pProgress);
1247    
1248          // make sure 'wlnk' chunk exists          // make sure 'wlnk' chunk exists
1249          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
# Line 834  namespace DLS { Line 1268  namespace DLS {
1268                  }                  }
1269              }              }
1270          }          }
         if (index < 0) throw Exception("Could not save Region, could not find Region's sample");  
1271          WavePoolTableIndex = index;          WavePoolTableIndex = index;
1272          // update 'wlnk' chunk          // update 'wlnk' chunk
1273          memccpy(&pData[0], &WaveLinkOptionFlags, 1, 2);          store16(&pData[0], WaveLinkOptionFlags);
1274          memccpy(&pData[2], &PhaseGroup, 1, 2);          store16(&pData[2], PhaseGroup);
1275          memccpy(&pData[4], &Channel, 1, 4);          store32(&pData[4], Channel);
1276          memccpy(&pData[8], &WavePoolTableIndex, 1, 4);          store32(&pData[8], WavePoolTableIndex);
1277        }
1278        
1279        /**
1280         * Make a (semi) deep copy of the Region object given by @a orig and assign
1281         * it to this object.
1282         *
1283         * Note that the sample pointer referenced by @a orig is simply copied as
1284         * memory address. Thus the respective sample is shared, not duplicated!
1285         *
1286         * @param orig - original Region object to be copied from
1287         */
1288        void Region::CopyAssign(const Region* orig) {
1289            // handle base classes
1290            Resource::CopyAssign(orig);
1291            Articulator::CopyAssign(orig);
1292            Sampler::CopyAssign(orig);
1293            // handle actual own attributes of this class
1294            // (the trivial ones)
1295            VelocityRange = orig->VelocityRange;
1296            KeyGroup = orig->KeyGroup;
1297            Layer = orig->Layer;
1298            SelfNonExclusive = orig->SelfNonExclusive;
1299            PhaseMaster = orig->PhaseMaster;
1300            PhaseGroup = orig->PhaseGroup;
1301            MultiChannel = orig->MultiChannel;
1302            Channel = orig->Channel;
1303            // only take the raw sample reference if the two Region objects are
1304            // part of the same file
1305            if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1306                WavePoolTableIndex = orig->WavePoolTableIndex;
1307                pSample = orig->pSample;
1308            } else {
1309                WavePoolTableIndex = -1;
1310                pSample = NULL;
1311            }
1312            FormatOptionFlags = orig->FormatOptionFlags;
1313            WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1314            // handle the last, a bit sensible attribute
1315            SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1316      }      }
   
1317    
1318    
1319  // *************** Instrument ***************  // *************** Instrument ***************
# Line 867  namespace DLS { Line 1338  namespace DLS {
1338          midi_locale_t locale;          midi_locale_t locale;
1339          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1340          if (insh) {          if (insh) {
1341                insh->SetPos(0);
1342    
1343              Regions = insh->ReadUint32();              Regions = insh->ReadUint32();
1344              insh->Read(&locale, 2, 4);              insh->Read(&locale, 2, 4);
1345          } else { // 'insh' chunk missing          } else { // 'insh' chunk missing
# Line 919  namespace DLS { Line 1392  namespace DLS {
1392          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1393          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
1394          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
1395          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1396          return pNewRegion;          return pNewRegion;
1397      }      }
1398    
1399        void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1400            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1401            lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1402    
1403            pRegions->remove(pSrc);
1404            RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
1405            pRegions->insert(iter, pSrc);
1406        }
1407    
1408      void Instrument::DeleteRegion(Region* pRegion) {      void Instrument::DeleteRegion(Region* pRegion) {
1409          if (!pRegions) return;          if (!pRegions) return;
1410          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1411          if (iter == pRegions->end()) return;          if (iter == pRegions->end()) return;
1412          pRegions->erase(iter);          pRegions->erase(iter);
1413          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1414            pRegion->DeleteChunks();
1415          delete pRegion;          delete pRegion;
1416      }      }
1417    
# Line 936  namespace DLS { Line 1419  namespace DLS {
1419       * Apply Instrument with all its Regions to the respective RIFF chunks.       * Apply Instrument with all its Regions to the respective RIFF chunks.
1420       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
1421       *       *
1422         * @param pProgress - callback function for progress notification
1423       * @throws Exception - on errors       * @throws Exception - on errors
1424       */       */
1425      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
1426          // first update base classes' chunks          // first update base classes' chunks
1427          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1428          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1429          // make sure 'insh' chunk exists          // make sure 'insh' chunk exists
1430          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1431          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1432          uint8_t* pData = (uint8_t*) insh->LoadChunkData();          uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1433          // update 'insh' chunk          // update 'insh' chunk
1434          Regions = (pRegions) ? pRegions->size() : 0;          Regions = (pRegions) ? uint32_t(pRegions->size()) : 0;
1435          midi_locale_t locale;          midi_locale_t locale;
1436          locale.instrument = MIDIProgram;          locale.instrument = MIDIProgram;
1437          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
1438          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);
1439          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
1440          memccpy(&pData[0], &Regions, 1, 4);          store32(&pData[0], Regions);
1441          memccpy(&pData[4], &locale, 2, 4);          store32(&pData[4], locale.bank);
1442            store32(&pData[8], locale.instrument);
1443          // update Region's chunks          // update Region's chunks
1444          if (!pRegions) return;          if (!pRegions) return;
1445          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
1446          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
1447          for (; iter != end; ++iter) {          for (int i = 0; iter != end; ++iter, ++i) {
1448              (*iter)->UpdateChunks();              // divide local progress into subprogress
1449                progress_t subprogress;
1450                __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1451                // do the actual work
1452                (*iter)->UpdateChunks(&subprogress);
1453          }          }
1454            __notify_progress(pProgress, 1.0); // notify done
1455      }      }
1456    
1457      /** @brief Destructor.      /** @brief Destructor.
1458       *       *
1459       * Removes RIFF chunks associated with this Instrument and frees all       * Frees all memory occupied by this instrument.
      * memory occupied by this instrument.  
1460       */       */
1461      Instrument::~Instrument() {      Instrument::~Instrument() {
1462          if (pRegions) {          if (pRegions) {
# Line 979  namespace DLS { Line 1468  namespace DLS {
1468              }              }
1469              delete pRegions;              delete pRegions;
1470          }          }
         // remove instrument's chunks  
         RIFF::List* pParent = pCkInstrument->GetParent();  
         pParent->DeleteSubChunk(pCkInstrument);  
1471      }      }
1472    
1473        /** @brief Remove all RIFF chunks associated with this Instrument object.
1474         *
1475         * See Storage::DeleteChunks() for details.
1476         */
1477        void Instrument::DeleteChunks() {
1478            // handle base classes
1479            Resource::DeleteChunks();
1480            Articulator::DeleteChunks();
1481    
1482            // handle RIFF chunks of members
1483            if (pRegions) {
1484                RegionList::iterator it  = pRegions->begin();
1485                RegionList::iterator end = pRegions->end();
1486                for (; it != end; ++it)
1487                    (*it)->DeleteChunks();
1488            }
1489    
1490            // handle own RIFF chunks
1491            if (pCkInstrument) {
1492                RIFF::List* pParent = pCkInstrument->GetParent();
1493                pParent->DeleteSubChunk(pCkInstrument);
1494                pCkInstrument = NULL;
1495            }
1496        }
1497    
1498        void Instrument::CopyAssignCore(const Instrument* orig) {
1499            // handle base classes
1500            Resource::CopyAssign(orig);
1501            Articulator::CopyAssign(orig);
1502            // handle actual own attributes of this class
1503            // (the trivial ones)
1504            IsDrum = orig->IsDrum;
1505            MIDIBank = orig->MIDIBank;
1506            MIDIBankCoarse = orig->MIDIBankCoarse;
1507            MIDIBankFine = orig->MIDIBankFine;
1508            MIDIProgram = orig->MIDIProgram;
1509        }
1510        
1511        /**
1512         * Make a (semi) deep copy of the Instrument object given by @a orig and assign
1513         * it to this object.
1514         *
1515         * Note that all sample pointers referenced by @a orig are simply copied as
1516         * memory address. Thus the respective samples are shared, not duplicated!
1517         *
1518         * @param orig - original Instrument object to be copied from
1519         */
1520        void Instrument::CopyAssign(const Instrument* orig) {
1521            CopyAssignCore(orig);
1522            // delete all regions first
1523            while (Regions) DeleteRegion(GetFirstRegion());
1524            // now recreate and copy regions
1525            {
1526                RegionList::const_iterator it = orig->pRegions->begin();
1527                for (int i = 0; i < orig->Regions; ++i, ++it) {
1528                    Region* dstRgn = AddRegion();
1529                    //NOTE: Region does semi-deep copy !
1530                    dstRgn->CopyAssign(*it);
1531                }
1532            }
1533        }
1534    
1535    
1536  // *************** File ***************  // *************** File ***************
# Line 996  namespace DLS { Line 1543  namespace DLS {
1543       * a DLS file.       * a DLS file.
1544       */       */
1545      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1546            pRIFF->SetByteOrder(RIFF::endian_little);
1547            bOwningRiff = true;
1548          pVersion = new version_t;          pVersion = new version_t;
1549          pVersion->major   = 0;          pVersion->major   = 0;
1550          pVersion->minor   = 0;          pVersion->minor   = 0;
# Line 1026  namespace DLS { Line 1575  namespace DLS {
1575      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1576          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1577          this->pRIFF = pRIFF;          this->pRIFF = pRIFF;
1578            bOwningRiff = false;
1579          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1580          if (ckVersion) {          if (ckVersion) {
1581                ckVersion->SetPos(0);
1582    
1583              pVersion = new version_t;              pVersion = new version_t;
1584              ckVersion->Read(pVersion, 4, 2);              ckVersion->Read(pVersion, 4, 2);
1585          }          }
# Line 1036  namespace DLS { Line 1587  namespace DLS {
1587    
1588          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1589          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.");
1590            colh->SetPos(0);
1591          Instruments = colh->ReadUint32();          Instruments = colh->ReadUint32();
1592    
1593          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1594          if (!ptbl) throw DLS::Exception("Mandatory <ptbl> chunk not found.");          if (!ptbl) { // pool table is missing - this is probably an ".art" file
1595          WavePoolHeaderSize = ptbl->ReadUint32();              WavePoolCount    = 0;
1596          WavePoolCount  = ptbl->ReadUint32();              pWavePoolTable   = NULL;
1597          pWavePoolTable = new uint32_t[WavePoolCount];              pWavePoolTableHi = NULL;
1598          pWavePoolTableHi = new uint32_t[WavePoolCount];              WavePoolHeaderSize = 8;
1599          ptbl->SetPos(WavePoolHeaderSize);              b64BitWavePoolOffsets = false;
1600            } else {
1601          // Check for 64 bit offsets (used in gig v3 files)              ptbl->SetPos(0);
1602          b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);  
1603          if (b64BitWavePoolOffsets) {              WavePoolHeaderSize = ptbl->ReadUint32();
1604              for (int i = 0 ; i < WavePoolCount ; i++) {              WavePoolCount  = ptbl->ReadUint32();
1605                  pWavePoolTableHi[i] = ptbl->ReadUint32();              pWavePoolTable = new uint32_t[WavePoolCount];
1606                  pWavePoolTable[i] = ptbl->ReadUint32();              pWavePoolTableHi = new uint32_t[WavePoolCount];
1607                  if (pWavePoolTable[i] & 0x80000000)              ptbl->SetPos(WavePoolHeaderSize);
1608                      throw DLS::Exception("Files larger than 2 GB not yet supported");  
1609                // Check for 64 bit offsets (used in gig v3 files)
1610                b64BitWavePoolOffsets = (ptbl->GetSize() - WavePoolHeaderSize == WavePoolCount * 8);
1611                if (b64BitWavePoolOffsets) {
1612                    for (int i = 0 ; i < WavePoolCount ; i++) {
1613                        pWavePoolTableHi[i] = ptbl->ReadUint32();
1614                        pWavePoolTable[i] = ptbl->ReadUint32();
1615                        //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1616                        //if (pWavePoolTable[i] & 0x80000000)
1617                        //    throw DLS::Exception("Files larger than 2 GB not yet supported");
1618                    }
1619                } else { // conventional 32 bit offsets
1620                    ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
1621                    for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;
1622              }              }
         } else { // conventional 32 bit offsets  
             ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));  
             for (int i = 0 ; i < WavePoolCount ; i++) pWavePoolTableHi[i] = 0;  
1623          }          }
1624    
1625          pSamples     = NULL;          pSamples     = NULL;
# Line 1090  namespace DLS { Line 1652  namespace DLS {
1652          if (pVersion) delete pVersion;          if (pVersion) delete pVersion;
1653          for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)          for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)
1654              delete *i;              delete *i;
1655            if (bOwningRiff)
1656                delete pRIFF;
1657      }      }
1658    
1659      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
# Line 1109  namespace DLS { Line 1673  namespace DLS {
1673          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
1674          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1675          if (wvpl) {          if (wvpl) {
1676              unsigned long wvplFileOffset = wvpl->GetFilePos();              file_offset_t wvplFileOffset = wvpl->GetFilePos() -
1677                                               wvpl->GetPos(); // should be zero, but just to be sure
1678              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1679              while (wave) {              while (wave) {
1680                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1681                      unsigned long waveFileOffset = wave->GetFilePos();                      file_offset_t waveFileOffset = wave->GetFilePos() -
1682                                                       wave->GetPos(); // should be zero, but just to be sure
1683                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1684                  }                  }
1685                  wave = wvpl->GetNextSubList();                  wave = wvpl->GetNextSubList();
# Line 1122  namespace DLS { Line 1688  namespace DLS {
1688          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)
1689              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1690              if (dwpl) {              if (dwpl) {
1691                  unsigned long dwplFileOffset = dwpl->GetFilePos();                  file_offset_t dwplFileOffset = dwpl->GetFilePos() -
1692                                                   dwpl->GetPos(); // should be zero, but just to be sure
1693                  RIFF::List* wave = dwpl->GetFirstSubList();                  RIFF::List* wave = dwpl->GetFirstSubList();
1694                  while (wave) {                  while (wave) {
1695                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
1696                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos() -
1697                                                           wave->GetPos(); // should be zero, but just to be sure
1698                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1699                      }                      }
1700                      wave = dwpl->GetNextSubList();                      wave = dwpl->GetNextSubList();
# Line 1165  namespace DLS { Line 1733  namespace DLS {
1733          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1734          if (iter == pSamples->end()) return;          if (iter == pSamples->end()) return;
1735          pSamples->erase(iter);          pSamples->erase(iter);
1736            pSample->DeleteChunks();
1737          delete pSample;          delete pSample;
1738      }      }
1739    
# Line 1224  namespace DLS { Line 1793  namespace DLS {
1793          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1794          if (iter == pInstruments->end()) return;          if (iter == pInstruments->end()) return;
1795          pInstruments->erase(iter);          pInstruments->erase(iter);
1796            pInstrument->DeleteChunks();
1797          delete pInstrument;          delete pInstrument;
1798      }      }
1799    
1800      /**      /**
1801         * Returns extension file of given index. Extension files are used
1802         * sometimes to circumvent the 2 GB file size limit of the RIFF format and
1803         * of certain operating systems in general. In this case, instead of just
1804         * using one file, the content is spread among several files with similar
1805         * file name scheme. This is especially used by some GigaStudio sound
1806         * libraries.
1807         *
1808         * @param index - index of extension file
1809         * @returns sought extension file, NULL if index out of bounds
1810         * @see GetFileName()
1811         */
1812        RIFF::File* File::GetExtensionFile(int index) {
1813            if (index < 0 || index >= ExtensionFiles.size()) return NULL;
1814            std::list<RIFF::File*>::iterator iter = ExtensionFiles.begin();
1815            for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i)
1816                if (i == index) return *iter;
1817            return NULL;
1818        }
1819    
1820        /** @brief File name of this DLS file.
1821         *
1822         * This method returns the file name as it was provided when loading
1823         * the respective DLS file. However in case the File object associates
1824         * an empty, that is new DLS file, which was not yet saved to disk,
1825         * this method will return an empty string.
1826         *
1827         * @see GetExtensionFile()
1828         */
1829        String File::GetFileName() {
1830            return pRIFF->GetFileName();
1831        }
1832        
1833        /**
1834         * You may call this method store a future file name, so you don't have to
1835         * to pass it to the Save() call later on.
1836         */
1837        void File::SetFileName(const String& name) {
1838            pRIFF->SetFileName(name);
1839        }
1840    
1841        /**
1842       * Apply all the DLS file's current instruments, samples and settings to       * Apply all the DLS file's current instruments, samples and settings to
1843       * the respective RIFF chunks. You have to call Save() to make changes       * the respective RIFF chunks. You have to call Save() to make changes
1844       * persistent.       * persistent.
1845       *       *
1846         * @param pProgress - callback function for progress notification
1847       * @throws Exception - on errors       * @throws Exception - on errors
1848       */       */
1849      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
1850          // first update base class's chunks          // first update base class's chunks
1851          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1852    
1853          // if version struct exists, update 'vers' chunk          // if version struct exists, update 'vers' chunk
1854          if (pVersion) {          if (pVersion) {
1855              RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);              RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1856              if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);              if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1857              uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();              uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1858              memccpy(pData, pVersion, 2, 4);              store16(&pData[0], pVersion->minor);
1859                store16(&pData[2], pVersion->major);
1860                store16(&pData[4], pVersion->build);
1861                store16(&pData[6], pVersion->release);
1862          }          }
1863    
1864          // update 'colh' chunk          // update 'colh' chunk
1865          Instruments = (pInstruments) ? pInstruments->size() : 0;          Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
1866          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1867          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1868          uint8_t* pData = (uint8_t*) colh->LoadChunkData();          uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1869          memccpy(pData, &Instruments, 1, 4);          store32(pData, Instruments);
1870    
1871          // update instrument's chunks          // update instrument's chunks
1872          if (pInstruments) {          if (pInstruments) {
1873                // divide local progress into subprogress
1874                progress_t subprogress;
1875                __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1876    
1877                // do the actual work
1878              InstrumentList::iterator iter = pInstruments->begin();              InstrumentList::iterator iter = pInstruments->begin();
1879              InstrumentList::iterator end  = pInstruments->end();              InstrumentList::iterator end  = pInstruments->end();
1880              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1881                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1882                    progress_t subsubprogress;
1883                    __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
1884                    // do the actual work
1885                    (*iter)->UpdateChunks(&subsubprogress);
1886              }              }
1887    
1888                __notify_progress(&subprogress, 1.0); // notify subprogress done
1889          }          }
1890    
1891          // update 'ptbl' chunk          // update 'ptbl' chunk
1892          const int iSamples = (pSamples) ? pSamples->size() : 0;          const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
1893          const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1894          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1895          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*/);
1896          const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;          int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1897          ptbl->Resize(iPtblSize);          ptbl->Resize(iPtblSize);
1898          pData = (uint8_t*) ptbl->LoadChunkData();          pData = (uint8_t*) ptbl->LoadChunkData();
1899          WavePoolCount = iSamples;          WavePoolCount = iSamples;
1900          memccpy(&pData[4], &WavePoolCount, 1, 4);          store32(&pData[4], WavePoolCount);
1901          // 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()
1902          memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);          memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
1903    
1904          // update sample's chunks          // update sample's chunks
1905          if (pSamples) {          if (pSamples) {
1906                // divide local progress into subprogress
1907                progress_t subprogress;
1908                __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
1909    
1910                // do the actual work
1911              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1912              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1913              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1914                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1915                    progress_t subsubprogress;
1916                    __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
1917                    // do the actual work
1918                    (*iter)->UpdateChunks(&subsubprogress);
1919                }
1920    
1921                __notify_progress(&subprogress, 1.0); // notify subprogress done
1922            }
1923    
1924            // if there are any extension files, gather which ones are regular
1925            // extension files used as wave pool files (.gx00, .gx01, ... , .gx98)
1926            // and which one is probably a convolution (GigaPulse) file (always to
1927            // be saved as .gx99)
1928            std::list<RIFF::File*> poolFiles;  // < for (.gx00, .gx01, ... , .gx98) files
1929            RIFF::File* pGigaPulseFile = NULL; // < for .gx99 file
1930            if (!ExtensionFiles.empty()) {
1931                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
1932                for (; it != ExtensionFiles.end(); ++it) {
1933                    //FIXME: the .gx99 file is always used by GSt for convolution
1934                    // data (GigaPulse); so we should better detect by subchunk
1935                    // whether the extension file is intended for convolution
1936                    // instead of checkking for a file name, because the latter does
1937                    // not work for saving new gigs created from scratch
1938                    const std::string oldName = (*it)->GetFileName();
1939                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
1940                    if (isGigaPulseFile)
1941                        pGigaPulseFile = *it;
1942                    else
1943                        poolFiles.push_back(*it);
1944                }
1945            }
1946    
1947            // update the 'xfil' chunk which describes all extension files (wave
1948            // pool files) except the .gx99 file
1949            if (!poolFiles.empty()) {
1950                const int n = poolFiles.size();
1951                const int iHeaderSize = 4;
1952                const int iEntrySize = 144;
1953    
1954                // make sure chunk exists, and with correct size
1955                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
1956                if (ckXfil)
1957                    ckXfil->Resize(iHeaderSize + n * iEntrySize);
1958                else
1959                    ckXfil = pRIFF->AddSubChunk(CHUNK_ID_XFIL, iHeaderSize + n * iEntrySize);
1960    
1961                uint8_t* pData = (uint8_t*) ckXfil->LoadChunkData();
1962    
1963                // re-assemble the chunk's content
1964                store32(pData, n);
1965                std::list<RIFF::File*>::iterator itExtFile = poolFiles.begin();
1966                for (int i = 0, iOffset = 4; i < n;
1967                     ++itExtFile, ++i, iOffset += iEntrySize)
1968                {
1969                    // update the filename string and 5 byte extension of each extension file
1970                    std::string file = lastPathComponent(
1971                        (*itExtFile)->GetFileName()
1972                    );
1973                    if (file.length() + 6 > 128)
1974                        throw Exception("Fatal error, extension filename length exceeds 122 byte maximum");
1975                    uint8_t* pStrings = &pData[iOffset];
1976                    memset(pStrings, 0, 128);
1977                    memcpy(pStrings, file.c_str(), file.length());
1978                    pStrings += file.length() + 1;
1979                    std::string ext = file.substr(file.length()-5);
1980                    memcpy(pStrings, ext.c_str(), 5);
1981                    // update the dlsid of the extension file
1982                    uint8_t* pId = &pData[iOffset + 128];
1983                    dlsid_t id;
1984                    RIFF::Chunk* ckDLSID = (*itExtFile)->GetSubChunk(CHUNK_ID_DLID);
1985                    if (ckDLSID) {
1986                        ckDLSID->Read(&id.ulData1, 1, 4);
1987                        ckDLSID->Read(&id.usData2, 1, 2);
1988                        ckDLSID->Read(&id.usData3, 1, 2);
1989                        ckDLSID->Read(id.abData, 8, 1);
1990                    } else {
1991                        ckDLSID = (*itExtFile)->AddSubChunk(CHUNK_ID_DLID, 16);
1992                        Resource::GenerateDLSID(&id);
1993                        uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
1994                        store32(&pData[0], id.ulData1);
1995                        store16(&pData[4], id.usData2);
1996                        store16(&pData[6], id.usData3);
1997                        memcpy(&pData[8], id.abData, 8);
1998                    }
1999                    store32(&pId[0], id.ulData1);
2000                    store16(&pId[4], id.usData2);
2001                    store16(&pId[6], id.usData3);
2002                    memcpy(&pId[8], id.abData, 8);
2003                }
2004            } else {
2005                // in case there was a 'xfil' chunk, remove it
2006                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2007                if (ckXfil) pRIFF->DeleteSubChunk(ckXfil);
2008            }
2009    
2010            // update the 'doxf' chunk which describes a .gx99 extension file
2011            // which contains convolution data (GigaPulse)
2012            if (pGigaPulseFile) {
2013                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2014                if (!ckDoxf) ckDoxf = pRIFF->AddSubChunk(CHUNK_ID_DOXF, 148);
2015    
2016                uint8_t* pData = (uint8_t*) ckDoxf->LoadChunkData();
2017    
2018                // update the dlsid from the extension file
2019                uint8_t* pId = &pData[132];
2020                RIFF::Chunk* ckDLSID = pGigaPulseFile->GetSubChunk(CHUNK_ID_DLID);
2021                if (!ckDLSID) { //TODO: auto generate DLS ID if missing
2022                    throw Exception("Fatal error, GigaPulse file does not contain a DLS ID chunk");
2023                } else {
2024                    dlsid_t id;
2025                    // read DLS ID from extension files's DLS ID chunk
2026                    uint8_t* pData = (uint8_t*) ckDLSID->LoadChunkData();
2027                    id.ulData1 = load32(&pData[0]);
2028                    id.usData2 = load16(&pData[4]);
2029                    id.usData3 = load16(&pData[6]);
2030                    memcpy(id.abData, &pData[8], 8);
2031                    // store DLS ID to 'doxf' chunk
2032                    store32(&pId[0], id.ulData1);
2033                    store16(&pId[4], id.usData2);
2034                    store16(&pId[6], id.usData3);
2035                    memcpy(&pId[8], id.abData, 8);
2036              }              }
2037            } else {
2038                // in case there was a 'doxf' chunk, remove it
2039                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2040                if (ckDoxf) pRIFF->DeleteSubChunk(ckDoxf);
2041            }
2042    
2043            // the RIFF file to be written might now been grown >= 4GB or might
2044            // been shrunk < 4GB, so we might need to update the wave pool offset
2045            // size and thus accordingly we would need to resize the wave pool
2046            // chunk
2047            const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
2048            const bool bRequires64Bit = (finalFileSize >> 32) != 0 || // < native 64 bit gig file
2049                                         poolFiles.size() > 0;        // < 32 bit gig file where the hi 32 bits are used as extension file nr
2050            if (b64BitWavePoolOffsets != bRequires64Bit) {
2051                b64BitWavePoolOffsets = bRequires64Bit;
2052                iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2053                iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2054                ptbl->Resize(iPtblSize);
2055          }          }
2056    
2057            __notify_progress(pProgress, 1.0); // notify done
2058      }      }
2059    
2060      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1297  namespace DLS { Line 2069  namespace DLS {
2069       * the new file (given by \a Path) afterwards.       * the new file (given by \a Path) afterwards.
2070       *       *
2071       * @param Path - path and file name where everything should be written to       * @param Path - path and file name where everything should be written to
2072         * @param pProgress - optional: callback function for progress notification
2073       */       */
2074      void File::Save(const String& Path) {      void File::Save(const String& Path, progress_t* pProgress) {
2075          UpdateChunks();          // calculate number of tasks to notify progress appropriately
2076          pRIFF->Save(Path);          const size_t nExtFiles = ExtensionFiles.size();
2077          __UpdateWavePoolTableChunk();          const float tasks = 2.f + nExtFiles;
2078    
2079            // save extension files (if required)
2080            if (!ExtensionFiles.empty()) {
2081                // for assembling path of extension files to be saved to
2082                const std::string folder = parentPath(Path);
2083                const std::string baseName = pathWithoutExtension(Path);
2084                // save the individual extension files
2085                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2086                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2087                    // divide local progress into subprogress
2088                    progress_t subprogress;
2089                    __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2090                    //FIXME: the .gx99 file is always used by GSt for convolution
2091                    // data (GigaPulse); so we should better detect by subchunk
2092                    // whether the extension file is intended for convolution
2093                    // instead of checkking for a file name, because the latter does
2094                    // not work for saving new gigs created from scratch
2095                    const std::string oldName = (*it)->GetFileName();
2096                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2097                    std::string ext = (isGigaPulseFile) ? ".gx99" : strPrint(".gx02d", i+1);
2098                    std::string newPath = concatPath(folder, baseName) + ext;
2099                    // save extension file to its new location
2100                    (*it)->Save(newPath, &subprogress);
2101                }
2102            }
2103    
2104            {
2105                // divide local progress into subprogress
2106                progress_t subprogress;
2107                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2108                // do the actual work
2109                UpdateChunks(&subprogress);
2110            }
2111            {
2112                // divide local progress into subprogress
2113                progress_t subprogress;
2114                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2115                // do the actual work
2116                pRIFF->Save(Path, &subprogress);
2117            }
2118            UpdateFileOffsets();
2119            __notify_progress(pProgress, 1.0); // notify done
2120      }      }
2121    
2122      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1310  namespace DLS { Line 2125  namespace DLS {
2125       * 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
2126       * have at the end of the saving process.       * have at the end of the saving process.
2127       *       *
2128       * @throws RIFF::Exception if any kind of IO error occured       * @param pProgress - optional: callback function for progress notification
2129       * @throws DLS::Exception  if any kind of DLS specific error occured       * @throws RIFF::Exception if any kind of IO error occurred
2130         * @throws DLS::Exception  if any kind of DLS specific error occurred
2131         */
2132        void File::Save(progress_t* pProgress) {
2133            // calculate number of tasks to notify progress appropriately
2134            const size_t nExtFiles = ExtensionFiles.size();
2135            const float tasks = 2.f + nExtFiles;
2136    
2137            // save extension files (if required)
2138            if (!ExtensionFiles.empty()) {
2139                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2140                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2141                    // divide local progress into subprogress
2142                    progress_t subprogress;
2143                    __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2144                    // save extension file
2145                    (*it)->Save(&subprogress);
2146                }
2147            }
2148    
2149            {
2150                // divide local progress into subprogress
2151                progress_t subprogress;
2152                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2153                // do the actual work
2154                UpdateChunks(&subprogress);
2155            }
2156            {
2157                // divide local progress into subprogress
2158                progress_t subprogress;
2159                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2160                // do the actual work
2161                pRIFF->Save(&subprogress);
2162            }
2163            UpdateFileOffsets();
2164            __notify_progress(pProgress, 1.0); // notify done
2165        }
2166    
2167        /** @brief Updates all file offsets stored all over the file.
2168         *
2169         * This virtual method is called whenever the overall file layout has been
2170         * changed (i.e. file or individual RIFF chunks have been resized). It is
2171         * then the responsibility of this method to update all file offsets stored
2172         * in the file format. For example samples are referenced by instruments by
2173         * file offsets. The gig format also stores references to instrument
2174         * scripts as file offsets, and thus it overrides this method to update
2175         * those file offsets as well.
2176       */       */
2177      void File::Save() {      void File::UpdateFileOffsets() {
         UpdateChunks();  
         pRIFF->Save();  
2178          __UpdateWavePoolTableChunk();          __UpdateWavePoolTableChunk();
2179      }      }
2180    
# Line 1353  namespace DLS { Line 2212  namespace DLS {
2212          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2213          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2214          // check if 'ptbl' chunk is large enough          // check if 'ptbl' chunk is large enough
2215          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2216          const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;          const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
2217          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
2218          // save the 'ptbl' chunk's current read/write position          // save the 'ptbl' chunk's current read/write position
2219          unsigned long ulOriginalPos = ptbl->GetPos();          file_offset_t ullOriginalPos = ptbl->GetPos();
2220          // update headers          // update headers
2221          ptbl->SetPos(0);          ptbl->SetPos(0);
2222          ptbl->WriteUint32(&WavePoolHeaderSize);          uint32_t tmp = WavePoolHeaderSize;
2223          ptbl->WriteUint32(&WavePoolCount);          ptbl->WriteUint32(&tmp);
2224            tmp = WavePoolCount;
2225            ptbl->WriteUint32(&tmp);
2226          // update offsets          // update offsets
2227          ptbl->SetPos(WavePoolHeaderSize);          ptbl->SetPos(WavePoolHeaderSize);
2228          if (b64BitWavePoolOffsets) {          if (b64BitWavePoolOffsets) {
2229              for (int i = 0 ; i < WavePoolCount ; i++) {              for (int i = 0 ; i < WavePoolCount ; i++) {
2230                  ptbl->WriteUint32(&pWavePoolTableHi[i]);                  tmp = pWavePoolTableHi[i];
2231                  ptbl->WriteUint32(&pWavePoolTable[i]);                  ptbl->WriteUint32(&tmp);
2232                    tmp = pWavePoolTable[i];
2233                    ptbl->WriteUint32(&tmp);
2234              }              }
2235          } else { // conventional 32 bit offsets          } else { // conventional 32 bit offsets
2236              for (int i = 0 ; i < WavePoolCount ; i++)              for (int i = 0 ; i < WavePoolCount ; i++) {
2237                  ptbl->WriteUint32(&pWavePoolTable[i]);                  tmp = pWavePoolTable[i];
2238                    ptbl->WriteUint32(&tmp);
2239                }
2240          }          }
2241          // restore 'ptbl' chunk's original read/write position          // restore 'ptbl' chunk's original read/write position
2242          ptbl->SetPos(ulOriginalPos);          ptbl->SetPos(ullOriginalPos);
2243      }      }
2244    
2245      /**      /**
# Line 1383  namespace DLS { Line 2248  namespace DLS {
2248       * exists already.       * exists already.
2249       */       */
2250      void File::__UpdateWavePoolTable() {      void File::__UpdateWavePoolTable() {
2251          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2252          // resize wave pool table arrays          // resize wave pool table arrays
2253          if (pWavePoolTable)   delete[] pWavePoolTable;          if (pWavePoolTable)   delete[] pWavePoolTable;
2254          if (pWavePoolTableHi) delete[] pWavePoolTableHi;          if (pWavePoolTableHi) delete[] pWavePoolTableHi;
2255          pWavePoolTable   = new uint32_t[WavePoolCount];          pWavePoolTable   = new uint32_t[WavePoolCount];
2256          pWavePoolTableHi = new uint32_t[WavePoolCount];          pWavePoolTableHi = new uint32_t[WavePoolCount];
2257          if (!pSamples) return;          if (!pSamples) return;
2258          // update offsets int wave pool table          // update offsets in wave pool table
2259          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2260          uint64_t wvplFileOffset = wvpl->GetFilePos();          uint64_t wvplFileOffset = wvpl->GetFilePos() -
2261          if (b64BitWavePoolOffsets) {                                    wvpl->GetPos(); // mandatory, since position might have changed
2262            if (!b64BitWavePoolOffsets) { // conventional 32 bit offsets (and no extension files) ...
2263              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
2264              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
2265              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
2266                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset =
2267                  (*iter)->ulWavePoolOffset = _64BitOffset;                      (*iter)->pWaveList->GetFilePos() -
2268                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);                      (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2269                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;                      wvplFileOffset -
2270              }                      LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2271          } 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;  
2272                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2273              }              }
2274            } else { // a) native 64 bit offsets without extension files or b) 32 bit offsets with extension files ...
2275                if (ExtensionFiles.empty()) { // native 64 bit offsets (and no extension files) [not compatible with GigaStudio] ...
2276                    SampleList::iterator iter = pSamples->begin();
2277                    SampleList::iterator end  = pSamples->end();
2278                    for (int i = 0 ; iter != end ; ++iter, i++) {
2279                        uint64_t _64BitOffset =
2280                            (*iter)->pWaveList->GetFilePos() -
2281                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2282                            wvplFileOffset -
2283                            LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2284                        (*iter)->ullWavePoolOffset = _64BitOffset;
2285                        pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
2286                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2287                    }
2288                } else { // 32 bit offsets with extension files (GigaStudio legacy support) ...
2289                    // the main gig and the extension files may contain wave data
2290                    std::vector<RIFF::File*> poolFiles;
2291                    poolFiles.push_back(pRIFF);
2292                    poolFiles.insert(poolFiles.end(), ExtensionFiles.begin(), ExtensionFiles.end());
2293    
2294                    RIFF::File* pCurPoolFile = NULL;
2295                    int fileNo = 0;
2296                    int waveOffset = 0;
2297                    SampleList::iterator iter = pSamples->begin();
2298                    SampleList::iterator end  = pSamples->end();
2299                    for (int i = 0 ; iter != end ; ++iter, i++) {
2300                        RIFF::File* pPoolFile = (*iter)->pWaveList->GetFile();
2301                        // if this sample is located in the same pool file as the
2302                        // last we reuse the previously computed fileNo and waveOffset
2303                        if (pPoolFile != pCurPoolFile) { // it is a different pool file than the last sample ...
2304                            pCurPoolFile = pPoolFile;
2305    
2306                            std::vector<RIFF::File*>::iterator sIter;
2307                            sIter = std::find(poolFiles.begin(), poolFiles.end(), pPoolFile);
2308                            if (sIter != poolFiles.end())
2309                                fileNo = std::distance(poolFiles.begin(), sIter);
2310                            else
2311                                throw DLS::Exception("Fatal error, unknown pool file");
2312    
2313                            RIFF::List* extWvpl = pCurPoolFile->GetSubList(LIST_TYPE_WVPL);
2314                            if (!extWvpl)
2315                                throw DLS::Exception("Fatal error, pool file has no 'wvpl' list chunk");
2316                            waveOffset =
2317                                extWvpl->GetFilePos() -
2318                                extWvpl->GetPos() + // mandatory, since position might have changed
2319                                LIST_HEADER_SIZE(pCurPoolFile->GetFileOffsetSize());
2320                        }
2321                        uint64_t _64BitOffset =
2322                            (*iter)->pWaveList->GetFilePos() -
2323                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2324                            waveOffset;
2325                        // pWavePoolTableHi stores file number when extension files are in use
2326                        pWavePoolTableHi[i] = (uint32_t) fileNo;
2327                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2328                        (*iter)->ullWavePoolOffset = _64BitOffset;
2329                    }
2330                }
2331          }          }
2332      }      }
2333    
2334    
   
2335  // *************** Exception ***************  // *************** Exception ***************
2336  // *  // *
2337    
2338      Exception::Exception(String Message) : RIFF::Exception(Message) {      Exception::Exception() : RIFF::Exception() {
2339        }
2340    
2341        Exception::Exception(String format, ...) : RIFF::Exception() {
2342            va_list arg;
2343            va_start(arg, format);
2344            Message = assemble(format, arg);
2345            va_end(arg);
2346        }
2347    
2348        Exception::Exception(String format, va_list arg) : RIFF::Exception() {
2349            Message = assemble(format, arg);
2350      }      }
2351    
2352      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.834  
changed lines
  Added in v.3478

  ViewVC Help
Powered by ViewVC