/[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 902 by persson, Sat Jul 22 14:22:01 2006 UTC revision 2912 by schoenebeck, Tue May 17 14:30:10 2016 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-2016 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 <time.h>  #include <time.h>
28    
29    #ifdef __APPLE__
30    #include <CoreFoundation/CFUUID.h>
31    #elif defined(HAVE_UUID_UUID_H)
32    #include <uuid/uuid.h>
33    #endif
34    
35  #include "helper.h"  #include "helper.h"
36    
37  // macros to decode connection transforms  // macros to decode connection transforms
# Line 45  Line 52 
52  #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x)             ((x) ? 0x8000 : 0)  #define CONN_TRANSFORM_INVERT_SRC_ENCODE(x)             ((x) ? 0x8000 : 0)
53  #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x)             ((x) ? 0x0200 : 0)  #define CONN_TRANSFORM_INVERT_CTL_ENCODE(x)             ((x) ? 0x0200 : 0)
54    
55  #define DRUM_TYPE_MASK                  0x00000001  #define DRUM_TYPE_MASK                  0x80000000
56    
57  #define F_RGN_OPTION_SELFNONEXCLUSIVE   0x0001  #define F_RGN_OPTION_SELFNONEXCLUSIVE   0x0001
58    
# Line 137  namespace DLS { Line 144  namespace DLS {
144      /**      /**
145       * Apply articulation connections to the respective RIFF chunks. You       * Apply articulation connections to the respective RIFF chunks. You
146       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
147         *
148         * @param pProgress - callback function for progress notification
149       */       */
150      void Articulation::UpdateChunks() {      void Articulation::UpdateChunks(progress_t* pProgress) {
151          const int iEntrySize = 12; // 12 bytes per connection block          const int iEntrySize = 12; // 12 bytes per connection block
152          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
153          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
154          memccpy(&pData[0], &HeaderSize, 1, 2);          store16(&pData[0], HeaderSize);
155          memccpy(&pData[2], &Connections, 1, 2);          store16(&pData[2], Connections);
156          for (uint32_t i = 0; i < Connections; i++) {          for (uint32_t i = 0; i < Connections; i++) {
157              Connection::conn_block_t c = pConnections[i].ToConnBlock();              Connection::conn_block_t c = pConnections[i].ToConnBlock();
158              memccpy(&pData[HeaderSize + i * iEntrySize],     &c.source, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize],     c.source);
159              memccpy(&pData[HeaderSize + i * iEntrySize + 2], &c.control, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize + 2], c.control);
160              memccpy(&pData[HeaderSize + i * iEntrySize + 4], &c.destination, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize + 4], c.destination);
161              memccpy(&pData[HeaderSize + i * iEntrySize + 6], &c.transform, 1, 2);              store16(&pData[HeaderSize + i * iEntrySize + 6], c.transform);
162              memccpy(&pData[HeaderSize + i * iEntrySize + 8], &c.scale, 1, 4);              store32(&pData[HeaderSize + i * iEntrySize + 8], c.scale);
163          }          }
164      }      }
165    
# Line 210  namespace DLS { Line 219  namespace DLS {
219      /**      /**
220       * Apply all articulations to the respective RIFF chunks. You have to       * Apply all articulations to the respective RIFF chunks. You have to
221       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
222         *
223         * @param pProgress - callback function for progress notification
224       */       */
225      void Articulator::UpdateChunks() {      void Articulator::UpdateChunks(progress_t* pProgress) {
226          if (pArticulations) {          if (pArticulations) {
227              ArticulationList::iterator iter = pArticulations->begin();              ArticulationList::iterator iter = pArticulations->begin();
228              ArticulationList::iterator end  = pArticulations->end();              ArticulationList::iterator end  = pArticulations->end();
229              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
230                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
231              }              }
232          }          }
233      }      }
234        
235        /**
236         * Not yet implemented in this version, since the .gig format does
237         * not need to copy DLS articulators and so far nobody used pure
238         * DLS instrument AFAIK.
239         */
240        void Articulator::CopyAssign(const Articulator* orig) {
241            //TODO: implement deep copy assignment for this class
242        }
243    
244    
245    
# Line 228  namespace DLS { Line 248  namespace DLS {
248    
249      /** @brief Constructor.      /** @brief Constructor.
250       *       *
251       * Initializes the info strings with values provided by a INFO list chunk.       * Initializes the info strings with values provided by an INFO list chunk.
252       *       *
253       * @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
254       */       */
255      Info::Info(RIFF::List* list) {      Info::Info(RIFF::List* list) {
256            pFixedStringLengths = NULL;
257          pResourceListChunk = list;          pResourceListChunk = list;
258          if (list) {          if (list) {
259              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);              RIFF::List* lstINFO = list->GetSubList(LIST_TYPE_INFO);
# Line 253  namespace DLS { Line 274  namespace DLS {
274                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);                  LoadString(CHUNK_ID_ISRC, lstINFO, Source);
275                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);                  LoadString(CHUNK_ID_ISRF, lstINFO, SourceForm);
276                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);                  LoadString(CHUNK_ID_ICMS, lstINFO, Commissioned);
277                    LoadString(CHUNK_ID_ISBJ, lstINFO, Subject);
278              }              }
279          }          }
280      }      }
# Line 260  namespace DLS { Line 282  namespace DLS {
282      Info::~Info() {      Info::~Info() {
283      }      }
284    
285        /**
286         * Forces specific Info fields to be of a fixed length when being saved
287         * to a file. By default the respective RIFF chunk of an Info field
288         * will have a size analogue to its actual string length. With this
289         * method however this behavior can be overridden, allowing to force an
290         * arbitrary fixed size individually for each Info field.
291         *
292         * This method is used as a workaround for the gig format, not for DLS.
293         *
294         * @param lengths - NULL terminated array of string_length_t elements
295         */
296        void Info::SetFixedStringLengths(const string_length_t* lengths) {
297            pFixedStringLengths = lengths;
298        }
299    
300      /** @brief Load given INFO field.      /** @brief Load given INFO field.
301       *       *
302       * 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 304  namespace DLS {
304       */       */
305      void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {      void Info::LoadString(uint32_t ChunkID, RIFF::List* lstINFO, String& s) {
306          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
307          if (ck) {          ::LoadString(ck, s); // function from helper.h
             const char* str = (char*)ck->LoadChunkData();  
             int size = ck->GetSize();  
             int len;  
             for (len = 0 ; len < size ; len++)  
                 if (str[len] == '\0') break;  
             s.assign(str, len);  
             ck->ReleaseChunkData();  
         }  
308      }      }
309    
310      /** @brief Apply given INFO field to the respective chunk.      /** @brief Apply given INFO field to the respective chunk.
# Line 294  namespace DLS { Line 323  namespace DLS {
323       * @param sDefault - default value       * @param sDefault - default value
324       */       */
325      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) {
326          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);          int size = 0;
327          if (ck) { // if chunk exists already, use 's' as value          if (pFixedStringLengths) {
328              ck->Resize(s.size() + 1);              for (int i = 0 ; pFixedStringLengths[i].length ; i++) {
329              char* pData = (char*) ck->LoadChunkData();                  if (pFixedStringLengths[i].chunkId == ChunkID) {
330              memcpy(pData, s.c_str(), s.size() + 1);                      size = pFixedStringLengths[i].length;
331          } else if (s != "" || sDefault != "") { // create chunk                      break;
332              const String& sToSave = (s != "") ? s : sDefault;                  }
333              ck = lstINFO->AddSubChunk(ChunkID, sToSave.size() + 1);              }
             char* pData = (char*) ck->LoadChunkData();  
             memcpy(pData, sToSave.c_str(), sToSave.size() + 1);  
334          }          }
335            RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
336            ::SaveString(ChunkID, ck, lstINFO, s, sDefault, size != 0, size); // function from helper.h
337      }      }
338    
339      /** @brief Update chunks with current info values.      /** @brief Update chunks with current info values.
340       *       *
341       * Apply current INFO field values to the respective INFO chunks. You       * Apply current INFO field values to the respective INFO chunks. You
342       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
343         *
344         * @param pProgress - callback function for progress notification
345       */       */
346      void Info::UpdateChunks() {      void Info::UpdateChunks(progress_t* pProgress) {
347          if (!pResourceListChunk) return;          if (!pResourceListChunk) return;
348    
349          // make sure INFO list chunk exists          // make sure INFO list chunk exists
350          RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);          RIFF::List* lstINFO   = pResourceListChunk->GetSubList(LIST_TYPE_INFO);
         if (!lstINFO) lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);  
351    
352          // assemble default values in case the respective chunk is missing yet          String defaultName = "";
353          String defaultName = "NONAME";          String defaultCreationDate = "";
354          // get current date          String defaultSoftware = "";
355          time_t now = time(NULL);          String defaultComments = "";
356          tm* pNowBroken = localtime(&now);  
357          String defaultCreationDate = ToString(1900 + pNowBroken->tm_year) + "-" +          uint32_t resourceType = pResourceListChunk->GetListType();
358                                       ToString(pNowBroken->tm_mon + 1)  + "-" +  
359                                       ToString(pNowBroken->tm_mday);          if (!lstINFO) {
360          String defaultSoftware = libraryName() + " " + libraryVersion();              lstINFO = pResourceListChunk->AddSubList(LIST_TYPE_INFO);
361          String defaultComments = "Created with " + libraryName() + " " + libraryVersion();  
362                // assemble default values
363                defaultName = "NONAME";
364    
365                if (resourceType == RIFF_TYPE_DLS) {
366                    // get current date
367                    time_t now = time(NULL);
368                    tm* pNowBroken = localtime(&now);
369                    char buf[11];
370                    strftime(buf, 11, "%F", pNowBroken);
371                    defaultCreationDate = buf;
372    
373                    defaultComments = "Created with " + libraryName() + " " + libraryVersion();
374                }
375                if (resourceType == RIFF_TYPE_DLS || resourceType == LIST_TYPE_INS)
376                {
377                    defaultSoftware = libraryName() + " " + libraryVersion();
378                }
379            }
380    
381          // save values          // save values
382          SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);  
383          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
384          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
385            SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
386          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
         SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));  
387          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
388          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
389            SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
390          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
391          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);  
392          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
393            SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
394            SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
395            SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""));
396            SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
397          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
398          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
399          SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
400        }
401        
402        /**
403         * Make a deep copy of the Info object given by @a orig and assign it to
404         * this object.
405         *
406         * @param orig - original Info object to be copied from
407         */
408        void Info::CopyAssign(const Info* orig) {
409            Name = orig->Name;
410            ArchivalLocation = orig->ArchivalLocation;
411            CreationDate = orig->CreationDate;
412            Comments = orig->Comments;
413            Product = orig->Product;
414            Copyright = orig->Copyright;
415            Artists = orig->Artists;
416            Genre = orig->Genre;
417            Keywords = orig->Keywords;
418            Engineer = orig->Engineer;
419            Technician = orig->Technician;
420            Software = orig->Software;
421            Medium = orig->Medium;
422            Source = orig->Source;
423            SourceForm = orig->SourceForm;
424            Commissioned = orig->Commissioned;
425            Subject = orig->Subject;
426            //FIXME: hmm, is copying this pointer a good idea?
427            pFixedStringLengths = orig->pFixedStringLengths;
428      }      }
429    
430    
# Line 392  namespace DLS { Line 470  namespace DLS {
470       * will not be applied at the moment (yet).       * will not be applied at the moment (yet).
471       *       *
472       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
473         *
474         * @param pProgress - callback function for progress notification
475       */       */
476      void Resource::UpdateChunks() {      void Resource::UpdateChunks(progress_t* pProgress) {
477          pInfo->UpdateChunks();          pInfo->UpdateChunks(pProgress);
478          //TODO: save DLSID  
479            if (pDLSID) {
480                // make sure 'dlid' chunk exists
481                RIFF::Chunk* ckDLSID = pResourceList->GetSubChunk(CHUNK_ID_DLID);
482                if (!ckDLSID) ckDLSID = pResourceList->AddSubChunk(CHUNK_ID_DLID, 16);
483                uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
484                // update 'dlid' chunk
485                store32(&pData[0], pDLSID->ulData1);
486                store16(&pData[4], pDLSID->usData2);
487                store16(&pData[6], pDLSID->usData3);
488                memcpy(&pData[8], pDLSID->abData, 8);
489            }
490      }      }
491    
492        /**
493         * Generates a new DLSID for the resource.
494         */
495        void Resource::GenerateDLSID() {
496    #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
497    
498            if (!pDLSID) pDLSID = new dlsid_t;
499    
500    #ifdef WIN32
501    
502            UUID uuid;
503            UuidCreate(&uuid);
504            pDLSID->ulData1 = uuid.Data1;
505            pDLSID->usData2 = uuid.Data2;
506            pDLSID->usData3 = uuid.Data3;
507            memcpy(pDLSID->abData, uuid.Data4, 8);
508    
509    #elif defined(__APPLE__)
510    
511            CFUUIDRef uuidRef = CFUUIDCreate(NULL);
512            CFUUIDBytes uuid = CFUUIDGetUUIDBytes(uuidRef);
513            CFRelease(uuidRef);
514            pDLSID->ulData1 = uuid.byte0 | uuid.byte1 << 8 | uuid.byte2 << 16 | uuid.byte3 << 24;
515            pDLSID->usData2 = uuid.byte4 | uuid.byte5 << 8;
516            pDLSID->usData3 = uuid.byte6 | uuid.byte7 << 8;
517            pDLSID->abData[0] = uuid.byte8;
518            pDLSID->abData[1] = uuid.byte9;
519            pDLSID->abData[2] = uuid.byte10;
520            pDLSID->abData[3] = uuid.byte11;
521            pDLSID->abData[4] = uuid.byte12;
522            pDLSID->abData[5] = uuid.byte13;
523            pDLSID->abData[6] = uuid.byte14;
524            pDLSID->abData[7] = uuid.byte15;
525    #else
526            uuid_t uuid;
527            uuid_generate(uuid);
528            pDLSID->ulData1 = uuid[0] | uuid[1] << 8 | uuid[2] << 16 | uuid[3] << 24;
529            pDLSID->usData2 = uuid[4] | uuid[5] << 8;
530            pDLSID->usData3 = uuid[6] | uuid[7] << 8;
531            memcpy(pDLSID->abData, &uuid[8], 8);
532    #endif
533    #endif
534        }
535        
536        /**
537         * Make a deep copy of the Resource object given by @a orig and assign it
538         * to this object.
539         *
540         * @param orig - original Resource object to be copied from
541         */
542        void Resource::CopyAssign(const Resource* orig) {
543            pInfo->CopyAssign(orig->pInfo);
544        }
545    
546    
547  // *************** Sampler ***************  // *************** Sampler ***************
# Line 414  namespace DLS { Line 558  namespace DLS {
558              SamplerOptions = wsmp->ReadUint32();              SamplerOptions = wsmp->ReadUint32();
559              SampleLoops    = wsmp->ReadUint32();              SampleLoops    = wsmp->ReadUint32();
560          } else { // 'wsmp' chunk missing          } else { // 'wsmp' chunk missing
561              uiHeaderSize   = 0;              uiHeaderSize   = 20;
562              UnityNote      = 64;              UnityNote      = 60;
563              FineTune       = 0; // +- 0 cents              FineTune       = 0; // +- 0 cents
564              Gain           = 0; // 0 dB              Gain           = 0; // 0 dB
565              SamplerOptions = F_WSMP_NO_COMPRESSION;              SamplerOptions = F_WSMP_NO_COMPRESSION;
# Line 439  namespace DLS { Line 583  namespace DLS {
583          if (pSampleLoops) delete[] pSampleLoops;          if (pSampleLoops) delete[] pSampleLoops;
584      }      }
585    
586        void Sampler::SetGain(int32_t gain) {
587            Gain = gain;
588        }
589    
590      /**      /**
591       * Apply all sample player options to the respective RIFF chunk. You       * Apply all sample player options to the respective RIFF chunk. You
592       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
593         *
594         * @param pProgress - callback function for progress notification
595       */       */
596      void Sampler::UpdateChunks() {      void Sampler::UpdateChunks(progress_t* pProgress) {
597          // make sure 'wsmp' chunk exists          // make sure 'wsmp' chunk exists
598          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
599            int wsmpSize = uiHeaderSize + SampleLoops * 16;
600          if (!wsmp) {          if (!wsmp) {
601              uiHeaderSize = 20;              wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, wsmpSize);
602              wsmp = pParentList->AddSubChunk(CHUNK_ID_WSMP, uiHeaderSize + SampleLoops * 16);          } else if (wsmp->GetSize() != wsmpSize) {
603                wsmp->Resize(wsmpSize);
604          }          }
605          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
606          // update headers size          // update headers size
607          memccpy(&pData[0], &uiHeaderSize, 1, 4);          store32(&pData[0], uiHeaderSize);
608          // update respective sampler options bits          // update respective sampler options bits
609          SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION          SamplerOptions = (NoSampleDepthTruncation) ? SamplerOptions | F_WSMP_NO_TRUNCATION
610                                                     : SamplerOptions & (~F_WSMP_NO_TRUNCATION);                                                     : SamplerOptions & (~F_WSMP_NO_TRUNCATION);
611          SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION          SamplerOptions = (NoSampleCompression) ? SamplerOptions | F_WSMP_NO_COMPRESSION
612                                                 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);                                                 : SamplerOptions & (~F_WSMP_NO_COMPRESSION);
613            store16(&pData[4], UnityNote);
614            store16(&pData[6], FineTune);
615            store32(&pData[8], Gain);
616            store32(&pData[12], SamplerOptions);
617            store32(&pData[16], SampleLoops);
618          // update loop definitions          // update loop definitions
619          for (uint32_t i = 0; i < SampleLoops; i++) {          for (uint32_t i = 0; i < SampleLoops; i++) {
620              //FIXME: this does not handle extended loop structs correctly              //FIXME: this does not handle extended loop structs correctly
621              memccpy(&pData[uiHeaderSize + i * 16], pSampleLoops + i, 4, 4);              store32(&pData[uiHeaderSize + i * 16], pSampleLoops[i].Size);
622                store32(&pData[uiHeaderSize + i * 16 + 4], pSampleLoops[i].LoopType);
623                store32(&pData[uiHeaderSize + i * 16 + 8], pSampleLoops[i].LoopStart);
624                store32(&pData[uiHeaderSize + i * 16 + 12], pSampleLoops[i].LoopLength);
625          }          }
626      }      }
627    
628        /**
629         * Adds a new sample loop with the provided loop definition.
630         *
631         * @param pLoopDef - points to a loop definition that is to be copied
632         */
633        void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {
634            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
635            // copy old loops array
636            for (int i = 0; i < SampleLoops; i++) {
637                pNewLoops[i] = pSampleLoops[i];
638            }
639            // add the new loop
640            pNewLoops[SampleLoops] = *pLoopDef;
641            // auto correct size field
642            pNewLoops[SampleLoops].Size = sizeof(DLS::sample_loop_t);
643            // free the old array and update the member variables
644            if (SampleLoops) delete[] pSampleLoops;
645            pSampleLoops = pNewLoops;
646            SampleLoops++;
647        }
648    
649        /**
650         * Deletes an existing sample loop.
651         *
652         * @param pLoopDef - pointer to existing loop definition
653         * @throws Exception - if given loop definition does not exist
654         */
655        void Sampler::DeleteSampleLoop(sample_loop_t* pLoopDef) {
656            sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops - 1];
657            // copy old loops array (skipping given loop)
658            for (int i = 0, o = 0; i < SampleLoops; i++) {
659                if (&pSampleLoops[i] == pLoopDef) continue;
660                if (o == SampleLoops - 1) {
661                    delete[] pNewLoops;
662                    throw Exception("Could not delete Sample Loop, because it does not exist");
663                }
664                pNewLoops[o] = pSampleLoops[i];
665                o++;
666            }
667            // free the old array and update the member variables
668            if (SampleLoops) delete[] pSampleLoops;
669            pSampleLoops = pNewLoops;
670            SampleLoops--;
671        }
672        
673        /**
674         * Make a deep copy of the Sampler object given by @a orig and assign it
675         * to this object.
676         *
677         * @param orig - original Sampler object to be copied from
678         */
679        void Sampler::CopyAssign(const Sampler* orig) {
680            // copy trivial scalars
681            UnityNote = orig->UnityNote;
682            FineTune = orig->FineTune;
683            Gain = orig->Gain;
684            NoSampleDepthTruncation = orig->NoSampleDepthTruncation;
685            NoSampleCompression = orig->NoSampleCompression;
686            SamplerOptions = orig->SamplerOptions;
687            
688            // copy sample loops
689            if (SampleLoops) delete[] pSampleLoops;
690            pSampleLoops = new sample_loop_t[orig->SampleLoops];
691            memcpy(pSampleLoops, orig->pSampleLoops, orig->SampleLoops * sizeof(sample_loop_t));
692            SampleLoops = orig->SampleLoops;
693        }
694    
695    
696  // *************** Sample ***************  // *************** Sample ***************
# Line 485  namespace DLS { Line 711  namespace DLS {
711       * @param WavePoolOffset - offset of this sample data from wave pool       * @param WavePoolOffset - offset of this sample data from wave pool
712       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
713       */       */
714      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) {
715          pWaveList = waveList;          pWaveList = waveList;
716          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;          ullWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE(waveList->GetFile()->GetFileOffsetSize());
717          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
718          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);
719          if (pCkFormat) {          if (pCkFormat) {
# Line 498  namespace DLS { Line 724  namespace DLS {
724              AverageBytesPerSecond  = pCkFormat->ReadUint32();              AverageBytesPerSecond  = pCkFormat->ReadUint32();
725              BlockAlign             = pCkFormat->ReadUint16();              BlockAlign             = pCkFormat->ReadUint16();
726              // PCM format specific              // PCM format specific
727              if (FormatTag == WAVE_FORMAT_PCM) {              if (FormatTag == DLS_WAVE_FORMAT_PCM) {
728                  BitDepth     = pCkFormat->ReadUint16();                  BitDepth     = pCkFormat->ReadUint16();
729                  FrameSize    = (FormatTag == WAVE_FORMAT_PCM) ? (BitDepth / 8) * Channels                  FrameSize    = (BitDepth / 8) * Channels;
                                                             : 0;  
730              } else { // unsupported sample data format              } else { // unsupported sample data format
731                  BitDepth     = 0;                  BitDepth     = 0;
732                  FrameSize    = 0;                  FrameSize    = 0;
733              }              }
734          } else { // 'fmt' chunk missing          } else { // 'fmt' chunk missing
735              FormatTag              = WAVE_FORMAT_PCM;              FormatTag              = DLS_WAVE_FORMAT_PCM;
736              BitDepth               = 16;              BitDepth               = 16;
737              Channels               = 1;              Channels               = 1;
738              SamplesPerSecond       = 44100;              SamplesPerSecond       = 44100;
# Line 515  namespace DLS { Line 740  namespace DLS {
740              FrameSize              = (BitDepth / 8) * Channels;              FrameSize              = (BitDepth / 8) * Channels;
741              BlockAlign             = FrameSize;              BlockAlign             = FrameSize;
742          }          }
743          SamplesTotal = (pCkData) ? (FormatTag == WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize          SamplesTotal = (pCkData) ? (FormatTag == DLS_WAVE_FORMAT_PCM) ? pCkData->GetSize() / FrameSize
744                                                                    : 0                                                                        : 0
745                                   : 0;                                   : 0;
746      }      }
747    
# Line 529  namespace DLS { Line 754  namespace DLS {
754          RIFF::List* pParent = pWaveList->GetParent();          RIFF::List* pParent = pWaveList->GetParent();
755          pParent->DeleteSubChunk(pWaveList);          pParent->DeleteSubChunk(pWaveList);
756      }      }
757        
758        /**
759         * Make a deep copy of the Sample object given by @a orig (without the
760         * actual sample waveform data however) and assign it to this object.
761         *
762         * This is a special internal variant of CopyAssign() which only copies the
763         * most mandatory member variables. It will be called by gig::Sample
764         * descendent instead of CopyAssign() since gig::Sample has its own
765         * implementation to access and copy the actual sample waveform data.
766         *
767         * @param orig - original Sample object to be copied from
768         */
769        void Sample::CopyAssignCore(const Sample* orig) {
770            // handle base classes
771            Resource::CopyAssign(orig);
772            // handle actual own attributes of this class
773            FormatTag = orig->FormatTag;
774            Channels = orig->Channels;
775            SamplesPerSecond = orig->SamplesPerSecond;
776            AverageBytesPerSecond = orig->AverageBytesPerSecond;
777            BlockAlign = orig->BlockAlign;
778            BitDepth = orig->BitDepth;
779            SamplesTotal = orig->SamplesTotal;
780            FrameSize = orig->FrameSize;
781        }
782        
783        /**
784         * Make a deep copy of the Sample object given by @a orig and assign it to
785         * this object.
786         *
787         * @param orig - original Sample object to be copied from
788         */
789        void Sample::CopyAssign(const Sample* orig) {
790            CopyAssignCore(orig);
791            
792            // copy sample waveform data (reading directly from disc)
793            Resize(orig->GetSize());
794            char* buf = (char*) LoadSampleData();
795            Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
796            const file_offset_t restorePos = pOrig->pCkData->GetPos();
797            pOrig->SetPos(0);
798            for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
799                const int iReadAtOnce = 64*1024;
800                file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
801                n = pOrig->Read(&buf[i], n);
802                if (!n) break;
803                todo -= n;
804                i += (n * pOrig->FrameSize);
805            }
806            pOrig->pCkData->SetPos(restorePos);
807        }
808    
809      /** @brief Load sample data into RAM.      /** @brief Load sample data into RAM.
810       *       *
# Line 576  namespace DLS { Line 852  namespace DLS {
852       * the RIFF chunk which encapsulates the sample's wave data. The       * the RIFF chunk which encapsulates the sample's wave data. The
853       * returned value is dependant to the current FrameSize value.       * returned value is dependant to the current FrameSize value.
854       *       *
855       * @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
856       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
857       */       */
858      unsigned long Sample::GetSize() {      file_offset_t Sample::GetSize() const {
859          if (FormatTag != WAVE_FORMAT_PCM) return 0;          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
860          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
861      }      }
862    
# Line 602  namespace DLS { Line 878  namespace DLS {
878       * calling File::Save() as this might exceed the current sample's       * calling File::Save() as this might exceed the current sample's
879       * boundary!       * boundary!
880       *       *
881       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
882       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
883       * other formats will fail!       * other formats will fail!
884       *       *
885       * @param iNewSize - new sample wave data size in sample points (must be       * @param iNewSize - new sample wave data size in sample points (must be
886       *                   greater than zero)       *                   greater than zero)
887       * @throws Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
888       * @throws Exception if \a iNewSize is less than 1       * @throws Exception if \a iNewSize is less than 1
889       * @see File::Save(), FrameSize, FormatTag       * @see File::Save(), FrameSize, FormatTag
890       */       */
891      void Sample::Resize(int iNewSize) {      void Sample::Resize(int iNewSize) {
892          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");
893          if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");          if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");
894          const int iSizeInBytes = iNewSize * FrameSize;          const int iSizeInBytes = iNewSize * FrameSize;
895          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
# Line 626  namespace DLS { Line 902  namespace DLS {
902       * 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
903       * the sample into RAM, thus for disk streaming.       * the sample into RAM, thus for disk streaming.
904       *       *
905       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
906       * FormatTag must be WAVE_FORMAT_PCM. Trying to reposition the sample       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to reposition the sample
907       * with other formats will fail!       * with other formats will fail!
908       *       *
909       * @param SampleCount  number of sample points       * @param SampleCount  number of sample points
910       * @param Whence       to which relation \a SampleCount refers to       * @param Whence       to which relation \a SampleCount refers to
911       * @returns new position within the sample, 0 if       * @returns new position within the sample, 0 if
912       *          FormatTag != WAVE_FORMAT_PCM       *          FormatTag != DLS_WAVE_FORMAT_PCM
913       * @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
914       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
915       */       */
916      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) {
917          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
918          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");
919          unsigned long orderedBytes = SampleCount * FrameSize;          file_offset_t orderedBytes = SampleCount * FrameSize;
920          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
921          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
922                                          : result / FrameSize;                                          : result / FrameSize;
923      }      }
# Line 655  namespace DLS { Line 931  namespace DLS {
931       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
932       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
933       */       */
934      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
935          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
936          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?
937      }      }
938    
# Line 675  namespace DLS { Line 951  namespace DLS {
951       * @throws Exception if current sample size is too small       * @throws Exception if current sample size is too small
952       * @see LoadSampleData()       * @see LoadSampleData()
953       */       */
954      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
955          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
956          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");
957          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?
958      }      }
# Line 685  namespace DLS { Line 961  namespace DLS {
961       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
962       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
963       *       *
964       * @throws Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @param pProgress - callback function for progress notification
965         * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
966       *                   was provided yet       *                   was provided yet
967       */       */
968      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
969          if (FormatTag != WAVE_FORMAT_PCM)          if (FormatTag != DLS_WAVE_FORMAT_PCM)
970              throw Exception("Could not save sample, only PCM format is supported");              throw Exception("Could not save sample, only PCM format is supported");
971          // 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
972          if (!pCkData)          if (!pCkData)
973              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");
974          // update chunks of base class as well          // update chunks of base class as well
975          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
976          // make sure 'fmt' chunk exists          // make sure 'fmt' chunk exists
977          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
978          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
979          uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkFormat->LoadChunkData();
980          // update 'fmt' chunk          // update 'fmt' chunk
981          memccpy(&pData[0], &FormatTag, 1, 2);          store16(&pData[0], FormatTag);
982          memccpy(&pData[2], &Channels,  1, 2);          store16(&pData[2], Channels);
983          memccpy(&pData[4], &SamplesPerSecond, 1, 4);          store32(&pData[4], SamplesPerSecond);
984          memccpy(&pData[8], &AverageBytesPerSecond, 1, 4);          store32(&pData[8], AverageBytesPerSecond);
985          memccpy(&pData[12], &BlockAlign, 1, 2);          store16(&pData[12], BlockAlign);
986          memccpy(&pData[14], &BitDepth, 1, 2); // assuming PCM format          store16(&pData[14], BitDepth); // assuming PCM format
987      }      }
988    
989    
# Line 770  namespace DLS { Line 1047  namespace DLS {
1047      Sample* Region::GetSample() {      Sample* Region::GetSample() {
1048          if (pSample) return pSample;          if (pSample) return pSample;
1049          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1050          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1051          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample();
1052          while (sample) {          while (sample) {
1053              if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);              if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1054              sample = file->GetNextSample();              sample = file->GetNextSample();
1055          }          }
1056          return NULL;          return NULL;
# Line 790  namespace DLS { Line 1067  namespace DLS {
1067      }      }
1068    
1069      /**      /**
1070         * Modifies the key range of this Region and makes sure the respective
1071         * chunks are in correct order.
1072         *
1073         * @param Low  - lower end of key range
1074         * @param High - upper end of key range
1075         */
1076        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
1077            KeyRange.low  = Low;
1078            KeyRange.high = High;
1079    
1080            // make sure regions are already loaded
1081            Instrument* pInstrument = (Instrument*) GetParent();
1082            if (!pInstrument->pRegions) pInstrument->LoadRegions();
1083            if (!pInstrument->pRegions) return;
1084    
1085            // find the r which is the first one to the right of this region
1086            // at its new position
1087            Region* r = NULL;
1088            Region* prev_region = NULL;
1089            for (
1090                Instrument::RegionList::iterator iter = pInstrument->pRegions->begin();
1091                iter != pInstrument->pRegions->end(); iter++
1092            ) {
1093                if ((*iter)->KeyRange.low > this->KeyRange.low) {
1094                    r = *iter;
1095                    break;
1096                }
1097                prev_region = *iter;
1098            }
1099    
1100            // place this region before r if it's not already there
1101            if (prev_region != this) pInstrument->MoveRegion(this, r);
1102        }
1103    
1104        /**
1105       * Apply Region settings to the respective RIFF chunks. You have to       * Apply Region settings to the respective RIFF chunks. You have to
1106       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
1107       *       *
1108         * @param pProgress - callback function for progress notification
1109       * @throws Exception - if the Region's sample could not be found       * @throws Exception - if the Region's sample could not be found
1110       */       */
1111      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
1112          // make sure 'rgnh' chunk exists          // make sure 'rgnh' chunk exists
1113          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1114          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, 14);          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
1115          uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();          uint8_t* pData = (uint8_t*) rgnh->LoadChunkData();
1116          FormatOptionFlags = (SelfNonExclusive)          FormatOptionFlags = (SelfNonExclusive)
1117                                  ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE                                  ? FormatOptionFlags | F_RGN_OPTION_SELFNONEXCLUSIVE
1118                                  : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);                                  : FormatOptionFlags & (~F_RGN_OPTION_SELFNONEXCLUSIVE);
1119          // update 'rgnh' chunk          // update 'rgnh' chunk
1120          memccpy(&pData[0], &KeyRange, 2, 2);          store16(&pData[0], KeyRange.low);
1121          memccpy(&pData[4], &VelocityRange, 2, 2);          store16(&pData[2], KeyRange.high);
1122          memccpy(&pData[8], &FormatOptionFlags, 1, 2);          store16(&pData[4], VelocityRange.low);
1123          memccpy(&pData[10], &KeyGroup, 1, 2);          store16(&pData[6], VelocityRange.high);
1124          memccpy(&pData[12], &Layer, 1, 2);          store16(&pData[8], FormatOptionFlags);
1125            store16(&pData[10], KeyGroup);
1126          // update chunks of base classes as well          if (rgnh->GetSize() >= 14) store16(&pData[12], Layer);
1127          Resource::UpdateChunks();  
1128          Articulator::UpdateChunks();          // update chunks of base classes as well (but skip Resource,
1129          Sampler::UpdateChunks();          // as a rgn doesn't seem to have dlid and INFO chunks)
1130            Articulator::UpdateChunks(pProgress);
1131            Sampler::UpdateChunks(pProgress);
1132    
1133          // make sure 'wlnk' chunk exists          // make sure 'wlnk' chunk exists
1134          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
# Line 838  namespace DLS { Line 1153  namespace DLS {
1153                  }                  }
1154              }              }
1155          }          }
         if (index < 0) throw Exception("Could not save Region, could not find Region's sample");  
1156          WavePoolTableIndex = index;          WavePoolTableIndex = index;
1157          // update 'wlnk' chunk          // update 'wlnk' chunk
1158          memccpy(&pData[0], &WaveLinkOptionFlags, 1, 2);          store16(&pData[0], WaveLinkOptionFlags);
1159          memccpy(&pData[2], &PhaseGroup, 1, 2);          store16(&pData[2], PhaseGroup);
1160          memccpy(&pData[4], &Channel, 1, 4);          store32(&pData[4], Channel);
1161          memccpy(&pData[8], &WavePoolTableIndex, 1, 4);          store32(&pData[8], WavePoolTableIndex);
1162        }
1163        
1164        /**
1165         * Make a (semi) deep copy of the Region object given by @a orig and assign
1166         * it to this object.
1167         *
1168         * Note that the sample pointer referenced by @a orig is simply copied as
1169         * memory address. Thus the respective sample is shared, not duplicated!
1170         *
1171         * @param orig - original Region object to be copied from
1172         */
1173        void Region::CopyAssign(const Region* orig) {
1174            // handle base classes
1175            Resource::CopyAssign(orig);
1176            Articulator::CopyAssign(orig);
1177            Sampler::CopyAssign(orig);
1178            // handle actual own attributes of this class
1179            // (the trivial ones)
1180            VelocityRange = orig->VelocityRange;
1181            KeyGroup = orig->KeyGroup;
1182            Layer = orig->Layer;
1183            SelfNonExclusive = orig->SelfNonExclusive;
1184            PhaseMaster = orig->PhaseMaster;
1185            PhaseGroup = orig->PhaseGroup;
1186            MultiChannel = orig->MultiChannel;
1187            Channel = orig->Channel;
1188            // only take the raw sample reference if the two Region objects are
1189            // part of the same file
1190            if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1191                WavePoolTableIndex = orig->WavePoolTableIndex;
1192                pSample = orig->pSample;
1193            } else {
1194                WavePoolTableIndex = -1;
1195                pSample = NULL;
1196            }
1197            FormatOptionFlags = orig->FormatOptionFlags;
1198            WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1199            // handle the last, a bit sensible attribute
1200            SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1201      }      }
   
1202    
1203    
1204  // *************** Instrument ***************  // *************** Instrument ***************
# Line 927  namespace DLS { Line 1279  namespace DLS {
1279          return pNewRegion;          return pNewRegion;
1280      }      }
1281    
1282        void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1283            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1284            lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1285    
1286            pRegions->remove(pSrc);
1287            RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
1288            pRegions->insert(iter, pSrc);
1289        }
1290    
1291      void Instrument::DeleteRegion(Region* pRegion) {      void Instrument::DeleteRegion(Region* pRegion) {
1292          if (!pRegions) return;          if (!pRegions) return;
1293          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
# Line 940  namespace DLS { Line 1301  namespace DLS {
1301       * Apply Instrument with all its Regions to the respective RIFF chunks.       * Apply Instrument with all its Regions to the respective RIFF chunks.
1302       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
1303       *       *
1304         * @param pProgress - callback function for progress notification
1305       * @throws Exception - on errors       * @throws Exception - on errors
1306       */       */
1307      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
1308          // first update base classes' chunks          // first update base classes' chunks
1309          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1310          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1311          // make sure 'insh' chunk exists          // make sure 'insh' chunk exists
1312          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1313          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
# Line 957  namespace DLS { Line 1319  namespace DLS {
1319          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
1320          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);
1321          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
1322          memccpy(&pData[0], &Regions, 1, 4);          store32(&pData[0], Regions);
1323          memccpy(&pData[4], &locale, 2, 4);          store32(&pData[4], locale.bank);
1324            store32(&pData[8], locale.instrument);
1325          // update Region's chunks          // update Region's chunks
1326          if (!pRegions) return;          if (!pRegions) return;
1327          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
1328          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
1329          for (; iter != end; ++iter) {          for (int i = 0; iter != end; ++iter, ++i) {
1330              (*iter)->UpdateChunks();              // divide local progress into subprogress
1331                progress_t subprogress;
1332                __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1333                // do the actual work
1334                (*iter)->UpdateChunks(&subprogress);
1335          }          }
1336            __notify_progress(pProgress, 1.0); // notify done
1337      }      }
1338    
1339      /** @brief Destructor.      /** @brief Destructor.
# Line 987  namespace DLS { Line 1355  namespace DLS {
1355          RIFF::List* pParent = pCkInstrument->GetParent();          RIFF::List* pParent = pCkInstrument->GetParent();
1356          pParent->DeleteSubChunk(pCkInstrument);          pParent->DeleteSubChunk(pCkInstrument);
1357      }      }
1358        
1359        void Instrument::CopyAssignCore(const Instrument* orig) {
1360            // handle base classes
1361            Resource::CopyAssign(orig);
1362            Articulator::CopyAssign(orig);
1363            // handle actual own attributes of this class
1364            // (the trivial ones)
1365            IsDrum = orig->IsDrum;
1366            MIDIBank = orig->MIDIBank;
1367            MIDIBankCoarse = orig->MIDIBankCoarse;
1368            MIDIBankFine = orig->MIDIBankFine;
1369            MIDIProgram = orig->MIDIProgram;
1370        }
1371        
1372        /**
1373         * Make a (semi) deep copy of the Instrument object given by @a orig and assign
1374         * it to this object.
1375         *
1376         * Note that all sample pointers referenced by @a orig are simply copied as
1377         * memory address. Thus the respective samples are shared, not duplicated!
1378         *
1379         * @param orig - original Instrument object to be copied from
1380         */
1381        void Instrument::CopyAssign(const Instrument* orig) {
1382            CopyAssignCore(orig);
1383            // delete all regions first
1384            while (Regions) DeleteRegion(GetFirstRegion());
1385            // now recreate and copy regions
1386            {
1387                RegionList::const_iterator it = orig->pRegions->begin();
1388                for (int i = 0; i < orig->Regions; ++i, ++it) {
1389                    Region* dstRgn = AddRegion();
1390                    //NOTE: Region does semi-deep copy !
1391                    dstRgn->CopyAssign(*it);
1392                }
1393            }
1394        }
1395    
1396    
1397  // *************** File ***************  // *************** File ***************
# Line 1000  namespace DLS { Line 1404  namespace DLS {
1404       * a DLS file.       * a DLS file.
1405       */       */
1406      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1407            pRIFF->SetByteOrder(RIFF::endian_little);
1408          pVersion = new version_t;          pVersion = new version_t;
1409          pVersion->major   = 0;          pVersion->major   = 0;
1410          pVersion->minor   = 0;          pVersion->minor   = 0;
# Line 1062  namespace DLS { Line 1467  namespace DLS {
1467                  for (int i = 0 ; i < WavePoolCount ; i++) {                  for (int i = 0 ; i < WavePoolCount ; i++) {
1468                      pWavePoolTableHi[i] = ptbl->ReadUint32();                      pWavePoolTableHi[i] = ptbl->ReadUint32();
1469                      pWavePoolTable[i] = ptbl->ReadUint32();                      pWavePoolTable[i] = ptbl->ReadUint32();
1470                      if (pWavePoolTable[i] & 0x80000000)                      //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1471                          throw DLS::Exception("Files larger than 2 GB not yet supported");                      //if (pWavePoolTable[i] & 0x80000000)
1472                        //    throw DLS::Exception("Files larger than 2 GB not yet supported");
1473                  }                  }
1474              } else { // conventional 32 bit offsets              } else { // conventional 32 bit offsets
1475                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
# Line 1120  namespace DLS { Line 1526  namespace DLS {
1526          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
1527          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1528          if (wvpl) {          if (wvpl) {
1529              unsigned long wvplFileOffset = wvpl->GetFilePos();              file_offset_t wvplFileOffset = wvpl->GetFilePos();
1530              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1531              while (wave) {              while (wave) {
1532                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1533                      unsigned long waveFileOffset = wave->GetFilePos();                      file_offset_t waveFileOffset = wave->GetFilePos();
1534                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1535                  }                  }
1536                  wave = wvpl->GetNextSubList();                  wave = wvpl->GetNextSubList();
# Line 1133  namespace DLS { Line 1539  namespace DLS {
1539          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)
1540              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1541              if (dwpl) {              if (dwpl) {
1542                  unsigned long dwplFileOffset = dwpl->GetFilePos();                  file_offset_t dwplFileOffset = dwpl->GetFilePos();
1543                  RIFF::List* wave = dwpl->GetFirstSubList();                  RIFF::List* wave = dwpl->GetFirstSubList();
1544                  while (wave) {                  while (wave) {
1545                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
1546                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
1547                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1548                      }                      }
1549                      wave = dwpl->GetNextSubList();                      wave = dwpl->GetNextSubList();
# Line 1239  namespace DLS { Line 1645  namespace DLS {
1645      }      }
1646    
1647      /**      /**
1648         * Returns extension file of given index. Extension files are used
1649         * sometimes to circumvent the 2 GB file size limit of the RIFF format and
1650         * of certain operating systems in general. In this case, instead of just
1651         * using one file, the content is spread among several files with similar
1652         * file name scheme. This is especially used by some GigaStudio sound
1653         * libraries.
1654         *
1655         * @param index - index of extension file
1656         * @returns sought extension file, NULL if index out of bounds
1657         * @see GetFileName()
1658         */
1659        RIFF::File* File::GetExtensionFile(int index) {
1660            if (index < 0 || index >= ExtensionFiles.size()) return NULL;
1661            std::list<RIFF::File*>::iterator iter = ExtensionFiles.begin();
1662            for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i)
1663                if (i == index) return *iter;
1664            return NULL;
1665        }
1666    
1667        /** @brief File name of this DLS file.
1668         *
1669         * This method returns the file name as it was provided when loading
1670         * the respective DLS file. However in case the File object associates
1671         * an empty, that is new DLS file, which was not yet saved to disk,
1672         * this method will return an empty string.
1673         *
1674         * @see GetExtensionFile()
1675         */
1676        String File::GetFileName() {
1677            return pRIFF->GetFileName();
1678        }
1679        
1680        /**
1681         * You may call this method store a future file name, so you don't have to
1682         * to pass it to the Save() call later on.
1683         */
1684        void File::SetFileName(const String& name) {
1685            pRIFF->SetFileName(name);
1686        }
1687    
1688        /**
1689       * Apply all the DLS file's current instruments, samples and settings to       * Apply all the DLS file's current instruments, samples and settings to
1690       * the respective RIFF chunks. You have to call Save() to make changes       * the respective RIFF chunks. You have to call Save() to make changes
1691       * persistent.       * persistent.
1692       *       *
1693         * @param pProgress - callback function for progress notification
1694       * @throws Exception - on errors       * @throws Exception - on errors
1695       */       */
1696      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
1697          // first update base class's chunks          // first update base class's chunks
1698          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1699    
1700          // if version struct exists, update 'vers' chunk          // if version struct exists, update 'vers' chunk
1701          if (pVersion) {          if (pVersion) {
1702              RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);              RIFF::Chunk* ckVersion    = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1703              if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);              if (!ckVersion) ckVersion = pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
1704              uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();              uint8_t* pData = (uint8_t*) ckVersion->LoadChunkData();
1705              memccpy(pData, pVersion, 2, 4);              store16(&pData[0], pVersion->minor);
1706                store16(&pData[2], pVersion->major);
1707                store16(&pData[4], pVersion->build);
1708                store16(&pData[6], pVersion->release);
1709          }          }
1710    
1711          // update 'colh' chunk          // update 'colh' chunk
# Line 1262  namespace DLS { Line 1713  namespace DLS {
1713          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1714          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1715          uint8_t* pData = (uint8_t*) colh->LoadChunkData();          uint8_t* pData = (uint8_t*) colh->LoadChunkData();
1716          memccpy(pData, &Instruments, 1, 4);          store32(pData, Instruments);
1717    
1718          // update instrument's chunks          // update instrument's chunks
1719          if (pInstruments) {          if (pInstruments) {
1720                // divide local progress into subprogress
1721                progress_t subprogress;
1722                __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1723    
1724                // do the actual work
1725              InstrumentList::iterator iter = pInstruments->begin();              InstrumentList::iterator iter = pInstruments->begin();
1726              InstrumentList::iterator end  = pInstruments->end();              InstrumentList::iterator end  = pInstruments->end();
1727              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1728                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1729                    progress_t subsubprogress;
1730                    __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
1731                    // do the actual work
1732                    (*iter)->UpdateChunks(&subsubprogress);
1733              }              }
1734    
1735                __notify_progress(&subprogress, 1.0); // notify subprogress done
1736          }          }
1737    
1738          // update 'ptbl' chunk          // update 'ptbl' chunk
1739          const int iSamples = (pSamples) ? pSamples->size() : 0;          const int iSamples = (pSamples) ? pSamples->size() : 0;
1740          const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1741          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1742          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*/);
1743          const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;          int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1744          ptbl->Resize(iPtblSize);          ptbl->Resize(iPtblSize);
1745          pData = (uint8_t*) ptbl->LoadChunkData();          pData = (uint8_t*) ptbl->LoadChunkData();
1746          WavePoolCount = iSamples;          WavePoolCount = iSamples;
1747          memccpy(&pData[4], &WavePoolCount, 1, 4);          store32(&pData[4], WavePoolCount);
1748          // 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()
1749          memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);          memset(&pData[WavePoolHeaderSize], 0, iPtblSize - WavePoolHeaderSize);
1750    
1751          // update sample's chunks          // update sample's chunks
1752          if (pSamples) {          if (pSamples) {
1753                // divide local progress into subprogress
1754                progress_t subprogress;
1755                __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
1756    
1757                // do the actual work
1758              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1759              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1760              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1761                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1762                    progress_t subsubprogress;
1763                    __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
1764                    // do the actual work
1765                    (*iter)->UpdateChunks(&subsubprogress);
1766              }              }
1767    
1768                __notify_progress(&subprogress, 1.0); // notify subprogress done
1769          }          }
1770    
1771            // the RIFF file to be written might now been grown >= 4GB or might
1772            // been shrunk < 4GB, so we might need to update the wave pool offset
1773            // size and thus accordingly we would need to resize the wave pool
1774            // chunk
1775            const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
1776            const bool bRequires64Bit = (finalFileSize >> 32) != 0;
1777            if (b64BitWavePoolOffsets != bRequires64Bit) {
1778                b64BitWavePoolOffsets = bRequires64Bit;
1779                iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1780                iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1781                ptbl->Resize(iPtblSize);
1782            }
1783    
1784            __notify_progress(pProgress, 1.0); // notify done
1785      }      }
1786    
1787      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1308  namespace DLS { Line 1796  namespace DLS {
1796       * the new file (given by \a Path) afterwards.       * the new file (given by \a Path) afterwards.
1797       *       *
1798       * @param Path - path and file name where everything should be written to       * @param Path - path and file name where everything should be written to
1799         * @param pProgress - optional: callback function for progress notification
1800       */       */
1801      void File::Save(const String& Path) {      void File::Save(const String& Path, progress_t* pProgress) {
1802          UpdateChunks();          {
1803          pRIFF->Save(Path);              // divide local progress into subprogress
1804          __UpdateWavePoolTableChunk();              progress_t subprogress;
1805                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress
1806                // do the actual work
1807                UpdateChunks(&subprogress);
1808                
1809            }
1810            {
1811                // divide local progress into subprogress
1812                progress_t subprogress;
1813                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress
1814                // do the actual work
1815                pRIFF->Save(Path, &subprogress);
1816            }
1817            UpdateFileOffsets();
1818            __notify_progress(pProgress, 1.0); // notify done
1819      }      }
1820    
1821      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1321  namespace DLS { Line 1824  namespace DLS {
1824       * 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
1825       * have at the end of the saving process.       * have at the end of the saving process.
1826       *       *
1827         * @param pProgress - optional: callback function for progress notification
1828       * @throws RIFF::Exception if any kind of IO error occured       * @throws RIFF::Exception if any kind of IO error occured
1829       * @throws DLS::Exception  if any kind of DLS specific error occured       * @throws DLS::Exception  if any kind of DLS specific error occured
1830       */       */
1831      void File::Save() {      void File::Save(progress_t* pProgress) {
1832          UpdateChunks();          {
1833          pRIFF->Save();              // divide local progress into subprogress
1834                progress_t subprogress;
1835                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress
1836                // do the actual work
1837                UpdateChunks(&subprogress);
1838            }
1839            {
1840                // divide local progress into subprogress
1841                progress_t subprogress;
1842                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress
1843                // do the actual work
1844                pRIFF->Save(&subprogress);
1845            }
1846            UpdateFileOffsets();
1847            __notify_progress(pProgress, 1.0); // notify done
1848        }
1849    
1850        /** @brief Updates all file offsets stored all over the file.
1851         *
1852         * This virtual method is called whenever the overall file layout has been
1853         * changed (i.e. file or individual RIFF chunks have been resized). It is
1854         * then the responsibility of this method to update all file offsets stored
1855         * in the file format. For example samples are referenced by instruments by
1856         * file offsets. The gig format also stores references to instrument
1857         * scripts as file offsets, and thus it overrides this method to update
1858         * those file offsets as well.
1859         */
1860        void File::UpdateFileOffsets() {
1861          __UpdateWavePoolTableChunk();          __UpdateWavePoolTableChunk();
1862      }      }
1863    
# Line 1365  namespace DLS { Line 1896  namespace DLS {
1896          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1897          // check if 'ptbl' chunk is large enough          // check if 'ptbl' chunk is large enough
1898          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? pSamples->size() : 0;
1899          const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;          const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
1900          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
1901          // save the 'ptbl' chunk's current read/write position          // save the 'ptbl' chunk's current read/write position
1902          unsigned long ulOriginalPos = ptbl->GetPos();          file_offset_t ullOriginalPos = ptbl->GetPos();
1903          // update headers          // update headers
1904          ptbl->SetPos(0);          ptbl->SetPos(0);
1905          ptbl->WriteUint32(&WavePoolHeaderSize);          uint32_t tmp = WavePoolHeaderSize;
1906          ptbl->WriteUint32(&WavePoolCount);          ptbl->WriteUint32(&tmp);
1907            tmp = WavePoolCount;
1908            ptbl->WriteUint32(&tmp);
1909          // update offsets          // update offsets
1910          ptbl->SetPos(WavePoolHeaderSize);          ptbl->SetPos(WavePoolHeaderSize);
1911          if (b64BitWavePoolOffsets) {          if (b64BitWavePoolOffsets) {
1912              for (int i = 0 ; i < WavePoolCount ; i++) {              for (int i = 0 ; i < WavePoolCount ; i++) {
1913                  ptbl->WriteUint32(&pWavePoolTableHi[i]);                  tmp = pWavePoolTableHi[i];
1914                  ptbl->WriteUint32(&pWavePoolTable[i]);                  ptbl->WriteUint32(&tmp);
1915                    tmp = pWavePoolTable[i];
1916                    ptbl->WriteUint32(&tmp);
1917              }              }
1918          } else { // conventional 32 bit offsets          } else { // conventional 32 bit offsets
1919              for (int i = 0 ; i < WavePoolCount ; i++)              for (int i = 0 ; i < WavePoolCount ; i++) {
1920                  ptbl->WriteUint32(&pWavePoolTable[i]);                  tmp = pWavePoolTable[i];
1921                    ptbl->WriteUint32(&tmp);
1922                }
1923          }          }
1924          // restore 'ptbl' chunk's original read/write position          // restore 'ptbl' chunk's original read/write position
1925          ptbl->SetPos(ulOriginalPos);          ptbl->SetPos(ullOriginalPos);
1926      }      }
1927    
1928      /**      /**
# Line 1408  namespace DLS { Line 1945  namespace DLS {
1945              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1946              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1947              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
1948                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
1949                  (*iter)->ulWavePoolOffset = _64BitOffset;                  (*iter)->ullWavePoolOffset = _64BitOffset;
1950                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
1951                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;
1952              }              }
# Line 1417  namespace DLS { Line 1954  namespace DLS {
1954              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1955              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1956              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
1957                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
1958                  (*iter)->ulWavePoolOffset = _64BitOffset;                  (*iter)->ullWavePoolOffset = _64BitOffset;
1959                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
1960              }              }
1961          }          }

Legend:
Removed from v.902  
changed lines
  Added in v.2912

  ViewVC Help
Powered by ViewVC