/[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 2329 by schoenebeck, Mon Mar 12 14:59:10 2012 UTC revision 3474 by schoenebeck, Wed Feb 20 16:04:19 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-2009 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 24  Line 24 
24  #include "DLS.h"  #include "DLS.h"
25    
26  #include <algorithm>  #include <algorithm>
27    #include <vector>
28  #include <time.h>  #include <time.h>
29    
30  #ifdef __APPLE__  #ifdef __APPLE__
# Line 144  namespace DLS { Line 145  namespace DLS {
145      /**      /**
146       * Apply articulation connections to the respective RIFF chunks. You       * Apply articulation connections to the respective RIFF chunks. You
147       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
148         *
149         * @param pProgress - callback function for progress notification
150       */       */
151      void Articulation::UpdateChunks() {      void Articulation::UpdateChunks(progress_t* pProgress) {
152          const int iEntrySize = 12; // 12 bytes per connection block          const int iEntrySize = 12; // 12 bytes per connection block
153          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
154          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
# Line 217  namespace DLS { Line 220  namespace DLS {
220      /**      /**
221       * Apply all articulations to the respective RIFF chunks. You have to       * Apply all articulations to the respective RIFF chunks. You have to
222       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
223         *
224         * @param pProgress - callback function for progress notification
225       */       */
226      void Articulator::UpdateChunks() {      void Articulator::UpdateChunks(progress_t* pProgress) {
227          if (pArticulations) {          if (pArticulations) {
228              ArticulationList::iterator iter = pArticulations->begin();              ArticulationList::iterator iter = pArticulations->begin();
229              ArticulationList::iterator end  = pArticulations->end();              ArticulationList::iterator end  = pArticulations->end();
230              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
231                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
232              }              }
233          }          }
234      }      }
235        
236        /**
237         * Not yet implemented in this version, since the .gig format does
238         * not need to copy DLS articulators and so far nobody used pure
239         * DLS instrument AFAIK.
240         */
241        void Articulator::CopyAssign(const Articulator* orig) {
242            //TODO: implement deep copy assignment for this class
243        }
244    
245    
246    
# Line 327  namespace DLS { Line 341  namespace DLS {
341       *       *
342       * Apply current INFO field values to the respective INFO chunks. You       * Apply current INFO field values to the respective INFO chunks. You
343       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
344         *
345         * @param pProgress - callback function for progress notification
346       */       */
347      void Info::UpdateChunks() {      void Info::UpdateChunks(progress_t* pProgress) {
348          if (!pResourceListChunk) return;          if (!pResourceListChunk) return;
349    
350          // make sure INFO list chunk exists          // make sure INFO list chunk exists
# Line 383  namespace DLS { Line 399  namespace DLS {
399          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));          SaveString(CHUNK_ID_ISRF, lstINFO, SourceForm, String(""));
400          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
401      }      }
402        
403        /**
404         * Make a deep copy of the Info object given by @a orig and assign it to
405         * this object.
406         *
407         * @param orig - original Info object to be copied from
408         */
409        void Info::CopyAssign(const Info* orig) {
410            Name = orig->Name;
411            ArchivalLocation = orig->ArchivalLocation;
412            CreationDate = orig->CreationDate;
413            Comments = orig->Comments;
414            Product = orig->Product;
415            Copyright = orig->Copyright;
416            Artists = orig->Artists;
417            Genre = orig->Genre;
418            Keywords = orig->Keywords;
419            Engineer = orig->Engineer;
420            Technician = orig->Technician;
421            Software = orig->Software;
422            Medium = orig->Medium;
423            Source = orig->Source;
424            SourceForm = orig->SourceForm;
425            Commissioned = orig->Commissioned;
426            Subject = orig->Subject;
427            //FIXME: hmm, is copying this pointer a good idea?
428            pFixedStringLengths = orig->pFixedStringLengths;
429        }
430    
431    
432    
# Line 427  namespace DLS { Line 471  namespace DLS {
471       * will not be applied at the moment (yet).       * will not be applied at the moment (yet).
472       *       *
473       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
474         *
475         * @param pProgress - callback function for progress notification
476       */       */
477      void Resource::UpdateChunks() {      void Resource::UpdateChunks(progress_t* pProgress) {
478          pInfo->UpdateChunks();          pInfo->UpdateChunks(pProgress);
479    
480          if (pDLSID) {          if (pDLSID) {
481              // make sure 'dlid' chunk exists              // make sure 'dlid' chunk exists
# Line 448  namespace DLS { Line 494  namespace DLS {
494       * Generates a new DLSID for the resource.       * Generates a new DLSID for the resource.
495       */       */
496      void Resource::GenerateDLSID() {      void Resource::GenerateDLSID() {
497  #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)          #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
   
498          if (!pDLSID) pDLSID = new dlsid_t;          if (!pDLSID) pDLSID = new dlsid_t;
499            GenerateDLSID(pDLSID);
500            #endif
501        }
502    
503        void Resource::GenerateDLSID(dlsid_t* pDLSID) {
504    #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
505  #ifdef WIN32  #ifdef WIN32
   
506          UUID uuid;          UUID uuid;
507          UuidCreate(&uuid);          UuidCreate(&uuid);
508          pDLSID->ulData1 = uuid.Data1;          pDLSID->ulData1 = uuid.Data1;
# Line 487  namespace DLS { Line 536  namespace DLS {
536  #endif  #endif
537  #endif  #endif
538      }      }
539        
540        /**
541         * Make a deep copy of the Resource object given by @a orig and assign it
542         * to this object.
543         *
544         * @param orig - original Resource object to be copied from
545         */
546        void Resource::CopyAssign(const Resource* orig) {
547            pInfo->CopyAssign(orig->pInfo);
548        }
549    
550    
551  // *************** Sampler ***************  // *************** Sampler ***************
# Line 535  namespace DLS { Line 594  namespace DLS {
594      /**      /**
595       * Apply all sample player options to the respective RIFF chunk. You       * Apply all sample player options to the respective RIFF chunk. You
596       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
597         *
598         * @param pProgress - callback function for progress notification
599       */       */
600      void Sampler::UpdateChunks() {      void Sampler::UpdateChunks(progress_t* pProgress) {
601          // make sure 'wsmp' chunk exists          // make sure 'wsmp' chunk exists
602          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
603          int wsmpSize = uiHeaderSize + SampleLoops * 16;          int wsmpSize = uiHeaderSize + SampleLoops * 16;
# Line 612  namespace DLS { Line 673  namespace DLS {
673          pSampleLoops = pNewLoops;          pSampleLoops = pNewLoops;
674          SampleLoops--;          SampleLoops--;
675      }      }
676        
677        /**
678         * Make a deep copy of the Sampler object given by @a orig and assign it
679         * to this object.
680         *
681         * @param orig - original Sampler object to be copied from
682         */
683        void Sampler::CopyAssign(const Sampler* orig) {
684            // copy trivial scalars
685            UnityNote = orig->UnityNote;
686            FineTune = orig->FineTune;
687            Gain = orig->Gain;
688            NoSampleDepthTruncation = orig->NoSampleDepthTruncation;
689            NoSampleCompression = orig->NoSampleCompression;
690            SamplerOptions = orig->SamplerOptions;
691            
692            // copy sample loops
693            if (SampleLoops) delete[] pSampleLoops;
694            pSampleLoops = new sample_loop_t[orig->SampleLoops];
695            memcpy(pSampleLoops, orig->pSampleLoops, orig->SampleLoops * sizeof(sample_loop_t));
696            SampleLoops = orig->SampleLoops;
697        }
698    
699    
700  // *************** Sample ***************  // *************** Sample ***************
# Line 633  namespace DLS { Line 715  namespace DLS {
715       * @param WavePoolOffset - offset of this sample data from wave pool       * @param WavePoolOffset - offset of this sample data from wave pool
716       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
717       */       */
718      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) {
719          pWaveList = waveList;          pWaveList = waveList;
720          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;          ullWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE(waveList->GetFile()->GetFileOffsetSize());
721          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
722          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);
723          if (pCkFormat) {          if (pCkFormat) {
# Line 676  namespace DLS { Line 758  namespace DLS {
758          RIFF::List* pParent = pWaveList->GetParent();          RIFF::List* pParent = pWaveList->GetParent();
759          pParent->DeleteSubChunk(pWaveList);          pParent->DeleteSubChunk(pWaveList);
760      }      }
761        
762        /**
763         * Make a deep copy of the Sample object given by @a orig (without the
764         * actual sample waveform data however) and assign it to this object.
765         *
766         * This is a special internal variant of CopyAssign() which only copies the
767         * most mandatory member variables. It will be called by gig::Sample
768         * descendent instead of CopyAssign() since gig::Sample has its own
769         * implementation to access and copy the actual sample waveform data.
770         *
771         * @param orig - original Sample object to be copied from
772         */
773        void Sample::CopyAssignCore(const Sample* orig) {
774            // handle base classes
775            Resource::CopyAssign(orig);
776            // handle actual own attributes of this class
777            FormatTag = orig->FormatTag;
778            Channels = orig->Channels;
779            SamplesPerSecond = orig->SamplesPerSecond;
780            AverageBytesPerSecond = orig->AverageBytesPerSecond;
781            BlockAlign = orig->BlockAlign;
782            BitDepth = orig->BitDepth;
783            SamplesTotal = orig->SamplesTotal;
784            FrameSize = orig->FrameSize;
785        }
786        
787        /**
788         * Make a deep copy of the Sample object given by @a orig and assign it to
789         * this object.
790         *
791         * @param orig - original Sample object to be copied from
792         */
793        void Sample::CopyAssign(const Sample* orig) {
794            CopyAssignCore(orig);
795            
796            // copy sample waveform data (reading directly from disc)
797            Resize(orig->GetSize());
798            char* buf = (char*) LoadSampleData();
799            Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
800            const file_offset_t restorePos = pOrig->pCkData->GetPos();
801            pOrig->SetPos(0);
802            for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
803                const int iReadAtOnce = 64*1024;
804                file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
805                n = pOrig->Read(&buf[i], n);
806                if (!n) break;
807                todo -= n;
808                i += (n * pOrig->FrameSize);
809            }
810            pOrig->pCkData->SetPos(restorePos);
811        }
812    
813      /** @brief Load sample data into RAM.      /** @brief Load sample data into RAM.
814       *       *
# Line 726  namespace DLS { Line 859  namespace DLS {
859       * @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
860       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
861       */       */
862      unsigned long Sample::GetSize() {      file_offset_t Sample::GetSize() const {
863          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
864          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
865      }      }
# Line 753  namespace DLS { Line 886  namespace DLS {
886       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
887       * other formats will fail!       * other formats will fail!
888       *       *
889       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
890       *                   greater than zero)       *                  greater than zero)
891       * @throws Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM
892       * @throws Exception if \a iNewSize is less than 1       * @throws Exception if \a NewSize is less than 1 or unrealistic large
893       * @see File::Save(), FrameSize, FormatTag       * @see File::Save(), FrameSize, FormatTag
894       */       */
895      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
896          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");
897          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");
898          const int iSizeInBytes = iNewSize * FrameSize;          if ((NewSize >> 48) != 0)
899                throw Exception("Unrealistic high DLS sample size detected");
900            const file_offset_t sizeInBytes = NewSize * FrameSize;
901          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
902          if (pCkData) pCkData->Resize(iSizeInBytes);          if (pCkData) pCkData->Resize(sizeInBytes);
903          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, sizeInBytes);
904      }      }
905    
906      /**      /**
# Line 784  namespace DLS { Line 919  namespace DLS {
919       * @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
920       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
921       */       */
922      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) {
923          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
924          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");
925          unsigned long orderedBytes = SampleCount * FrameSize;          file_offset_t orderedBytes = SampleCount * FrameSize;
926          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
927          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
928                                          : result / FrameSize;                                          : result / FrameSize;
929      }      }
# Line 802  namespace DLS { Line 937  namespace DLS {
937       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
938       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
939       */       */
940      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
941          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
942          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?
943      }      }
# Line 822  namespace DLS { Line 957  namespace DLS {
957       * @throws Exception if current sample size is too small       * @throws Exception if current sample size is too small
958       * @see LoadSampleData()       * @see LoadSampleData()
959       */       */
960      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
961          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
962          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");
963          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 832  namespace DLS { Line 967  namespace DLS {
967       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
968       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
969       *       *
970         * @param pProgress - callback function for progress notification
971       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
972       *                   was provided yet       *                   was provided yet
973       */       */
974      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
975          if (FormatTag != DLS_WAVE_FORMAT_PCM)          if (FormatTag != DLS_WAVE_FORMAT_PCM)
976              throw Exception("Could not save sample, only PCM format is supported");              throw Exception("Could not save sample, only PCM format is supported");
977          // 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
978          if (!pCkData)          if (!pCkData)
979              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");
980          // update chunks of base class as well          // update chunks of base class as well
981          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
982          // make sure 'fmt' chunk exists          // make sure 'fmt' chunk exists
983          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
984          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 864  namespace DLS { Line 1000  namespace DLS {
1000      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) {
1001          pCkRegion = rgnList;          pCkRegion = rgnList;
1002    
1003          // articulation informations          // articulation information
1004          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
1005          if (rgnh) {          if (rgnh) {
1006              rgnh->Read(&KeyRange, 2, 2);              rgnh->Read(&KeyRange, 2, 2);
# Line 886  namespace DLS { Line 1022  namespace DLS {
1022          }          }
1023          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
1024    
1025          // sample informations          // sample information
1026          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
1027          if (wlnk) {          if (wlnk) {
1028              WaveLinkOptionFlags = wlnk->ReadUint16();              WaveLinkOptionFlags = wlnk->ReadUint16();
# Line 917  namespace DLS { Line 1053  namespace DLS {
1053      Sample* Region::GetSample() {      Sample* Region::GetSample() {
1054          if (pSample) return pSample;          if (pSample) return pSample;
1055          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1056          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1057          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample();
1058          while (sample) {          while (sample) {
1059              if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);              if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1060              sample = file->GetNextSample();              sample = file->GetNextSample();
1061          }          }
1062          return NULL;          return NULL;
# Line 975  namespace DLS { Line 1111  namespace DLS {
1111       * Apply Region settings to the respective RIFF chunks. You have to       * Apply Region settings to the respective RIFF chunks. You have to
1112       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
1113       *       *
1114         * @param pProgress - callback function for progress notification
1115       * @throws Exception - if the Region's sample could not be found       * @throws Exception - if the Region's sample could not be found
1116       */       */
1117      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
1118          // make sure 'rgnh' chunk exists          // make sure 'rgnh' chunk exists
1119          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1120          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
# Line 996  namespace DLS { Line 1133  namespace DLS {
1133    
1134          // update chunks of base classes as well (but skip Resource,          // update chunks of base classes as well (but skip Resource,
1135          // as a rgn doesn't seem to have dlid and INFO chunks)          // as a rgn doesn't seem to have dlid and INFO chunks)
1136          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1137          Sampler::UpdateChunks();          Sampler::UpdateChunks(pProgress);
1138    
1139          // make sure 'wlnk' chunk exists          // make sure 'wlnk' chunk exists
1140          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
# Line 1029  namespace DLS { Line 1166  namespace DLS {
1166          store32(&pData[4], Channel);          store32(&pData[4], Channel);
1167          store32(&pData[8], WavePoolTableIndex);          store32(&pData[8], WavePoolTableIndex);
1168      }      }
1169        
1170        /**
1171         * Make a (semi) deep copy of the Region object given by @a orig and assign
1172         * it to this object.
1173         *
1174         * Note that the sample pointer referenced by @a orig is simply copied as
1175         * memory address. Thus the respective sample is shared, not duplicated!
1176         *
1177         * @param orig - original Region object to be copied from
1178         */
1179        void Region::CopyAssign(const Region* orig) {
1180            // handle base classes
1181            Resource::CopyAssign(orig);
1182            Articulator::CopyAssign(orig);
1183            Sampler::CopyAssign(orig);
1184            // handle actual own attributes of this class
1185            // (the trivial ones)
1186            VelocityRange = orig->VelocityRange;
1187            KeyGroup = orig->KeyGroup;
1188            Layer = orig->Layer;
1189            SelfNonExclusive = orig->SelfNonExclusive;
1190            PhaseMaster = orig->PhaseMaster;
1191            PhaseGroup = orig->PhaseGroup;
1192            MultiChannel = orig->MultiChannel;
1193            Channel = orig->Channel;
1194            // only take the raw sample reference if the two Region objects are
1195            // part of the same file
1196            if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1197                WavePoolTableIndex = orig->WavePoolTableIndex;
1198                pSample = orig->pSample;
1199            } else {
1200                WavePoolTableIndex = -1;
1201                pSample = NULL;
1202            }
1203            FormatOptionFlags = orig->FormatOptionFlags;
1204            WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1205            // handle the last, a bit sensible attribute
1206            SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1207        }
1208    
1209    
1210  // *************** Instrument ***************  // *************** Instrument ***************
# Line 1106  namespace DLS { Line 1281  namespace DLS {
1281          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1282          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
1283          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
1284          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1285          return pNewRegion;          return pNewRegion;
1286      }      }
1287    
1288      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1289          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1290          lrgn->MoveSubChunk(pSrc->pCkRegion, pDst ? pDst->pCkRegion : 0);          lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1291    
1292          pRegions->remove(pSrc);          pRegions->remove(pSrc);
1293          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
# Line 1124  namespace DLS { Line 1299  namespace DLS {
1299          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1300          if (iter == pRegions->end()) return;          if (iter == pRegions->end()) return;
1301          pRegions->erase(iter);          pRegions->erase(iter);
1302          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1303          delete pRegion;          delete pRegion;
1304      }      }
1305    
# Line 1132  namespace DLS { Line 1307  namespace DLS {
1307       * Apply Instrument with all its Regions to the respective RIFF chunks.       * Apply Instrument with all its Regions to the respective RIFF chunks.
1308       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
1309       *       *
1310         * @param pProgress - callback function for progress notification
1311       * @throws Exception - on errors       * @throws Exception - on errors
1312       */       */
1313      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
1314          // first update base classes' chunks          // first update base classes' chunks
1315          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1316          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1317          // make sure 'insh' chunk exists          // make sure 'insh' chunk exists
1318          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1319          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1320          uint8_t* pData = (uint8_t*) insh->LoadChunkData();          uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1321          // update 'insh' chunk          // update 'insh' chunk
1322          Regions = (pRegions) ? pRegions->size() : 0;          Regions = (pRegions) ? uint32_t(pRegions->size()) : 0;
1323          midi_locale_t locale;          midi_locale_t locale;
1324          locale.instrument = MIDIProgram;          locale.instrument = MIDIProgram;
1325          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
# Line 1156  namespace DLS { Line 1332  namespace DLS {
1332          if (!pRegions) return;          if (!pRegions) return;
1333          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
1334          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
1335          for (; iter != end; ++iter) {          for (int i = 0; iter != end; ++iter, ++i) {
1336              (*iter)->UpdateChunks();              // divide local progress into subprogress
1337                progress_t subprogress;
1338                __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1339                // do the actual work
1340                (*iter)->UpdateChunks(&subprogress);
1341          }          }
1342            __notify_progress(pProgress, 1.0); // notify done
1343      }      }
1344    
1345      /** @brief Destructor.      /** @brief Destructor.
# Line 1180  namespace DLS { Line 1361  namespace DLS {
1361          RIFF::List* pParent = pCkInstrument->GetParent();          RIFF::List* pParent = pCkInstrument->GetParent();
1362          pParent->DeleteSubChunk(pCkInstrument);          pParent->DeleteSubChunk(pCkInstrument);
1363      }      }
1364        
1365        void Instrument::CopyAssignCore(const Instrument* orig) {
1366            // handle base classes
1367            Resource::CopyAssign(orig);
1368            Articulator::CopyAssign(orig);
1369            // handle actual own attributes of this class
1370            // (the trivial ones)
1371            IsDrum = orig->IsDrum;
1372            MIDIBank = orig->MIDIBank;
1373            MIDIBankCoarse = orig->MIDIBankCoarse;
1374            MIDIBankFine = orig->MIDIBankFine;
1375            MIDIProgram = orig->MIDIProgram;
1376        }
1377        
1378        /**
1379         * Make a (semi) deep copy of the Instrument object given by @a orig and assign
1380         * it to this object.
1381         *
1382         * Note that all sample pointers referenced by @a orig are simply copied as
1383         * memory address. Thus the respective samples are shared, not duplicated!
1384         *
1385         * @param orig - original Instrument object to be copied from
1386         */
1387        void Instrument::CopyAssign(const Instrument* orig) {
1388            CopyAssignCore(orig);
1389            // delete all regions first
1390            while (Regions) DeleteRegion(GetFirstRegion());
1391            // now recreate and copy regions
1392            {
1393                RegionList::const_iterator it = orig->pRegions->begin();
1394                for (int i = 0; i < orig->Regions; ++i, ++it) {
1395                    Region* dstRgn = AddRegion();
1396                    //NOTE: Region does semi-deep copy !
1397                    dstRgn->CopyAssign(*it);
1398                }
1399            }
1400        }
1401    
1402    
1403  // *************** File ***************  // *************** File ***************
# Line 1194  namespace DLS { Line 1411  namespace DLS {
1411       */       */
1412      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1413          pRIFF->SetByteOrder(RIFF::endian_little);          pRIFF->SetByteOrder(RIFF::endian_little);
1414            bOwningRiff = true;
1415          pVersion = new version_t;          pVersion = new version_t;
1416          pVersion->major   = 0;          pVersion->major   = 0;
1417          pVersion->minor   = 0;          pVersion->minor   = 0;
# Line 1224  namespace DLS { Line 1442  namespace DLS {
1442      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1443          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1444          this->pRIFF = pRIFF;          this->pRIFF = pRIFF;
1445            bOwningRiff = false;
1446          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1447          if (ckVersion) {          if (ckVersion) {
1448              pVersion = new version_t;              pVersion = new version_t;
# Line 1256  namespace DLS { Line 1474  namespace DLS {
1474                  for (int i = 0 ; i < WavePoolCount ; i++) {                  for (int i = 0 ; i < WavePoolCount ; i++) {
1475                      pWavePoolTableHi[i] = ptbl->ReadUint32();                      pWavePoolTableHi[i] = ptbl->ReadUint32();
1476                      pWavePoolTable[i] = ptbl->ReadUint32();                      pWavePoolTable[i] = ptbl->ReadUint32();
1477                      if (pWavePoolTable[i] & 0x80000000)                      //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1478                          throw DLS::Exception("Files larger than 2 GB not yet supported");                      //if (pWavePoolTable[i] & 0x80000000)
1479                        //    throw DLS::Exception("Files larger than 2 GB not yet supported");
1480                  }                  }
1481              } else { // conventional 32 bit offsets              } else { // conventional 32 bit offsets
1482                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
# Line 1295  namespace DLS { Line 1514  namespace DLS {
1514          if (pVersion) delete pVersion;          if (pVersion) delete pVersion;
1515          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++)
1516              delete *i;              delete *i;
1517            if (bOwningRiff)
1518                delete pRIFF;
1519      }      }
1520    
1521      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
# Line 1314  namespace DLS { Line 1535  namespace DLS {
1535          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
1536          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1537          if (wvpl) {          if (wvpl) {
1538              unsigned long wvplFileOffset = wvpl->GetFilePos();              file_offset_t wvplFileOffset = wvpl->GetFilePos();
1539              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1540              while (wave) {              while (wave) {
1541                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1542                      unsigned long waveFileOffset = wave->GetFilePos();                      file_offset_t waveFileOffset = wave->GetFilePos();
1543                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1544                  }                  }
1545                  wave = wvpl->GetNextSubList();                  wave = wvpl->GetNextSubList();
# Line 1327  namespace DLS { Line 1548  namespace DLS {
1548          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)
1549              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1550              if (dwpl) {              if (dwpl) {
1551                  unsigned long dwplFileOffset = dwpl->GetFilePos();                  file_offset_t dwplFileOffset = dwpl->GetFilePos();
1552                  RIFF::List* wave = dwpl->GetFirstSubList();                  RIFF::List* wave = dwpl->GetFirstSubList();
1553                  while (wave) {                  while (wave) {
1554                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
1555                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
1556                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1557                      }                      }
1558                      wave = dwpl->GetNextSubList();                      wave = dwpl->GetNextSubList();
# Line 1464  namespace DLS { Line 1685  namespace DLS {
1685      String File::GetFileName() {      String File::GetFileName() {
1686          return pRIFF->GetFileName();          return pRIFF->GetFileName();
1687      }      }
1688        
1689        /**
1690         * You may call this method store a future file name, so you don't have to
1691         * to pass it to the Save() call later on.
1692         */
1693        void File::SetFileName(const String& name) {
1694            pRIFF->SetFileName(name);
1695        }
1696    
1697      /**      /**
1698       * Apply all the DLS file's current instruments, samples and settings to       * Apply all the DLS file's current instruments, samples and settings to
1699       * the respective RIFF chunks. You have to call Save() to make changes       * the respective RIFF chunks. You have to call Save() to make changes
1700       * persistent.       * persistent.
1701       *       *
1702         * @param pProgress - callback function for progress notification
1703       * @throws Exception - on errors       * @throws Exception - on errors
1704       */       */
1705      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
1706          // first update base class's chunks          // first update base class's chunks
1707          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1708    
1709          // if version struct exists, update 'vers' chunk          // if version struct exists, update 'vers' chunk
1710          if (pVersion) {          if (pVersion) {
# Line 1488  namespace DLS { Line 1718  namespace DLS {
1718          }          }
1719    
1720          // update 'colh' chunk          // update 'colh' chunk
1721          Instruments = (pInstruments) ? pInstruments->size() : 0;          Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
1722          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1723          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1724          uint8_t* pData = (uint8_t*) colh->LoadChunkData();          uint8_t* pData = (uint8_t*) colh->LoadChunkData();
# Line 1496  namespace DLS { Line 1726  namespace DLS {
1726    
1727          // update instrument's chunks          // update instrument's chunks
1728          if (pInstruments) {          if (pInstruments) {
1729                // divide local progress into subprogress
1730                progress_t subprogress;
1731                __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1732    
1733                // do the actual work
1734              InstrumentList::iterator iter = pInstruments->begin();              InstrumentList::iterator iter = pInstruments->begin();
1735              InstrumentList::iterator end  = pInstruments->end();              InstrumentList::iterator end  = pInstruments->end();
1736              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1737                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1738                    progress_t subsubprogress;
1739                    __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
1740                    // do the actual work
1741                    (*iter)->UpdateChunks(&subsubprogress);
1742              }              }
1743    
1744                __notify_progress(&subprogress, 1.0); // notify subprogress done
1745          }          }
1746    
1747          // update 'ptbl' chunk          // update 'ptbl' chunk
1748          const int iSamples = (pSamples) ? pSamples->size() : 0;          const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
1749          const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1750          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1751          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*/);
1752          const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;          int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1753          ptbl->Resize(iPtblSize);          ptbl->Resize(iPtblSize);
1754          pData = (uint8_t*) ptbl->LoadChunkData();          pData = (uint8_t*) ptbl->LoadChunkData();
1755          WavePoolCount = iSamples;          WavePoolCount = iSamples;
# Line 1518  namespace DLS { Line 1759  namespace DLS {
1759    
1760          // update sample's chunks          // update sample's chunks
1761          if (pSamples) {          if (pSamples) {
1762                // divide local progress into subprogress
1763                progress_t subprogress;
1764                __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
1765    
1766                // do the actual work
1767              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
1768              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
1769              for (; iter != end; ++iter) {              for (int i = 0; iter != end; ++iter, ++i) {
1770                  (*iter)->UpdateChunks();                  // divide subprogress into sub-subprogress
1771                    progress_t subsubprogress;
1772                    __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
1773                    // do the actual work
1774                    (*iter)->UpdateChunks(&subsubprogress);
1775                }
1776    
1777                __notify_progress(&subprogress, 1.0); // notify subprogress done
1778            }
1779    
1780            // if there are any extension files, gather which ones are regular
1781            // extension files used as wave pool files (.gx00, .gx01, ... , .gx98)
1782            // and which one is probably a convolution (GigaPulse) file (always to
1783            // be saved as .gx99)
1784            std::list<RIFF::File*> poolFiles;  // < for (.gx00, .gx01, ... , .gx98) files
1785            RIFF::File* pGigaPulseFile = NULL; // < for .gx99 file
1786            if (!ExtensionFiles.empty()) {
1787                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
1788                for (; it != ExtensionFiles.end(); ++it) {
1789                    //FIXME: the .gx99 file is always used by GSt for convolution
1790                    // data (GigaPulse); so we should better detect by subchunk
1791                    // whether the extension file is intended for convolution
1792                    // instead of checkking for a file name, because the latter does
1793                    // not work for saving new gigs created from scratch
1794                    const std::string oldName = (*it)->GetFileName();
1795                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
1796                    if (isGigaPulseFile)
1797                        pGigaPulseFile = *it;
1798                    else
1799                        poolFiles.push_back(*it);
1800              }              }
1801          }          }
1802    
1803            // update the 'xfil' chunk which describes all extension files (wave
1804            // pool files) except the .gx99 file
1805            if (!poolFiles.empty()) {
1806                const int n = poolFiles.size();
1807                const int iHeaderSize = 4;
1808                const int iEntrySize = 144;
1809    
1810                // make sure chunk exists, and with correct size
1811                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
1812                if (ckXfil)
1813                    ckXfil->Resize(iHeaderSize + n * iEntrySize);
1814                else
1815                    ckXfil = pRIFF->AddSubChunk(CHUNK_ID_XFIL, iHeaderSize + n * iEntrySize);
1816    
1817                uint8_t* pData = (uint8_t*) ckXfil->LoadChunkData();
1818    
1819                // re-assemble the chunk's content
1820                store32(pData, n);
1821                std::list<RIFF::File*>::iterator itExtFile = poolFiles.begin();
1822                for (int i = 0, iOffset = 4; i < n;
1823                     ++itExtFile, ++i, iOffset += iEntrySize)
1824                {
1825                    // update the filename string and 5 byte extension of each extension file
1826                    std::string file = lastPathComponent(
1827                        (*itExtFile)->GetFileName()
1828                    );
1829                    if (file.length() + 6 > 128)
1830                        throw Exception("Fatal error, extension filename length exceeds 122 byte maximum");
1831                    uint8_t* pStrings = &pData[iOffset];
1832                    memset(pStrings, 0, 128);
1833                    memcpy(pStrings, file.c_str(), file.length());
1834                    pStrings += file.length() + 1;
1835                    std::string ext = file.substr(file.length()-5);
1836                    memcpy(pStrings, ext.c_str(), 5);
1837                    // update the dlsid of the extension file
1838                    uint8_t* pId = &pData[iOffset + 128];
1839                    dlsid_t id;
1840                    RIFF::Chunk* ckDLSID = (*itExtFile)->GetSubChunk(CHUNK_ID_DLID);
1841                    if (ckDLSID) {
1842                        ckDLSID->Read(&id.ulData1, 1, 4);
1843                        ckDLSID->Read(&id.usData2, 1, 2);
1844                        ckDLSID->Read(&id.usData3, 1, 2);
1845                        ckDLSID->Read(id.abData, 8, 1);
1846                    } else {
1847                        ckDLSID = (*itExtFile)->AddSubChunk(CHUNK_ID_DLID, 16);
1848                        Resource::GenerateDLSID(&id);
1849                        uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
1850                        store32(&pData[0], id.ulData1);
1851                        store16(&pData[4], id.usData2);
1852                        store16(&pData[6], id.usData3);
1853                        memcpy(&pData[8], id.abData, 8);
1854                    }
1855                    store32(&pId[0], id.ulData1);
1856                    store16(&pId[4], id.usData2);
1857                    store16(&pId[6], id.usData3);
1858                    memcpy(&pId[8], id.abData, 8);
1859                }
1860            } else {
1861                // in case there was a 'xfil' chunk, remove it
1862                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
1863                if (ckXfil) pRIFF->DeleteSubChunk(ckXfil);
1864            }
1865    
1866            // update the 'doxf' chunk which describes a .gx99 extension file
1867            // which contains convolution data (GigaPulse)
1868            if (pGigaPulseFile) {
1869                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
1870                if (!ckDoxf) ckDoxf = pRIFF->AddSubChunk(CHUNK_ID_DOXF, 148);
1871    
1872                uint8_t* pData = (uint8_t*) ckDoxf->LoadChunkData();
1873    
1874                // update the dlsid from the extension file
1875                uint8_t* pId = &pData[132];
1876                RIFF::Chunk* ckDLSID = pGigaPulseFile->GetSubChunk(CHUNK_ID_DLID);
1877                if (!ckDLSID) { //TODO: auto generate DLS ID if missing
1878                    throw Exception("Fatal error, GigaPulse file does not contain a DLS ID chunk");
1879                } else {
1880                    dlsid_t id;
1881                    // read DLS ID from extension files's DLS ID chunk
1882                    uint8_t* pData = (uint8_t*) ckDLSID->LoadChunkData();
1883                    id.ulData1 = load32(&pData[0]);
1884                    id.usData2 = load16(&pData[4]);
1885                    id.usData3 = load16(&pData[6]);
1886                    memcpy(id.abData, &pData[8], 8);
1887                    // store DLS ID to 'doxf' chunk
1888                    store32(&pId[0], id.ulData1);
1889                    store16(&pId[4], id.usData2);
1890                    store16(&pId[6], id.usData3);
1891                    memcpy(&pId[8], id.abData, 8);
1892                }
1893            } else {
1894                // in case there was a 'doxf' chunk, remove it
1895                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
1896                if (ckDoxf) pRIFF->DeleteSubChunk(ckDoxf);
1897            }
1898    
1899            // the RIFF file to be written might now been grown >= 4GB or might
1900            // been shrunk < 4GB, so we might need to update the wave pool offset
1901            // size and thus accordingly we would need to resize the wave pool
1902            // chunk
1903            const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
1904            const bool bRequires64Bit = (finalFileSize >> 32) != 0 || // < native 64 bit gig file
1905                                         poolFiles.size() > 0;        // < 32 bit gig file where the hi 32 bits are used as extension file nr
1906            if (b64BitWavePoolOffsets != bRequires64Bit) {
1907                b64BitWavePoolOffsets = bRequires64Bit;
1908                iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1909                iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1910                ptbl->Resize(iPtblSize);
1911            }
1912    
1913            __notify_progress(pProgress, 1.0); // notify done
1914      }      }
1915    
1916      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1538  namespace DLS { Line 1925  namespace DLS {
1925       * the new file (given by \a Path) afterwards.       * the new file (given by \a Path) afterwards.
1926       *       *
1927       * @param Path - path and file name where everything should be written to       * @param Path - path and file name where everything should be written to
1928         * @param pProgress - optional: callback function for progress notification
1929       */       */
1930      void File::Save(const String& Path) {      void File::Save(const String& Path, progress_t* pProgress) {
1931          UpdateChunks();          // calculate number of tasks to notify progress appropriately
1932          pRIFF->Save(Path);          const size_t nExtFiles = ExtensionFiles.size();
1933          __UpdateWavePoolTableChunk();          const float tasks = 2.f + nExtFiles;
1934    
1935            // save extension files (if required)
1936            if (!ExtensionFiles.empty()) {
1937                // for assembling path of extension files to be saved to
1938                const std::string folder = parentPath(Path);
1939                const std::string baseName = pathWithoutExtension(Path);
1940                // save the individual extension files
1941                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
1942                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
1943                    // divide local progress into subprogress
1944                    progress_t subprogress;
1945                    __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
1946                    //FIXME: the .gx99 file is always used by GSt for convolution
1947                    // data (GigaPulse); so we should better detect by subchunk
1948                    // whether the extension file is intended for convolution
1949                    // instead of checkking for a file name, because the latter does
1950                    // not work for saving new gigs created from scratch
1951                    const std::string oldName = (*it)->GetFileName();
1952                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
1953                    std::string ext = (isGigaPulseFile) ? ".gx99" : strPrint(".gx02d", i+1);
1954                    std::string newPath = concatPath(folder, baseName) + ext;
1955                    // save extension file to its new location
1956                    (*it)->Save(newPath, &subprogress);
1957                }
1958            }
1959    
1960            {
1961                // divide local progress into subprogress
1962                progress_t subprogress;
1963                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
1964                // do the actual work
1965                UpdateChunks(&subprogress);
1966            }
1967            {
1968                // divide local progress into subprogress
1969                progress_t subprogress;
1970                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
1971                // do the actual work
1972                pRIFF->Save(Path, &subprogress);
1973            }
1974            UpdateFileOffsets();
1975            __notify_progress(pProgress, 1.0); // notify done
1976      }      }
1977    
1978      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1551  namespace DLS { Line 1981  namespace DLS {
1981       * 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
1982       * have at the end of the saving process.       * have at the end of the saving process.
1983       *       *
1984       * @throws RIFF::Exception if any kind of IO error occured       * @param pProgress - optional: callback function for progress notification
1985       * @throws DLS::Exception  if any kind of DLS specific error occured       * @throws RIFF::Exception if any kind of IO error occurred
1986         * @throws DLS::Exception  if any kind of DLS specific error occurred
1987         */
1988        void File::Save(progress_t* pProgress) {
1989            // calculate number of tasks to notify progress appropriately
1990            const size_t nExtFiles = ExtensionFiles.size();
1991            const float tasks = 2.f + nExtFiles;
1992    
1993            // save extension files (if required)
1994            if (!ExtensionFiles.empty()) {
1995                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
1996                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
1997                    // divide local progress into subprogress
1998                    progress_t subprogress;
1999                    __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2000                    // save extension file
2001                    (*it)->Save(&subprogress);
2002                }
2003            }
2004    
2005            {
2006                // divide local progress into subprogress
2007                progress_t subprogress;
2008                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2009                // do the actual work
2010                UpdateChunks(&subprogress);
2011            }
2012            {
2013                // divide local progress into subprogress
2014                progress_t subprogress;
2015                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2016                // do the actual work
2017                pRIFF->Save(&subprogress);
2018            }
2019            UpdateFileOffsets();
2020            __notify_progress(pProgress, 1.0); // notify done
2021        }
2022    
2023        /** @brief Updates all file offsets stored all over the file.
2024         *
2025         * This virtual method is called whenever the overall file layout has been
2026         * changed (i.e. file or individual RIFF chunks have been resized). It is
2027         * then the responsibility of this method to update all file offsets stored
2028         * in the file format. For example samples are referenced by instruments by
2029         * file offsets. The gig format also stores references to instrument
2030         * scripts as file offsets, and thus it overrides this method to update
2031         * those file offsets as well.
2032       */       */
2033      void File::Save() {      void File::UpdateFileOffsets() {
         UpdateChunks();  
         pRIFF->Save();  
2034          __UpdateWavePoolTableChunk();          __UpdateWavePoolTableChunk();
2035      }      }
2036    
# Line 1594  namespace DLS { Line 2068  namespace DLS {
2068          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2069          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2070          // check if 'ptbl' chunk is large enough          // check if 'ptbl' chunk is large enough
2071          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2072          const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;          const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
2073          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
2074          // save the 'ptbl' chunk's current read/write position          // save the 'ptbl' chunk's current read/write position
2075          unsigned long ulOriginalPos = ptbl->GetPos();          file_offset_t ullOriginalPos = ptbl->GetPos();
2076          // update headers          // update headers
2077          ptbl->SetPos(0);          ptbl->SetPos(0);
2078          uint32_t tmp = WavePoolHeaderSize;          uint32_t tmp = WavePoolHeaderSize;
# Line 1621  namespace DLS { Line 2095  namespace DLS {
2095              }              }
2096          }          }
2097          // restore 'ptbl' chunk's original read/write position          // restore 'ptbl' chunk's original read/write position
2098          ptbl->SetPos(ulOriginalPos);          ptbl->SetPos(ullOriginalPos);
2099      }      }
2100    
2101      /**      /**
# Line 1630  namespace DLS { Line 2104  namespace DLS {
2104       * exists already.       * exists already.
2105       */       */
2106      void File::__UpdateWavePoolTable() {      void File::__UpdateWavePoolTable() {
2107          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2108          // resize wave pool table arrays          // resize wave pool table arrays
2109          if (pWavePoolTable)   delete[] pWavePoolTable;          if (pWavePoolTable)   delete[] pWavePoolTable;
2110          if (pWavePoolTableHi) delete[] pWavePoolTableHi;          if (pWavePoolTableHi) delete[] pWavePoolTableHi;
2111          pWavePoolTable   = new uint32_t[WavePoolCount];          pWavePoolTable   = new uint32_t[WavePoolCount];
2112          pWavePoolTableHi = new uint32_t[WavePoolCount];          pWavePoolTableHi = new uint32_t[WavePoolCount];
2113          if (!pSamples) return;          if (!pSamples) return;
2114          // update offsets int wave pool table          // update offsets in wave pool table
2115          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2116          uint64_t wvplFileOffset = wvpl->GetFilePos();          uint64_t wvplFileOffset = wvpl->GetFilePos();
2117          if (b64BitWavePoolOffsets) {          if (!b64BitWavePoolOffsets) { // conventional 32 bit offsets (and no extension files) ...
2118              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
2119              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
2120              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
2121                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2122                  (*iter)->ulWavePoolOffset = _64BitOffset;                  (*iter)->ullWavePoolOffset = _64BitOffset;
                 pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);  
                 pWavePoolTable[i]   = (uint32_t) _64BitOffset;  
             }  
         } else { // conventional 32 bit offsets  
             SampleList::iterator iter = pSamples->begin();  
             SampleList::iterator end  = pSamples->end();  
             for (int i = 0 ; iter != end ; ++iter, i++) {  
                 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;  
                 (*iter)->ulWavePoolOffset = _64BitOffset;  
2123                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2124              }              }
2125            } else { // a) native 64 bit offsets without extension files or b) 32 bit offsets with extension files ...
2126                if (ExtensionFiles.empty()) { // native 64 bit offsets (and no extension files) [not compatible with GigaStudio] ...
2127                    SampleList::iterator iter = pSamples->begin();
2128                    SampleList::iterator end  = pSamples->end();
2129                    for (int i = 0 ; iter != end ; ++iter, i++) {
2130                        uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2131                        (*iter)->ullWavePoolOffset = _64BitOffset;
2132                        pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
2133                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2134                    }
2135                } else { // 32 bit offsets with extension files (GigaStudio legacy support) ...
2136                    // the main gig and the extension files may contain wave data
2137                    std::vector<RIFF::File*> poolFiles;
2138                    poolFiles.push_back(pRIFF);
2139                    poolFiles.insert(poolFiles.end(), ExtensionFiles.begin(), ExtensionFiles.end());
2140    
2141                    RIFF::File* pCurPoolFile = NULL;
2142                    int fileNo = 0;
2143                    int waveOffset = 0;
2144                    SampleList::iterator iter = pSamples->begin();
2145                    SampleList::iterator end  = pSamples->end();
2146                    for (int i = 0 ; iter != end ; ++iter, i++) {
2147                        RIFF::File* pPoolFile = (*iter)->pWaveList->GetFile();
2148                        // if this sample is located in the same pool file as the
2149                        // last we reuse the previously computed fileNo and waveOffset
2150                        if (pPoolFile != pCurPoolFile) { // it is a different pool file than the last sample ...
2151                            pCurPoolFile = pPoolFile;
2152    
2153                            std::vector<RIFF::File*>::iterator sIter;
2154                            sIter = std::find(poolFiles.begin(), poolFiles.end(), pPoolFile);
2155                            if (sIter != poolFiles.end())
2156                                fileNo = std::distance(poolFiles.begin(), sIter);
2157                            else
2158                                throw DLS::Exception("Fatal error, unknown pool file");
2159    
2160                            RIFF::List* extWvpl = pCurPoolFile->GetSubList(LIST_TYPE_WVPL);
2161                            if (!extWvpl)
2162                                throw DLS::Exception("Fatal error, pool file has no 'wvpl' list chunk");
2163                            waveOffset = extWvpl->GetFilePos() + LIST_HEADER_SIZE(pCurPoolFile->GetFileOffsetSize());
2164                        }
2165                        uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - waveOffset;
2166                        // pWavePoolTableHi stores file number when extension files are in use
2167                        pWavePoolTableHi[i] = (uint32_t) fileNo;
2168                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2169                        (*iter)->ullWavePoolOffset = _64BitOffset;
2170                    }
2171                }
2172          }          }
2173      }      }
2174    
2175    
   
2176  // *************** Exception ***************  // *************** Exception ***************
2177  // *  // *
2178    
2179      Exception::Exception(String Message) : RIFF::Exception(Message) {      Exception::Exception() : RIFF::Exception() {
2180        }
2181    
2182        Exception::Exception(String format, ...) : RIFF::Exception() {
2183            va_list arg;
2184            va_start(arg, format);
2185            Message = assemble(format, arg);
2186            va_end(arg);
2187        }
2188    
2189        Exception::Exception(String format, va_list arg) : RIFF::Exception() {
2190            Message = assemble(format, arg);
2191      }      }
2192    
2193      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.2329  
changed lines
  Added in v.3474

  ViewVC Help
Powered by ViewVC