/[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 1179 by persson, Sat May 12 11:25:04 2007 UTC revision 3463 by schoenebeck, Sun Feb 10 19:58:24 2019 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2007 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 <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 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();
# 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 233  namespace DLS { Line 253  namespace DLS {
253       * @param list - pointer to a list chunk which contains an 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          UseFixedLengthStrings = false;          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 262  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 286  namespace DLS { Line 321  namespace DLS {
321       * @param lstINFO  - parent (INFO) RIFF list chunk       * @param lstINFO  - parent (INFO) RIFF list chunk
322       * @param s        - current value of info field       * @param s        - current value of info field
323       * @param sDefault - default value       * @param sDefault - default value
      * @param bUseFixedLengthStrings - should a specific string size be forced in the chunk?  
      * @param size     - wanted size of the INFO chunk. This is ignored if bUseFixedLengthStrings is false.  
324       */       */
325      void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault, bool bUseFixedLengthStrings, int size) {      void Info::SaveString(uint32_t ChunkID, RIFF::List* lstINFO, const String& s, const String& sDefault) {
326            int size = 0;
327            if (pFixedStringLengths) {
328                for (int i = 0 ; pFixedStringLengths[i].length ; i++) {
329                    if (pFixedStringLengths[i].chunkId == ChunkID) {
330                        size = pFixedStringLengths[i].length;
331                        break;
332                    }
333                }
334            }
335          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);          RIFF::Chunk* ck = lstINFO->GetSubChunk(ChunkID);
336          ::SaveString(ChunkID, ck, lstINFO, s, sDefault, bUseFixedLengthStrings, size); // function from helper.h          ::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
# Line 336  namespace DLS { Line 380  namespace DLS {
380    
381          // save values          // save values
382    
383          // (the string size values are for gig files; they are only          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""));
384          // used if UseFixedLengthStrings is set to true)          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""));
385          SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName, UseFixedLengthStrings,          SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""));
386                     resourceType == RIFF_TYPE_DLS ? 128 : 64);          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments);
387          SaveString(CHUNK_ID_IARL, lstINFO, ArchivalLocation, String(""), UseFixedLengthStrings, 256);          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""));
388          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate, UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_ICRD, lstINFO, CreationDate, defaultCreationDate);
389          SaveString(CHUNK_ID_ICMT, lstINFO, Comments, defaultComments, UseFixedLengthStrings, 1024);          SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""));
390          SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""), UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""));
391          SaveString(CHUNK_ID_ICOP, lstINFO, Copyright, String(""), UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""));
392          SaveString(CHUNK_ID_IART, lstINFO, Artists, String(""), UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""));
393          SaveString(CHUNK_ID_IGNR, lstINFO, Genre, String(""), UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_INAM, lstINFO, Name, defaultName);
394          SaveString(CHUNK_ID_IKEY, lstINFO, Keywords, String(""), UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_IPRD, lstINFO, Product, String(""));
395          SaveString(CHUNK_ID_IENG, lstINFO, Engineer, String(""), UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""));
396          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""), UseFixedLengthStrings, 128);          SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware);
397          SaveString(CHUNK_ID_ISFT, lstINFO, Software, defaultSoftware, UseFixedLengthStrings,          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""));
398                     resourceType == LIST_TYPE_INS ?          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
399                     (Software == "" ? defaultSoftware.length()+1 : Software.length()+1) : 128);          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
400          SaveString(CHUNK_ID_IMED, lstINFO, Medium, String(""), UseFixedLengthStrings, 128);      }
401          SaveString(CHUNK_ID_ISRC, lstINFO, Source, String(""), UseFixedLengthStrings, 128);      
402          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""), UseFixedLengthStrings, 128);      /**
403          SaveString(CHUNK_ID_ICMS, lstINFO, Commissioned, String(""), UseFixedLengthStrings, 128);       * Make a deep copy of the Info object given by @a orig and assign it to
404          SaveString(CHUNK_ID_ISBJ, lstINFO, Subject, String(""), UseFixedLengthStrings, 128);       * 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 403  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 425  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 450  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
# Line 487  namespace DLS { Line 628  namespace DLS {
628      /**      /**
629       * Adds a new sample loop with the provided loop definition.       * Adds a new sample loop with the provided loop definition.
630       *       *
631       * @param - points to a loop definition that is to be copied       * @param pLoopDef - points to a loop definition that is to be copied
632       */       */
633      void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {      void Sampler::AddSampleLoop(sample_loop_t* pLoopDef) {
634          sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];          sample_loop_t* pNewLoops = new sample_loop_t[SampleLoops + 1];
# Line 516  namespace DLS { Line 657  namespace DLS {
657          // copy old loops array (skipping given loop)          // copy old loops array (skipping given loop)
658          for (int i = 0, o = 0; i < SampleLoops; i++) {          for (int i = 0, o = 0; i < SampleLoops; i++) {
659              if (&pSampleLoops[i] == pLoopDef) continue;              if (&pSampleLoops[i] == pLoopDef) continue;
660              if (o == SampleLoops - 1)              if (o == SampleLoops - 1) {
661                    delete[] pNewLoops;
662                  throw Exception("Could not delete Sample Loop, because it does not exist");                  throw Exception("Could not delete Sample Loop, because it does not exist");
663                }
664              pNewLoops[o] = pSampleLoops[i];              pNewLoops[o] = pSampleLoops[i];
665              o++;              o++;
666          }          }
# Line 526  namespace DLS { Line 669  namespace DLS {
669          pSampleLoops = pNewLoops;          pSampleLoops = pNewLoops;
670          SampleLoops--;          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 547  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 590  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 640  namespace DLS { Line 855  namespace DLS {
855       * @returns number of sample points or 0 if FormatTag != DLS_WAVE_FORMAT_PCM       * @returns number of sample points or 0 if FormatTag != DLS_WAVE_FORMAT_PCM
856       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
857       */       */
858      unsigned long Sample::GetSize() {      file_offset_t Sample::GetSize() const {
859          if (FormatTag != DLS_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      }      }
# Line 667  namespace DLS { Line 882  namespace DLS {
882       * FormatTag must be DLS_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 NewSize - new sample wave data size in sample points (must be
886       *                   greater than zero)       *                  greater than zero)
887       * @throws Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM
888       * @throws Exception if \a iNewSize is less than 1       * @throws Exception if \a NewSize is less than 1 or unrealistic large
889       * @see File::Save(), FrameSize, FormatTag       * @see File::Save(), FrameSize, FormatTag
890       */       */
891      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
892          if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");          if (FormatTag != DLS_WAVE_FORMAT_PCM) throw Exception("Sample's format is not DLS_WAVE_FORMAT_PCM");
893          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");
894          const int iSizeInBytes = iNewSize * FrameSize;          if ((NewSize >> 48) != 0)
895                throw Exception("Unrealistic high DLS sample size detected");
896            const file_offset_t sizeInBytes = NewSize * FrameSize;
897          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
898          if (pCkData) pCkData->Resize(iSizeInBytes);          if (pCkData) pCkData->Resize(sizeInBytes);
899          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, sizeInBytes);
900      }      }
901    
902      /**      /**
# Line 698  namespace DLS { Line 915  namespace DLS {
915       * @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
916       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
917       */       */
918      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) {
919          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
920          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");
921          unsigned long orderedBytes = SampleCount * FrameSize;          file_offset_t orderedBytes = SampleCount * FrameSize;
922          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
923          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
924                                          : result / FrameSize;                                          : result / FrameSize;
925      }      }
# Line 716  namespace DLS { Line 933  namespace DLS {
933       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
934       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
935       */       */
936      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
937          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
938          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?
939      }      }
# Line 736  namespace DLS { Line 953  namespace DLS {
953       * @throws Exception if current sample size is too small       * @throws Exception if current sample size is too small
954       * @see LoadSampleData()       * @see LoadSampleData()
955       */       */
956      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
957          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0; // failed: wave data not PCM format
958          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");
959          return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?          return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
# Line 746  namespace DLS { Line 963  namespace DLS {
963       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
964       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
965       *       *
966         * @param pProgress - callback function for progress notification
967       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
968       *                   was provided yet       *                   was provided yet
969       */       */
970      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
971          if (FormatTag != DLS_WAVE_FORMAT_PCM)          if (FormatTag != DLS_WAVE_FORMAT_PCM)
972              throw Exception("Could not save sample, only PCM format is supported");              throw Exception("Could not save sample, only PCM format is supported");
973          // 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
974          if (!pCkData)          if (!pCkData)
975              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");
976          // update chunks of base class as well          // update chunks of base class as well
977          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
978          // make sure 'fmt' chunk exists          // make sure 'fmt' chunk exists
979          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
980          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
# Line 778  namespace DLS { Line 996  namespace DLS {
996      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) {
997          pCkRegion = rgnList;          pCkRegion = rgnList;
998    
999          // articulation informations          // articulation information
1000          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
1001          if (rgnh) {          if (rgnh) {
1002              rgnh->Read(&KeyRange, 2, 2);              rgnh->Read(&KeyRange, 2, 2);
# Line 800  namespace DLS { Line 1018  namespace DLS {
1018          }          }
1019          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
1020    
1021          // sample informations          // sample information
1022          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
1023          if (wlnk) {          if (wlnk) {
1024              WaveLinkOptionFlags = wlnk->ReadUint16();              WaveLinkOptionFlags = wlnk->ReadUint16();
# Line 831  namespace DLS { Line 1049  namespace DLS {
1049      Sample* Region::GetSample() {      Sample* Region::GetSample() {
1050          if (pSample) return pSample;          if (pSample) return pSample;
1051          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1052          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1053          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample();
1054          while (sample) {          while (sample) {
1055              if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);              if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1056              sample = file->GetNextSample();              sample = file->GetNextSample();
1057          }          }
1058          return NULL;          return NULL;
# Line 851  namespace DLS { Line 1069  namespace DLS {
1069      }      }
1070    
1071      /**      /**
1072         * Modifies the key range of this Region and makes sure the respective
1073         * chunks are in correct order.
1074         *
1075         * @param Low  - lower end of key range
1076         * @param High - upper end of key range
1077         */
1078        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
1079            KeyRange.low  = Low;
1080            KeyRange.high = High;
1081    
1082            // make sure regions are already loaded
1083            Instrument* pInstrument = (Instrument*) GetParent();
1084            if (!pInstrument->pRegions) pInstrument->LoadRegions();
1085            if (!pInstrument->pRegions) return;
1086    
1087            // find the r which is the first one to the right of this region
1088            // at its new position
1089            Region* r = NULL;
1090            Region* prev_region = NULL;
1091            for (
1092                Instrument::RegionList::iterator iter = pInstrument->pRegions->begin();
1093                iter != pInstrument->pRegions->end(); iter++
1094            ) {
1095                if ((*iter)->KeyRange.low > this->KeyRange.low) {
1096                    r = *iter;
1097                    break;
1098                }
1099                prev_region = *iter;
1100            }
1101    
1102            // place this region before r if it's not already there
1103            if (prev_region != this) pInstrument->MoveRegion(this, r);
1104        }
1105    
1106        /**
1107       * Apply Region settings to the respective RIFF chunks. You have to       * Apply Region settings to the respective RIFF chunks. You have to
1108       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
1109       *       *
1110         * @param pProgress - callback function for progress notification
1111       * @throws Exception - if the Region's sample could not be found       * @throws Exception - if the Region's sample could not be found
1112       */       */
1113      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
1114          // make sure 'rgnh' chunk exists          // make sure 'rgnh' chunk exists
1115          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1116          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
# Line 875  namespace DLS { Line 1129  namespace DLS {
1129    
1130          // update chunks of base classes as well (but skip Resource,          // update chunks of base classes as well (but skip Resource,
1131          // as a rgn doesn't seem to have dlid and INFO chunks)          // as a rgn doesn't seem to have dlid and INFO chunks)
1132          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1133          Sampler::UpdateChunks();          Sampler::UpdateChunks(pProgress);
1134    
1135          // make sure 'wlnk' chunk exists          // make sure 'wlnk' chunk exists
1136          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
# Line 901  namespace DLS { Line 1155  namespace DLS {
1155                  }                  }
1156              }              }
1157          }          }
         if (index < 0) throw Exception("Could not save Region, could not find Region's sample");  
1158          WavePoolTableIndex = index;          WavePoolTableIndex = index;
1159          // update 'wlnk' chunk          // update 'wlnk' chunk
1160          store16(&pData[0], WaveLinkOptionFlags);          store16(&pData[0], WaveLinkOptionFlags);
# Line 909  namespace DLS { Line 1162  namespace DLS {
1162          store32(&pData[4], Channel);          store32(&pData[4], Channel);
1163          store32(&pData[8], WavePoolTableIndex);          store32(&pData[8], WavePoolTableIndex);
1164      }      }
1165        
1166        /**
1167         * Make a (semi) deep copy of the Region object given by @a orig and assign
1168         * it to this object.
1169         *
1170         * Note that the sample pointer referenced by @a orig is simply copied as
1171         * memory address. Thus the respective sample is shared, not duplicated!
1172         *
1173         * @param orig - original Region object to be copied from
1174         */
1175        void Region::CopyAssign(const Region* orig) {
1176            // handle base classes
1177            Resource::CopyAssign(orig);
1178            Articulator::CopyAssign(orig);
1179            Sampler::CopyAssign(orig);
1180            // handle actual own attributes of this class
1181            // (the trivial ones)
1182            VelocityRange = orig->VelocityRange;
1183            KeyGroup = orig->KeyGroup;
1184            Layer = orig->Layer;
1185            SelfNonExclusive = orig->SelfNonExclusive;
1186            PhaseMaster = orig->PhaseMaster;
1187            PhaseGroup = orig->PhaseGroup;
1188            MultiChannel = orig->MultiChannel;
1189            Channel = orig->Channel;
1190            // only take the raw sample reference if the two Region objects are
1191            // part of the same file
1192            if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1193                WavePoolTableIndex = orig->WavePoolTableIndex;
1194                pSample = orig->pSample;
1195            } else {
1196                WavePoolTableIndex = -1;
1197                pSample = NULL;
1198            }
1199            FormatOptionFlags = orig->FormatOptionFlags;
1200            WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1201            // handle the last, a bit sensible attribute
1202            SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1203        }
1204    
1205    
1206  // *************** Instrument ***************  // *************** Instrument ***************
# Line 986  namespace DLS { Line 1277  namespace DLS {
1277          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1278          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
1279          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
1280          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1281          return pNewRegion;          return pNewRegion;
1282      }      }
1283    
1284      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1285          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1286          lrgn->MoveSubChunk(pSrc->pCkRegion, pDst ? pDst->pCkRegion : 0);          lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1287    
1288          pRegions->remove(pSrc);          pRegions->remove(pSrc);
1289          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
# Line 1004  namespace DLS { Line 1295  namespace DLS {
1295          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1296          if (iter == pRegions->end()) return;          if (iter == pRegions->end()) return;
1297          pRegions->erase(iter);          pRegions->erase(iter);
1298          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1299          delete pRegion;          delete pRegion;
1300      }      }
1301    
# Line 1012  namespace DLS { Line 1303  namespace DLS {
1303       * Apply Instrument with all its Regions to the respective RIFF chunks.       * Apply Instrument with all its Regions to the respective RIFF chunks.
1304       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
1305       *       *
1306         * @param pProgress - callback function for progress notification
1307       * @throws Exception - on errors       * @throws Exception - on errors
1308       */       */
1309      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
1310          // first update base classes' chunks          // first update base classes' chunks
1311          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1312          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1313          // make sure 'insh' chunk exists          // make sure 'insh' chunk exists
1314          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1315          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1316          uint8_t* pData = (uint8_t*) insh->LoadChunkData();          uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1317          // update 'insh' chunk          // update 'insh' chunk
1318          Regions = (pRegions) ? pRegions->size() : 0;          Regions = (pRegions) ? uint32_t(pRegions->size()) : 0;
1319          midi_locale_t locale;          midi_locale_t locale;
1320          locale.instrument = MIDIProgram;          locale.instrument = MIDIProgram;
1321          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
# Line 1036  namespace DLS { Line 1328  namespace DLS {
1328          if (!pRegions) return;          if (!pRegions) return;
1329          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
1330          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
1331          for (; iter != end; ++iter) {          for (int i = 0; iter != end; ++iter, ++i) {
1332              (*iter)->UpdateChunks();              // divide local progress into subprogress
1333                progress_t subprogress;
1334                __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1335                // do the actual work
1336                (*iter)->UpdateChunks(&subprogress);
1337          }          }
1338            __notify_progress(pProgress, 1.0); // notify done
1339      }      }
1340    
1341      /** @brief Destructor.      /** @brief Destructor.
# Line 1060  namespace DLS { Line 1357  namespace DLS {
1357          RIFF::List* pParent = pCkInstrument->GetParent();          RIFF::List* pParent = pCkInstrument->GetParent();
1358          pParent->DeleteSubChunk(pCkInstrument);          pParent->DeleteSubChunk(pCkInstrument);
1359      }      }
1360        
1361        void Instrument::CopyAssignCore(const Instrument* orig) {
1362            // handle base classes
1363            Resource::CopyAssign(orig);
1364            Articulator::CopyAssign(orig);
1365            // handle actual own attributes of this class
1366            // (the trivial ones)
1367            IsDrum = orig->IsDrum;
1368            MIDIBank = orig->MIDIBank;
1369            MIDIBankCoarse = orig->MIDIBankCoarse;
1370            MIDIBankFine = orig->MIDIBankFine;
1371            MIDIProgram = orig->MIDIProgram;
1372        }
1373        
1374        /**
1375         * Make a (semi) deep copy of the Instrument object given by @a orig and assign
1376         * it to this object.
1377         *
1378         * Note that all sample pointers referenced by @a orig are simply copied as
1379         * memory address. Thus the respective samples are shared, not duplicated!
1380         *
1381         * @param orig - original Instrument object to be copied from
1382         */
1383        void Instrument::CopyAssign(const Instrument* orig) {
1384            CopyAssignCore(orig);
1385            // delete all regions first
1386            while (Regions) DeleteRegion(GetFirstRegion());
1387            // now recreate and copy regions
1388            {
1389                RegionList::const_iterator it = orig->pRegions->begin();
1390                for (int i = 0; i < orig->Regions; ++i, ++it) {
1391                    Region* dstRgn = AddRegion();
1392                    //NOTE: Region does semi-deep copy !
1393                    dstRgn->CopyAssign(*it);
1394                }
1395            }
1396        }
1397    
1398    
1399  // *************** File ***************  // *************** File ***************
# Line 1073  namespace DLS { Line 1406  namespace DLS {
1406       * a DLS file.       * a DLS file.
1407       */       */
1408      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1409            pRIFF->SetByteOrder(RIFF::endian_little);
1410            bOwningRiff = true;
1411          pVersion = new version_t;          pVersion = new version_t;
1412          pVersion->major   = 0;          pVersion->major   = 0;
1413          pVersion->minor   = 0;          pVersion->minor   = 0;
# Line 1103  namespace DLS { Line 1438  namespace DLS {
1438      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1439          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1440          this->pRIFF = pRIFF;          this->pRIFF = pRIFF;
1441            bOwningRiff = false;
1442          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1443          if (ckVersion) {          if (ckVersion) {
1444              pVersion = new version_t;              pVersion = new version_t;
# Line 1135  namespace DLS { Line 1470  namespace DLS {
1470                  for (int i = 0 ; i < WavePoolCount ; i++) {                  for (int i = 0 ; i < WavePoolCount ; i++) {
1471                      pWavePoolTableHi[i] = ptbl->ReadUint32();                      pWavePoolTableHi[i] = ptbl->ReadUint32();
1472                      pWavePoolTable[i] = ptbl->ReadUint32();                      pWavePoolTable[i] = ptbl->ReadUint32();
1473                      if (pWavePoolTable[i] & 0x80000000)                      //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1474                          throw DLS::Exception("Files larger than 2 GB not yet supported");                      //if (pWavePoolTable[i] & 0x80000000)
1475                        //    throw DLS::Exception("Files larger than 2 GB not yet supported");
1476                  }                  }
1477              } else { // conventional 32 bit offsets              } else { // conventional 32 bit offsets
1478                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
# Line 1174  namespace DLS { Line 1510  namespace DLS {
1510          if (pVersion) delete pVersion;          if (pVersion) delete pVersion;
1511          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++)
1512              delete *i;              delete *i;
1513            if (bOwningRiff)
1514                delete pRIFF;
1515      }      }
1516    
1517      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
# Line 1193  namespace DLS { Line 1531  namespace DLS {
1531          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
1532          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1533          if (wvpl) {          if (wvpl) {
1534              unsigned long wvplFileOffset = wvpl->GetFilePos();              file_offset_t wvplFileOffset = wvpl->GetFilePos();
1535              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1536              while (wave) {              while (wave) {
1537                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1538                      unsigned long waveFileOffset = wave->GetFilePos();                      file_offset_t waveFileOffset = wave->GetFilePos();
1539                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1540                  }                  }
1541                  wave = wvpl->GetNextSubList();                  wave = wvpl->GetNextSubList();
# Line 1206  namespace DLS { Line 1544  namespace DLS {
1544          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)
1545              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1546              if (dwpl) {              if (dwpl) {
1547                  unsigned long dwplFileOffset = dwpl->GetFilePos();                  file_offset_t dwplFileOffset = dwpl->GetFilePos();
1548                  RIFF::List* wave = dwpl->GetFirstSubList();                  RIFF::List* wave = dwpl->GetFirstSubList();
1549                  while (wave) {                  while (wave) {
1550                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
1551                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
1552                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1553                      }                      }
1554                      wave = dwpl->GetNextSubList();                      wave = dwpl->GetNextSubList();
# Line 1312  namespace DLS { Line 1650  namespace DLS {
1650      }      }
1651    
1652      /**      /**
1653         * Returns extension file of given index. Extension files are used
1654         * sometimes to circumvent the 2 GB file size limit of the RIFF format and
1655         * of certain operating systems in general. In this case, instead of just
1656         * using one file, the content is spread among several files with similar
1657         * file name scheme. This is especially used by some GigaStudio sound
1658         * libraries.
1659         *
1660         * @param index - index of extension file
1661         * @returns sought extension file, NULL if index out of bounds
1662         * @see GetFileName()
1663         */
1664        RIFF::File* File::GetExtensionFile(int index) {
1665            if (index < 0 || index >= ExtensionFiles.size()) return NULL;
1666            std::list<RIFF::File*>::iterator iter = ExtensionFiles.begin();
1667            for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i)
1668                if (i == index) return *iter;
1669            return NULL;
1670        }
1671    
1672        /** @brief File name of this DLS file.
1673         *
1674         * This method returns the file name as it was provided when loading
1675         * the respective DLS file. However in case the File object associates
1676         * an empty, that is new DLS file, which was not yet saved to disk,
1677         * this method will return an empty string.
1678         *
1679         * @see GetExtensionFile()
1680         */
1681        String File::GetFileName() {
1682            return pRIFF->GetFileName();
1683        }
1684        
1685        /**
1686         * You may call this method store a future file name, so you don't have to
1687         * to pass it to the Save() call later on.
1688         */
1689        void File::SetFileName(const String& name) {
1690            pRIFF->SetFileName(name);
1691        }
1692    
1693        /**
1694       * Apply all the DLS file's current instruments, samples and settings to       * Apply all the DLS file's current instruments, samples and settings to
1695       * the respective RIFF chunks. You have to call Save() to make changes       * the respective RIFF chunks. You have to call Save() to make changes
1696       * persistent.       * persistent.
1697       *       *
1698         * @param pProgress - callback function for progress notification
1699       * @throws Exception - on errors       * @throws Exception - on errors
1700       */       */
1701      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
1702          // first update base class's chunks          // first update base class's chunks
1703          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1704    
1705          // if version struct exists, update 'vers' chunk          // if version struct exists, update 'vers' chunk
1706          if (pVersion) {          if (pVersion) {
# Line 1334  namespace DLS { Line 1714  namespace DLS {
1714          }          }
1715    
1716          // update 'colh' chunk          // update 'colh' chunk
1717          Instruments = (pInstruments) ? pInstruments->size() : 0;          Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
1718          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1719          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1720          uint8_t* pData = (uint8_t*) colh->LoadChunkData();          uint8_t* pData = (uint8_t*) colh->LoadChunkData();
# Line 1342  namespace DLS { Line 1722  namespace DLS {
1722    
1723          // update instrument's chunks          // update instrument's chunks
1724          if (pInstruments) {          if (pInstruments) {
1725                // divide local progress into subprogress
1726                progress_t subprogress;
1727                __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1728    
1729                // do the actual work
1730              InstrumentList::iterator iter = pInstruments->begin();              InstrumentList::iterator iter = pInstruments->begin();
1731              InstrumentList::iterator end  = pInstruments->end();              InstrumentList::iterator end  = pInstruments->end();
1732              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1733                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1734                    progress_t subsubprogress;
1735                    __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
1736                    // do the actual work
1737                    (*iter)->UpdateChunks(&subsubprogress);
1738              }              }
1739    
1740                __notify_progress(&subprogress, 1.0); // notify subprogress done
1741          }          }
1742    
1743          // update 'ptbl' chunk          // update 'ptbl' chunk
1744          const int iSamples = (pSamples) ? pSamples->size() : 0;          const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
1745          const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1746          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1747          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*/);
1748          const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;          int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1749          ptbl->Resize(iPtblSize);          ptbl->Resize(iPtblSize);
1750          pData = (uint8_t*) ptbl->LoadChunkData();          pData = (uint8_t*) ptbl->LoadChunkData();
1751          WavePoolCount = iSamples;          WavePoolCount = iSamples;
# Line 1364  namespace DLS { Line 1755  namespace DLS {
1755    
1756          // update sample's chunks          // update sample's chunks
1757          if (pSamples) {          if (pSamples) {
1758                // divide local progress into subprogress
1759                progress_t subprogress;
1760                __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
1761    
1762                // do the actual work
1763              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1764              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1765              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1766                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1767              }                  progress_t subsubprogress;
1768                    __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
1769                    // do the actual work
1770                    (*iter)->UpdateChunks(&subsubprogress);
1771                }
1772    
1773                __notify_progress(&subprogress, 1.0); // notify subprogress done
1774            }
1775    
1776            // the RIFF file to be written might now been grown >= 4GB or might
1777            // been shrunk < 4GB, so we might need to update the wave pool offset
1778            // size and thus accordingly we would need to resize the wave pool
1779            // chunk
1780            const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
1781            const bool bRequires64Bit = (finalFileSize >> 32) != 0;
1782            if (b64BitWavePoolOffsets != bRequires64Bit) {
1783                b64BitWavePoolOffsets = bRequires64Bit;
1784                iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1785                iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1786                ptbl->Resize(iPtblSize);
1787          }          }
1788    
1789            __notify_progress(pProgress, 1.0); // notify done
1790      }      }
1791    
1792      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1384  namespace DLS { Line 1801  namespace DLS {
1801       * the new file (given by \a Path) afterwards.       * the new file (given by \a Path) afterwards.
1802       *       *
1803       * @param Path - path and file name where everything should be written to       * @param Path - path and file name where everything should be written to
1804         * @param pProgress - optional: callback function for progress notification
1805       */       */
1806      void File::Save(const String& Path) {      void File::Save(const String& Path, progress_t* pProgress) {
1807          UpdateChunks();          {
1808          pRIFF->Save(Path);              // divide local progress into subprogress
1809          __UpdateWavePoolTableChunk();              progress_t subprogress;
1810                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress
1811                // do the actual work
1812                UpdateChunks(&subprogress);
1813                
1814            }
1815            {
1816                // divide local progress into subprogress
1817                progress_t subprogress;
1818                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress
1819                // do the actual work
1820                pRIFF->Save(Path, &subprogress);
1821            }
1822            UpdateFileOffsets();
1823            __notify_progress(pProgress, 1.0); // notify done
1824      }      }
1825    
1826      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1397  namespace DLS { Line 1829  namespace DLS {
1829       * 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
1830       * have at the end of the saving process.       * have at the end of the saving process.
1831       *       *
1832       * @throws RIFF::Exception if any kind of IO error occured       * @param pProgress - optional: callback function for progress notification
1833       * @throws DLS::Exception  if any kind of DLS specific error occured       * @throws RIFF::Exception if any kind of IO error occurred
1834         * @throws DLS::Exception  if any kind of DLS specific error occurred
1835         */
1836        void File::Save(progress_t* pProgress) {
1837            {
1838                // divide local progress into subprogress
1839                progress_t subprogress;
1840                __divide_progress(pProgress, &subprogress, 2.f, 0.f); // arbitrarily subdivided into 50% of total progress
1841                // do the actual work
1842                UpdateChunks(&subprogress);
1843            }
1844            {
1845                // divide local progress into subprogress
1846                progress_t subprogress;
1847                __divide_progress(pProgress, &subprogress, 2.f, 1.f); // arbitrarily subdivided into 50% of total progress
1848                // do the actual work
1849                pRIFF->Save(&subprogress);
1850            }
1851            UpdateFileOffsets();
1852            __notify_progress(pProgress, 1.0); // notify done
1853        }
1854    
1855        /** @brief Updates all file offsets stored all over the file.
1856         *
1857         * This virtual method is called whenever the overall file layout has been
1858         * changed (i.e. file or individual RIFF chunks have been resized). It is
1859         * then the responsibility of this method to update all file offsets stored
1860         * in the file format. For example samples are referenced by instruments by
1861         * file offsets. The gig format also stores references to instrument
1862         * scripts as file offsets, and thus it overrides this method to update
1863         * those file offsets as well.
1864       */       */
1865      void File::Save() {      void File::UpdateFileOffsets() {
         UpdateChunks();  
         pRIFF->Save();  
1866          __UpdateWavePoolTableChunk();          __UpdateWavePoolTableChunk();
1867      }      }
1868    
# Line 1440  namespace DLS { Line 1900  namespace DLS {
1900          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1901          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1902          // check if 'ptbl' chunk is large enough          // check if 'ptbl' chunk is large enough
1903          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
1904          const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;          const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
1905          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
1906          // save the 'ptbl' chunk's current read/write position          // save the 'ptbl' chunk's current read/write position
1907          unsigned long ulOriginalPos = ptbl->GetPos();          file_offset_t ullOriginalPos = ptbl->GetPos();
1908          // update headers          // update headers
1909          ptbl->SetPos(0);          ptbl->SetPos(0);
1910          uint32_t tmp = WavePoolHeaderSize;          uint32_t tmp = WavePoolHeaderSize;
# Line 1467  namespace DLS { Line 1927  namespace DLS {
1927              }              }
1928          }          }
1929          // restore 'ptbl' chunk's original read/write position          // restore 'ptbl' chunk's original read/write position
1930          ptbl->SetPos(ulOriginalPos);          ptbl->SetPos(ullOriginalPos);
1931      }      }
1932    
1933      /**      /**
# Line 1476  namespace DLS { Line 1936  namespace DLS {
1936       * exists already.       * exists already.
1937       */       */
1938      void File::__UpdateWavePoolTable() {      void File::__UpdateWavePoolTable() {
1939          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
1940          // resize wave pool table arrays          // resize wave pool table arrays
1941          if (pWavePoolTable)   delete[] pWavePoolTable;          if (pWavePoolTable)   delete[] pWavePoolTable;
1942          if (pWavePoolTableHi) delete[] pWavePoolTableHi;          if (pWavePoolTableHi) delete[] pWavePoolTableHi;
# Line 1490  namespace DLS { Line 1950  namespace DLS {
1950              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1951              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1952              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
1953                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
1954                  (*iter)->ulWavePoolOffset = _64BitOffset;                  (*iter)->ullWavePoolOffset = _64BitOffset;
1955                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
1956                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;
1957              }              }
# Line 1499  namespace DLS { Line 1959  namespace DLS {
1959              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1960              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1961              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
1962                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
1963                  (*iter)->ulWavePoolOffset = _64BitOffset;                  (*iter)->ullWavePoolOffset = _64BitOffset;
1964                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
1965              }              }
1966          }          }
# Line 1511  namespace DLS { Line 1971  namespace DLS {
1971  // *************** Exception ***************  // *************** Exception ***************
1972  // *  // *
1973    
1974      Exception::Exception(String Message) : RIFF::Exception(Message) {      Exception::Exception() : RIFF::Exception() {
1975        }
1976    
1977        Exception::Exception(String format, ...) : RIFF::Exception() {
1978            va_list arg;
1979            va_start(arg, format);
1980            Message = assemble(format, arg);
1981            va_end(arg);
1982        }
1983    
1984        Exception::Exception(String format, va_list arg) : RIFF::Exception() {
1985            Message = assemble(format, arg);
1986      }      }
1987    
1988      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.1179  
changed lines
  Added in v.3463

  ViewVC Help
Powered by ViewVC