/[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 2310 by persson, Sat Feb 11 11:08:01 2012 UTC revision 3488 by schoenebeck, Thu Feb 28 17:49:07 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 121  namespace DLS { Line 122  namespace DLS {
122              artl->GetChunkID() != CHUNK_ID_ARTL) {              artl->GetChunkID() != CHUNK_ID_ARTL) {
123                throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");                throw DLS::Exception("<artl-ck> or <art2-ck> chunk expected");
124          }          }
125    
126            artl->SetPos(0);
127    
128          HeaderSize  = artl->ReadUint32();          HeaderSize  = artl->ReadUint32();
129          Connections = artl->ReadUint32();          Connections = artl->ReadUint32();
130          artl->SetPos(HeaderSize);          artl->SetPos(HeaderSize);
# Line 144  namespace DLS { Line 148  namespace DLS {
148      /**      /**
149       * Apply articulation connections to the respective RIFF chunks. You       * Apply articulation connections to the respective RIFF chunks. You
150       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
151         *
152         * @param pProgress - callback function for progress notification
153       */       */
154      void Articulation::UpdateChunks() {      void Articulation::UpdateChunks(progress_t* pProgress) {
155          const int iEntrySize = 12; // 12 bytes per connection block          const int iEntrySize = 12; // 12 bytes per connection block
156          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);          pArticulationCk->Resize(HeaderSize + Connections * iEntrySize);
157          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();          uint8_t* pData = (uint8_t*) pArticulationCk->LoadChunkData();
# Line 161  namespace DLS { Line 167  namespace DLS {
167          }          }
168      }      }
169    
170        /** @brief Remove all RIFF chunks associated with this Articulation object.
171         *
172         * At the moment Articulation::DeleteChunks() does nothing. It is
173         * recommended to call this method explicitly though from deriving classes's
174         * own overridden implementation of this method to avoid potential future
175         * compatiblity issues.
176         *
177         * See Storage::DeleteChunks() for details.
178         */
179        void Articulation::DeleteChunks() {
180        }
181    
182    
183    
184  // *************** Articulator  ***************  // *************** Articulator  ***************
# Line 217  namespace DLS { Line 235  namespace DLS {
235      /**      /**
236       * Apply all articulations to the respective RIFF chunks. You have to       * Apply all articulations to the respective RIFF chunks. You have to
237       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
238         *
239         * @param pProgress - callback function for progress notification
240         */
241        void Articulator::UpdateChunks(progress_t* pProgress) {
242            if (pArticulations) {
243                ArticulationList::iterator iter = pArticulations->begin();
244                ArticulationList::iterator end  = pArticulations->end();
245                for (; iter != end; ++iter) {
246                    (*iter)->UpdateChunks(pProgress);
247                }
248            }
249        }
250    
251        /** @brief Remove all RIFF chunks associated with this Articulator object.
252         *
253         * See Storage::DeleteChunks() for details.
254       */       */
255      void Articulator::UpdateChunks() {      void Articulator::DeleteChunks() {
256          if (pArticulations) {          if (pArticulations) {
257              ArticulationList::iterator iter = pArticulations->begin();              ArticulationList::iterator iter = pArticulations->begin();
258              ArticulationList::iterator end  = pArticulations->end();              ArticulationList::iterator end  = pArticulations->end();
259              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
260                  (*iter)->UpdateChunks();                  (*iter)->DeleteChunks();
261              }              }
262          }          }
263      }      }
264    
265        /**
266         * Not yet implemented in this version, since the .gig format does
267         * not need to copy DLS articulators and so far nobody used pure
268         * DLS instrument AFAIK.
269         */
270        void Articulator::CopyAssign(const Articulator* orig) {
271            //TODO: implement deep copy assignment for this class
272        }
273    
274    
275    
276  // *************** Info  ***************  // *************** Info  ***************
# Line 327  namespace DLS { Line 370  namespace DLS {
370       *       *
371       * Apply current INFO field values to the respective INFO chunks. You       * Apply current INFO field values to the respective INFO chunks. You
372       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
373         *
374         * @param pProgress - callback function for progress notification
375       */       */
376      void Info::UpdateChunks() {      void Info::UpdateChunks(progress_t* pProgress) {
377          if (!pResourceListChunk) return;          if (!pResourceListChunk) return;
378    
379          // make sure INFO list chunk exists          // make sure INFO list chunk exists
# Line 384  namespace DLS { Line 429  namespace DLS {
429          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));          SaveString(CHUNK_ID_ITCH, lstINFO, Technician, String(""));
430      }      }
431    
432        /** @brief Remove all RIFF chunks associated with this Info object.
433         *
434         * At the moment Info::DeleteChunks() does nothing. It is
435         * recommended to call this method explicitly though from deriving classes's
436         * own overridden implementation of this method to avoid potential future
437         * compatiblity issues.
438         *
439         * See Storage::DeleteChunks() for details.
440         */
441        void Info::DeleteChunks() {
442        }
443    
444        /**
445         * Make a deep copy of the Info object given by @a orig and assign it to
446         * this object.
447         *
448         * @param orig - original Info object to be copied from
449         */
450        void Info::CopyAssign(const Info* orig) {
451            Name = orig->Name;
452            ArchivalLocation = orig->ArchivalLocation;
453            CreationDate = orig->CreationDate;
454            Comments = orig->Comments;
455            Product = orig->Product;
456            Copyright = orig->Copyright;
457            Artists = orig->Artists;
458            Genre = orig->Genre;
459            Keywords = orig->Keywords;
460            Engineer = orig->Engineer;
461            Technician = orig->Technician;
462            Software = orig->Software;
463            Medium = orig->Medium;
464            Source = orig->Source;
465            SourceForm = orig->SourceForm;
466            Commissioned = orig->Commissioned;
467            Subject = orig->Subject;
468            //FIXME: hmm, is copying this pointer a good idea?
469            pFixedStringLengths = orig->pFixedStringLengths;
470        }
471    
472    
473    
474  // *************** Resource ***************  // *************** Resource ***************
# Line 406  namespace DLS { Line 491  namespace DLS {
491    
492          RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);          RIFF::Chunk* ckDLSID = lstResource->GetSubChunk(CHUNK_ID_DLID);
493          if (ckDLSID) {          if (ckDLSID) {
494                ckDLSID->SetPos(0);
495    
496              pDLSID = new dlsid_t;              pDLSID = new dlsid_t;
497              ckDLSID->Read(&pDLSID->ulData1, 1, 4);              ckDLSID->Read(&pDLSID->ulData1, 1, 4);
498              ckDLSID->Read(&pDLSID->usData2, 1, 2);              ckDLSID->Read(&pDLSID->usData2, 1, 2);
# Line 420  namespace DLS { Line 507  namespace DLS {
507          if (pInfo)  delete pInfo;          if (pInfo)  delete pInfo;
508      }      }
509    
510        /** @brief Remove all RIFF chunks associated with this Resource object.
511         *
512         * At the moment Resource::DeleteChunks() does nothing. It is recommended
513         * to call this method explicitly though from deriving classes's own
514         * overridden implementation of this method to avoid potential future
515         * compatiblity issues.
516         *
517         * See Storage::DeleteChunks() for details.
518         */
519        void Resource::DeleteChunks() {
520        }
521    
522      /** @brief Update chunks with current Resource data.      /** @brief Update chunks with current Resource data.
523       *       *
524       * Apply Resource data persistently below the previously given resource       * Apply Resource data persistently below the previously given resource
# Line 427  namespace DLS { Line 526  namespace DLS {
526       * will not be applied at the moment (yet).       * will not be applied at the moment (yet).
527       *       *
528       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
529         *
530         * @param pProgress - callback function for progress notification
531       */       */
532      void Resource::UpdateChunks() {      void Resource::UpdateChunks(progress_t* pProgress) {
533          pInfo->UpdateChunks();          pInfo->UpdateChunks(pProgress);
534    
535          if (pDLSID) {          if (pDLSID) {
536              // make sure 'dlid' chunk exists              // make sure 'dlid' chunk exists
# Line 448  namespace DLS { Line 549  namespace DLS {
549       * Generates a new DLSID for the resource.       * Generates a new DLSID for the resource.
550       */       */
551      void Resource::GenerateDLSID() {      void Resource::GenerateDLSID() {
552  #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)          #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
   
553          if (!pDLSID) pDLSID = new dlsid_t;          if (!pDLSID) pDLSID = new dlsid_t;
554            GenerateDLSID(pDLSID);
555            #endif
556        }
557    
558        void Resource::GenerateDLSID(dlsid_t* pDLSID) {
559    #if defined(WIN32) || defined(__APPLE__) || defined(HAVE_UUID_GENERATE)
560  #ifdef WIN32  #ifdef WIN32
   
561          UUID uuid;          UUID uuid;
562          UuidCreate(&uuid);          UuidCreate(&uuid);
563          pDLSID->ulData1 = uuid.Data1;          pDLSID->ulData1 = uuid.Data1;
# Line 487  namespace DLS { Line 591  namespace DLS {
591  #endif  #endif
592  #endif  #endif
593      }      }
594        
595        /**
596         * Make a deep copy of the Resource object given by @a orig and assign it
597         * to this object.
598         *
599         * @param orig - original Resource object to be copied from
600         */
601        void Resource::CopyAssign(const Resource* orig) {
602            pInfo->CopyAssign(orig->pInfo);
603        }
604    
605    
606  // *************** Sampler ***************  // *************** Sampler ***************
# Line 496  namespace DLS { Line 610  namespace DLS {
610          pParentList       = ParentList;          pParentList       = ParentList;
611          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = ParentList->GetSubChunk(CHUNK_ID_WSMP);
612          if (wsmp) {          if (wsmp) {
613                wsmp->SetPos(0);
614    
615              uiHeaderSize   = wsmp->ReadUint32();              uiHeaderSize   = wsmp->ReadUint32();
616              UnityNote      = wsmp->ReadUint16();              UnityNote      = wsmp->ReadUint16();
617              FineTune       = wsmp->ReadInt16();              FineTune       = wsmp->ReadInt16();
# Line 535  namespace DLS { Line 651  namespace DLS {
651      /**      /**
652       * Apply all sample player options to the respective RIFF chunk. You       * Apply all sample player options to the respective RIFF chunk. You
653       * have to call File::Save() to make changes persistent.       * have to call File::Save() to make changes persistent.
654         *
655         * @param pProgress - callback function for progress notification
656       */       */
657      void Sampler::UpdateChunks() {      void Sampler::UpdateChunks(progress_t* pProgress) {
658          // make sure 'wsmp' chunk exists          // make sure 'wsmp' chunk exists
659          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
660          int wsmpSize = uiHeaderSize + SampleLoops * 16;          int wsmpSize = uiHeaderSize + SampleLoops * 16;
# Line 568  namespace DLS { Line 686  namespace DLS {
686          }          }
687      }      }
688    
689        /** @brief Remove all RIFF chunks associated with this Sampler object.
690         *
691         * At the moment Sampler::DeleteChunks() does nothing. It is
692         * recommended to call this method explicitly though from deriving classes's
693         * own overridden implementation of this method to avoid potential future
694         * compatiblity issues.
695         *
696         * See Storage::DeleteChunks() for details.
697         */
698        void Sampler::DeleteChunks() {
699        }
700    
701      /**      /**
702       * Adds a new sample loop with the provided loop definition.       * Adds a new sample loop with the provided loop definition.
703       *       *
# Line 612  namespace DLS { Line 742  namespace DLS {
742          pSampleLoops = pNewLoops;          pSampleLoops = pNewLoops;
743          SampleLoops--;          SampleLoops--;
744      }      }
745        
746        /**
747         * Make a deep copy of the Sampler object given by @a orig and assign it
748         * to this object.
749         *
750         * @param orig - original Sampler object to be copied from
751         */
752        void Sampler::CopyAssign(const Sampler* orig) {
753            // copy trivial scalars
754            UnityNote = orig->UnityNote;
755            FineTune = orig->FineTune;
756            Gain = orig->Gain;
757            NoSampleDepthTruncation = orig->NoSampleDepthTruncation;
758            NoSampleCompression = orig->NoSampleCompression;
759            SamplerOptions = orig->SamplerOptions;
760            
761            // copy sample loops
762            if (SampleLoops) delete[] pSampleLoops;
763            pSampleLoops = new sample_loop_t[orig->SampleLoops];
764            memcpy(pSampleLoops, orig->pSampleLoops, orig->SampleLoops * sizeof(sample_loop_t));
765            SampleLoops = orig->SampleLoops;
766        }
767    
768    
769  // *************** Sample ***************  // *************** Sample ***************
# Line 633  namespace DLS { Line 784  namespace DLS {
784       * @param WavePoolOffset - offset of this sample data from wave pool       * @param WavePoolOffset - offset of this sample data from wave pool
785       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
786       */       */
787      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : Resource(pFile, waveList) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset) : Resource(pFile, waveList) {
788          pWaveList = waveList;          pWaveList = waveList;
789          ulWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE;          ullWavePoolOffset = WavePoolOffset - LIST_HEADER_SIZE(waveList->GetFile()->GetFileOffsetSize());
790          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);          pCkFormat = waveList->GetSubChunk(CHUNK_ID_FMT);
791          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);          pCkData   = waveList->GetSubChunk(CHUNK_ID_DATA);
792          if (pCkFormat) {          if (pCkFormat) {
793                pCkFormat->SetPos(0);
794    
795              // common fields              // common fields
796              FormatTag              = pCkFormat->ReadUint16();              FormatTag              = pCkFormat->ReadUint16();
797              Channels               = pCkFormat->ReadUint16();              Channels               = pCkFormat->ReadUint16();
# Line 669  namespace DLS { Line 822  namespace DLS {
822    
823      /** @brief Destructor.      /** @brief Destructor.
824       *       *
825       * Removes RIFF chunks associated with this Sample and frees all       * Frees all memory occupied by this sample.
      * memory occupied by this sample.  
826       */       */
827      Sample::~Sample() {      Sample::~Sample() {
828          RIFF::List* pParent = pWaveList->GetParent();          if (pCkData)
829          pParent->DeleteSubChunk(pWaveList);              pCkData->ReleaseChunkData();
830            if (pCkFormat)
831                pCkFormat->ReleaseChunkData();
832        }
833    
834        /** @brief Remove all RIFF chunks associated with this Sample object.
835         *
836         * See Storage::DeleteChunks() for details.
837         */
838        void Sample::DeleteChunks() {
839            // handle base class
840            Resource::DeleteChunks();
841    
842            // handle own RIFF chunks
843            if (pWaveList) {
844                RIFF::List* pParent = pWaveList->GetParent();
845                pParent->DeleteSubChunk(pWaveList);
846                pWaveList = NULL;
847            }
848        }
849    
850        /**
851         * Make a deep copy of the Sample object given by @a orig (without the
852         * actual sample waveform data however) and assign it to this object.
853         *
854         * This is a special internal variant of CopyAssign() which only copies the
855         * most mandatory member variables. It will be called by gig::Sample
856         * descendent instead of CopyAssign() since gig::Sample has its own
857         * implementation to access and copy the actual sample waveform data.
858         *
859         * @param orig - original Sample object to be copied from
860         */
861        void Sample::CopyAssignCore(const Sample* orig) {
862            // handle base classes
863            Resource::CopyAssign(orig);
864            // handle actual own attributes of this class
865            FormatTag = orig->FormatTag;
866            Channels = orig->Channels;
867            SamplesPerSecond = orig->SamplesPerSecond;
868            AverageBytesPerSecond = orig->AverageBytesPerSecond;
869            BlockAlign = orig->BlockAlign;
870            BitDepth = orig->BitDepth;
871            SamplesTotal = orig->SamplesTotal;
872            FrameSize = orig->FrameSize;
873        }
874        
875        /**
876         * Make a deep copy of the Sample object given by @a orig and assign it to
877         * this object.
878         *
879         * @param orig - original Sample object to be copied from
880         */
881        void Sample::CopyAssign(const Sample* orig) {
882            CopyAssignCore(orig);
883            
884            // copy sample waveform data (reading directly from disc)
885            Resize(orig->GetSize());
886            char* buf = (char*) LoadSampleData();
887            Sample* pOrig = (Sample*) orig; //HACK: circumventing the constness here for now
888            const file_offset_t restorePos = pOrig->pCkData->GetPos();
889            pOrig->SetPos(0);
890            for (file_offset_t todo = pOrig->GetSize(), i = 0; todo; ) {
891                const int iReadAtOnce = 64*1024;
892                file_offset_t n = (iReadAtOnce < todo) ? iReadAtOnce : todo;
893                n = pOrig->Read(&buf[i], n);
894                if (!n) break;
895                todo -= n;
896                i += (n * pOrig->FrameSize);
897            }
898            pOrig->pCkData->SetPos(restorePos);
899      }      }
900    
901      /** @brief Load sample data into RAM.      /** @brief Load sample data into RAM.
# Line 726  namespace DLS { Line 947  namespace DLS {
947       * @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
948       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
949       */       */
950      unsigned long Sample::GetSize() {      file_offset_t Sample::GetSize() const {
951          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;          if (FormatTag != DLS_WAVE_FORMAT_PCM) return 0;
952          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;          return (pCkData) ? pCkData->GetSize() / FrameSize : 0;
953      }      }
# Line 753  namespace DLS { Line 974  namespace DLS {
974       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
975       * other formats will fail!       * other formats will fail!
976       *       *
977       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
978       *                   greater than zero)       *                  greater than zero)
979       * @throws Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM
980       * @throws Exception if \a iNewSize is less than 1       * @throws Exception if \a NewSize is less than 1 or unrealistic large
981       * @see File::Save(), FrameSize, FormatTag       * @see File::Save(), FrameSize, FormatTag
982       */       */
983      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
984          if (FormatTag != 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");
985          if (iNewSize < 1) throw Exception("Sample size must be at least one sample point");          if (NewSize < 1) throw Exception("Sample size must be at least one sample point");
986          const int iSizeInBytes = iNewSize * FrameSize;          if ((NewSize >> 48) != 0)
987                throw Exception("Unrealistic high DLS sample size detected");
988            const file_offset_t sizeInBytes = NewSize * FrameSize;
989          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);          pCkData = pWaveList->GetSubChunk(CHUNK_ID_DATA);
990          if (pCkData) pCkData->Resize(iSizeInBytes);          if (pCkData) pCkData->Resize(sizeInBytes);
991          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, iSizeInBytes);          else pCkData = pWaveList->AddSubChunk(CHUNK_ID_DATA, sizeInBytes);
992      }      }
993    
994      /**      /**
# Line 784  namespace DLS { Line 1007  namespace DLS {
1007       * @throws Exception if no data RIFF chunk was created for the sample yet       * @throws Exception if no data RIFF chunk was created for the sample yet
1008       * @see FrameSize, FormatTag       * @see FrameSize, FormatTag
1009       */       */
1010      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
1011          if (FormatTag != 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
1012          if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");          if (!pCkData) throw Exception("No data chunk created for sample yet, call Sample::Resize() to create one");
1013          unsigned long orderedBytes = SampleCount * FrameSize;          file_offset_t orderedBytes = SampleCount * FrameSize;
1014          unsigned long result = pCkData->SetPos(orderedBytes, Whence);          file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
1015          return (result == orderedBytes) ? SampleCount          return (result == orderedBytes) ? SampleCount
1016                                          : result / FrameSize;                                          : result / FrameSize;
1017      }      }
# Line 802  namespace DLS { Line 1025  namespace DLS {
1025       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1026       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1027       */       */
1028      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount) {
1029          if (FormatTag != 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
1030          return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?          return pCkData->Read(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
1031      }      }
# Line 822  namespace DLS { Line 1045  namespace DLS {
1045       * @throws Exception if current sample size is too small       * @throws Exception if current sample size is too small
1046       * @see LoadSampleData()       * @see LoadSampleData()
1047       */       */
1048      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1049          if (FormatTag != 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
1050          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1051          return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?          return pCkData->Write(pBuffer, SampleCount, FrameSize); // FIXME: channel inversion due to endian correction?
# Line 832  namespace DLS { Line 1055  namespace DLS {
1055       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
1056       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
1057       *       *
1058         * @param pProgress - callback function for progress notification
1059       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
1060       *                   was provided yet       *                   was provided yet
1061       */       */
1062      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
1063          if (FormatTag != DLS_WAVE_FORMAT_PCM)          if (FormatTag != DLS_WAVE_FORMAT_PCM)
1064              throw Exception("Could not save sample, only PCM format is supported");              throw Exception("Could not save sample, only PCM format is supported");
1065          // we refuse to do anything if not sample wave form was provided yet          // we refuse to do anything if not sample wave form was provided yet
1066          if (!pCkData)          if (!pCkData)
1067              throw Exception("Could not save sample, there is no sample data to save");              throw Exception("Could not save sample, there is no sample data to save");
1068          // update chunks of base class as well          // update chunks of base class as well
1069          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1070          // make sure 'fmt' chunk exists          // make sure 'fmt' chunk exists
1071          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);          RIFF::Chunk* pCkFormat = pWaveList->GetSubChunk(CHUNK_ID_FMT);
1072          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format          if (!pCkFormat) pCkFormat = pWaveList->AddSubChunk(CHUNK_ID_FMT, 16); // assumes PCM format
# Line 864  namespace DLS { Line 1088  namespace DLS {
1088      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : Resource(pInstrument, rgnList), Articulator(rgnList), Sampler(rgnList) {
1089          pCkRegion = rgnList;          pCkRegion = rgnList;
1090    
1091          // articulation informations          // articulation information
1092          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = rgnList->GetSubChunk(CHUNK_ID_RGNH);
1093          if (rgnh) {          if (rgnh) {
1094                rgnh->SetPos(0);
1095    
1096              rgnh->Read(&KeyRange, 2, 2);              rgnh->Read(&KeyRange, 2, 2);
1097              rgnh->Read(&VelocityRange, 2, 2);              rgnh->Read(&VelocityRange, 2, 2);
1098              FormatOptionFlags = rgnh->ReadUint16();              FormatOptionFlags = rgnh->ReadUint16();
# Line 886  namespace DLS { Line 1112  namespace DLS {
1112          }          }
1113          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;          SelfNonExclusive = FormatOptionFlags & F_RGN_OPTION_SELFNONEXCLUSIVE;
1114    
1115          // sample informations          // sample information
1116          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = rgnList->GetSubChunk(CHUNK_ID_WLNK);
1117          if (wlnk) {          if (wlnk) {
1118                wlnk->SetPos(0);
1119    
1120              WaveLinkOptionFlags = wlnk->ReadUint16();              WaveLinkOptionFlags = wlnk->ReadUint16();
1121              PhaseGroup          = wlnk->ReadUint16();              PhaseGroup          = wlnk->ReadUint16();
1122              Channel             = wlnk->ReadUint32();              Channel             = wlnk->ReadUint32();
# Line 907  namespace DLS { Line 1135  namespace DLS {
1135    
1136      /** @brief Destructor.      /** @brief Destructor.
1137       *       *
1138       * Removes RIFF chunks associated with this Region.       * Intended to free up all memory occupied by this Region object. ATM this
1139         * destructor implementation does nothing though.
1140       */       */
1141      Region::~Region() {      Region::~Region() {
1142          RIFF::List* pParent = pCkRegion->GetParent();      }
1143          pParent->DeleteSubChunk(pCkRegion);  
1144        /** @brief Remove all RIFF chunks associated with this Region object.
1145         *
1146         * See Storage::DeleteChunks() for details.
1147         */
1148        void Region::DeleteChunks() {
1149            // handle base classes
1150            Resource::DeleteChunks();
1151            Articulator::DeleteChunks();
1152            Sampler::DeleteChunks();
1153    
1154            // handle own RIFF chunks
1155            if (pCkRegion) {
1156                RIFF::List* pParent = pCkRegion->GetParent();
1157                pParent->DeleteSubChunk(pCkRegion);
1158                pCkRegion = NULL;
1159            }
1160      }      }
1161    
1162      Sample* Region::GetSample() {      Sample* Region::GetSample() {
1163          if (pSample) return pSample;          if (pSample) return pSample;
1164          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
1165          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          uint64_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
1166          Sample* sample = file->GetFirstSample();          Sample* sample = file->GetFirstSample();
1167          while (sample) {          while (sample) {
1168              if (sample->ulWavePoolOffset == soughtoffset) return (pSample = sample);              if (sample->ullWavePoolOffset == soughtoffset) return (pSample = sample);
1169              sample = file->GetNextSample();              sample = file->GetNextSample();
1170          }          }
1171          return NULL;          return NULL;
# Line 975  namespace DLS { Line 1220  namespace DLS {
1220       * Apply Region settings to the respective RIFF chunks. You have to       * Apply Region settings to the respective RIFF chunks. You have to
1221       * call File::Save() to make changes persistent.       * call File::Save() to make changes persistent.
1222       *       *
1223         * @param pProgress - callback function for progress notification
1224       * @throws Exception - if the Region's sample could not be found       * @throws Exception - if the Region's sample could not be found
1225       */       */
1226      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
1227          // make sure 'rgnh' chunk exists          // make sure 'rgnh' chunk exists
1228          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);          RIFF::Chunk* rgnh = pCkRegion->GetSubChunk(CHUNK_ID_RGNH);
1229          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);          if (!rgnh) rgnh = pCkRegion->AddSubChunk(CHUNK_ID_RGNH, Layer ? 14 : 12);
# Line 996  namespace DLS { Line 1242  namespace DLS {
1242    
1243          // update chunks of base classes as well (but skip Resource,          // update chunks of base classes as well (but skip Resource,
1244          // as a rgn doesn't seem to have dlid and INFO chunks)          // as a rgn doesn't seem to have dlid and INFO chunks)
1245          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1246          Sampler::UpdateChunks();          Sampler::UpdateChunks(pProgress);
1247    
1248          // make sure 'wlnk' chunk exists          // make sure 'wlnk' chunk exists
1249          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);          RIFF::Chunk* wlnk = pCkRegion->GetSubChunk(CHUNK_ID_WLNK);
# Line 1029  namespace DLS { Line 1275  namespace DLS {
1275          store32(&pData[4], Channel);          store32(&pData[4], Channel);
1276          store32(&pData[8], WavePoolTableIndex);          store32(&pData[8], WavePoolTableIndex);
1277      }      }
1278        
1279        /**
1280         * Make a (semi) deep copy of the Region object given by @a orig and assign
1281         * it to this object.
1282         *
1283         * Note that the sample pointer referenced by @a orig is simply copied as
1284         * memory address. Thus the respective sample is shared, not duplicated!
1285         *
1286         * @param orig - original Region object to be copied from
1287         */
1288        void Region::CopyAssign(const Region* orig) {
1289            // handle base classes
1290            Resource::CopyAssign(orig);
1291            Articulator::CopyAssign(orig);
1292            Sampler::CopyAssign(orig);
1293            // handle actual own attributes of this class
1294            // (the trivial ones)
1295            VelocityRange = orig->VelocityRange;
1296            KeyGroup = orig->KeyGroup;
1297            Layer = orig->Layer;
1298            SelfNonExclusive = orig->SelfNonExclusive;
1299            PhaseMaster = orig->PhaseMaster;
1300            PhaseGroup = orig->PhaseGroup;
1301            MultiChannel = orig->MultiChannel;
1302            Channel = orig->Channel;
1303            // only take the raw sample reference if the two Region objects are
1304            // part of the same file
1305            if (GetParent()->GetParent() == orig->GetParent()->GetParent()) {
1306                WavePoolTableIndex = orig->WavePoolTableIndex;
1307                pSample = orig->pSample;
1308            } else {
1309                WavePoolTableIndex = -1;
1310                pSample = NULL;
1311            }
1312            FormatOptionFlags = orig->FormatOptionFlags;
1313            WaveLinkOptionFlags = orig->WaveLinkOptionFlags;
1314            // handle the last, a bit sensible attribute
1315            SetKeyRange(orig->KeyRange.low, orig->KeyRange.high);
1316        }
1317    
1318    
1319  // *************** Instrument ***************  // *************** Instrument ***************
# Line 1054  namespace DLS { Line 1338  namespace DLS {
1338          midi_locale_t locale;          midi_locale_t locale;
1339          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1340          if (insh) {          if (insh) {
1341                insh->SetPos(0);
1342    
1343              Regions = insh->ReadUint32();              Regions = insh->ReadUint32();
1344              insh->Read(&locale, 2, 4);              insh->Read(&locale, 2, 4);
1345          } else { // 'insh' chunk missing          } else { // 'insh' chunk missing
# Line 1106  namespace DLS { Line 1392  namespace DLS {
1392          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
1393          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
1394          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
1395          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1396          return pNewRegion;          return pNewRegion;
1397      }      }
1398    
1399      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {      void Instrument::MoveRegion(Region* pSrc, Region* pDst) {
1400          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
1401          lrgn->MoveSubChunk(pSrc->pCkRegion, pDst ? pDst->pCkRegion : 0);          lrgn->MoveSubChunk(pSrc->pCkRegion, (RIFF::Chunk*) (pDst ? pDst->pCkRegion : 0));
1402    
1403          pRegions->remove(pSrc);          pRegions->remove(pSrc);
1404          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pDst);
# Line 1124  namespace DLS { Line 1410  namespace DLS {
1410          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);          RegionList::iterator iter = find(pRegions->begin(), pRegions->end(), pRegion);
1411          if (iter == pRegions->end()) return;          if (iter == pRegions->end()) return;
1412          pRegions->erase(iter);          pRegions->erase(iter);
1413          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
1414            pRegion->DeleteChunks();
1415          delete pRegion;          delete pRegion;
1416      }      }
1417    
# Line 1132  namespace DLS { Line 1419  namespace DLS {
1419       * Apply Instrument with all its Regions to the respective RIFF chunks.       * Apply Instrument with all its Regions to the respective RIFF chunks.
1420       * You have to call File::Save() to make changes persistent.       * You have to call File::Save() to make changes persistent.
1421       *       *
1422         * @param pProgress - callback function for progress notification
1423       * @throws Exception - on errors       * @throws Exception - on errors
1424       */       */
1425      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
1426          // first update base classes' chunks          // first update base classes' chunks
1427          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1428          Articulator::UpdateChunks();          Articulator::UpdateChunks(pProgress);
1429          // make sure 'insh' chunk exists          // make sure 'insh' chunk exists
1430          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);          RIFF::Chunk* insh = pCkInstrument->GetSubChunk(CHUNK_ID_INSH);
1431          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);          if (!insh) insh = pCkInstrument->AddSubChunk(CHUNK_ID_INSH, 12);
1432          uint8_t* pData = (uint8_t*) insh->LoadChunkData();          uint8_t* pData = (uint8_t*) insh->LoadChunkData();
1433          // update 'insh' chunk          // update 'insh' chunk
1434          Regions = (pRegions) ? pRegions->size() : 0;          Regions = (pRegions) ? uint32_t(pRegions->size()) : 0;
1435          midi_locale_t locale;          midi_locale_t locale;
1436          locale.instrument = MIDIProgram;          locale.instrument = MIDIProgram;
1437          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);          locale.bank       = MIDI_BANK_ENCODE(MIDIBankCoarse, MIDIBankFine);
# Line 1156  namespace DLS { Line 1444  namespace DLS {
1444          if (!pRegions) return;          if (!pRegions) return;
1445          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
1446          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
1447          for (; iter != end; ++iter) {          for (int i = 0; iter != end; ++iter, ++i) {
1448              (*iter)->UpdateChunks();              if (pProgress) {
1449                    // divide local progress into subprogress
1450                    progress_t subprogress;
1451                    __divide_progress(pProgress, &subprogress, pRegions->size(), i);
1452                    // do the actual work
1453                    (*iter)->UpdateChunks(&subprogress);
1454                } else
1455                    (*iter)->UpdateChunks(NULL);
1456          }          }
1457            if (pProgress)
1458                __notify_progress(pProgress, 1.0); // notify done
1459      }      }
1460    
1461      /** @brief Destructor.      /** @brief Destructor.
1462       *       *
1463       * Removes RIFF chunks associated with this Instrument and frees all       * Frees all memory occupied by this instrument.
      * memory occupied by this instrument.  
1464       */       */
1465      Instrument::~Instrument() {      Instrument::~Instrument() {
1466          if (pRegions) {          if (pRegions) {
# Line 1176  namespace DLS { Line 1472  namespace DLS {
1472              }              }
1473              delete pRegions;              delete pRegions;
1474          }          }
         // remove instrument's chunks  
         RIFF::List* pParent = pCkInstrument->GetParent();  
         pParent->DeleteSubChunk(pCkInstrument);  
1475      }      }
1476    
1477        /** @brief Remove all RIFF chunks associated with this Instrument object.
1478         *
1479         * See Storage::DeleteChunks() for details.
1480         */
1481        void Instrument::DeleteChunks() {
1482            // handle base classes
1483            Resource::DeleteChunks();
1484            Articulator::DeleteChunks();
1485    
1486            // handle RIFF chunks of members
1487            if (pRegions) {
1488                RegionList::iterator it  = pRegions->begin();
1489                RegionList::iterator end = pRegions->end();
1490                for (; it != end; ++it)
1491                    (*it)->DeleteChunks();
1492            }
1493    
1494            // handle own RIFF chunks
1495            if (pCkInstrument) {
1496                RIFF::List* pParent = pCkInstrument->GetParent();
1497                pParent->DeleteSubChunk(pCkInstrument);
1498                pCkInstrument = NULL;
1499            }
1500        }
1501    
1502        void Instrument::CopyAssignCore(const Instrument* orig) {
1503            // handle base classes
1504            Resource::CopyAssign(orig);
1505            Articulator::CopyAssign(orig);
1506            // handle actual own attributes of this class
1507            // (the trivial ones)
1508            IsDrum = orig->IsDrum;
1509            MIDIBank = orig->MIDIBank;
1510            MIDIBankCoarse = orig->MIDIBankCoarse;
1511            MIDIBankFine = orig->MIDIBankFine;
1512            MIDIProgram = orig->MIDIProgram;
1513        }
1514        
1515        /**
1516         * Make a (semi) deep copy of the Instrument object given by @a orig and assign
1517         * it to this object.
1518         *
1519         * Note that all sample pointers referenced by @a orig are simply copied as
1520         * memory address. Thus the respective samples are shared, not duplicated!
1521         *
1522         * @param orig - original Instrument object to be copied from
1523         */
1524        void Instrument::CopyAssign(const Instrument* orig) {
1525            CopyAssignCore(orig);
1526            // delete all regions first
1527            while (Regions) DeleteRegion(GetFirstRegion());
1528            // now recreate and copy regions
1529            {
1530                RegionList::const_iterator it = orig->pRegions->begin();
1531                for (int i = 0; i < orig->Regions; ++i, ++it) {
1532                    Region* dstRgn = AddRegion();
1533                    //NOTE: Region does semi-deep copy !
1534                    dstRgn->CopyAssign(*it);
1535                }
1536            }
1537        }
1538    
1539    
1540  // *************** File ***************  // *************** File ***************
# Line 1194  namespace DLS { Line 1548  namespace DLS {
1548       */       */
1549      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {      File::File() : Resource(NULL, pRIFF = new RIFF::File(RIFF_TYPE_DLS)) {
1550          pRIFF->SetByteOrder(RIFF::endian_little);          pRIFF->SetByteOrder(RIFF::endian_little);
1551            bOwningRiff = true;
1552          pVersion = new version_t;          pVersion = new version_t;
1553          pVersion->major   = 0;          pVersion->major   = 0;
1554          pVersion->minor   = 0;          pVersion->minor   = 0;
# Line 1224  namespace DLS { Line 1579  namespace DLS {
1579      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {      File::File(RIFF::File* pRIFF) : Resource(NULL, pRIFF) {
1580          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");          if (!pRIFF) throw DLS::Exception("NULL pointer reference to RIFF::File object.");
1581          this->pRIFF = pRIFF;          this->pRIFF = pRIFF;
1582            bOwningRiff = false;
1583          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);          RIFF::Chunk* ckVersion = pRIFF->GetSubChunk(CHUNK_ID_VERS);
1584          if (ckVersion) {          if (ckVersion) {
1585                ckVersion->SetPos(0);
1586    
1587              pVersion = new version_t;              pVersion = new version_t;
1588              ckVersion->Read(pVersion, 4, 2);              ckVersion->Read(pVersion, 4, 2);
1589          }          }
# Line 1234  namespace DLS { Line 1591  namespace DLS {
1591    
1592          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1593          if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");          if (!colh) throw DLS::Exception("Mandatory chunks in RIFF list chunk not found.");
1594            colh->SetPos(0);
1595          Instruments = colh->ReadUint32();          Instruments = colh->ReadUint32();
1596    
1597          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
# Line 1244  namespace DLS { Line 1602  namespace DLS {
1602              WavePoolHeaderSize = 8;              WavePoolHeaderSize = 8;
1603              b64BitWavePoolOffsets = false;              b64BitWavePoolOffsets = false;
1604          } else {          } else {
1605                ptbl->SetPos(0);
1606    
1607              WavePoolHeaderSize = ptbl->ReadUint32();              WavePoolHeaderSize = ptbl->ReadUint32();
1608              WavePoolCount  = ptbl->ReadUint32();              WavePoolCount  = ptbl->ReadUint32();
1609              pWavePoolTable = new uint32_t[WavePoolCount];              pWavePoolTable = new uint32_t[WavePoolCount];
# Line 1256  namespace DLS { Line 1616  namespace DLS {
1616                  for (int i = 0 ; i < WavePoolCount ; i++) {                  for (int i = 0 ; i < WavePoolCount ; i++) {
1617                      pWavePoolTableHi[i] = ptbl->ReadUint32();                      pWavePoolTableHi[i] = ptbl->ReadUint32();
1618                      pWavePoolTable[i] = ptbl->ReadUint32();                      pWavePoolTable[i] = ptbl->ReadUint32();
1619                      if (pWavePoolTable[i] & 0x80000000)                      //NOTE: disabled this 2GB check, not sure why this check was still left here (Christian, 2016-05-12)
1620                          throw DLS::Exception("Files larger than 2 GB not yet supported");                      //if (pWavePoolTable[i] & 0x80000000)
1621                        //    throw DLS::Exception("Files larger than 2 GB not yet supported");
1622                  }                  }
1623              } else { // conventional 32 bit offsets              } else { // conventional 32 bit offsets
1624                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));                  ptbl->Read(pWavePoolTable, WavePoolCount, sizeof(uint32_t));
# Line 1295  namespace DLS { Line 1656  namespace DLS {
1656          if (pVersion) delete pVersion;          if (pVersion) delete pVersion;
1657          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++)
1658              delete *i;              delete *i;
1659            if (bOwningRiff)
1660                delete pRIFF;
1661      }      }
1662    
1663      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample() {
# Line 1314  namespace DLS { Line 1677  namespace DLS {
1677          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
1678          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
1679          if (wvpl) {          if (wvpl) {
1680              unsigned long wvplFileOffset = wvpl->GetFilePos();              file_offset_t wvplFileOffset = wvpl->GetFilePos() -
1681                                               wvpl->GetPos(); // should be zero, but just to be sure
1682              RIFF::List* wave = wvpl->GetFirstSubList();              RIFF::List* wave = wvpl->GetFirstSubList();
1683              while (wave) {              while (wave) {
1684                  if (wave->GetListType() == LIST_TYPE_WAVE) {                  if (wave->GetListType() == LIST_TYPE_WAVE) {
1685                      unsigned long waveFileOffset = wave->GetFilePos();                      file_offset_t waveFileOffset = wave->GetFilePos() -
1686                                                       wave->GetPos(); // should be zero, but just to be sure
1687                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));
1688                  }                  }
1689                  wave = wvpl->GetNextSubList();                  wave = wvpl->GetNextSubList();
# Line 1327  namespace DLS { Line 1692  namespace DLS {
1692          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)
1693              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);              RIFF::List* dwpl = pRIFF->GetSubList(LIST_TYPE_DWPL);
1694              if (dwpl) {              if (dwpl) {
1695                  unsigned long dwplFileOffset = dwpl->GetFilePos();                  file_offset_t dwplFileOffset = dwpl->GetFilePos() -
1696                                                   dwpl->GetPos(); // should be zero, but just to be sure
1697                  RIFF::List* wave = dwpl->GetFirstSubList();                  RIFF::List* wave = dwpl->GetFirstSubList();
1698                  while (wave) {                  while (wave) {
1699                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
1700                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos() -
1701                                                           wave->GetPos(); // should be zero, but just to be sure
1702                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - dwplFileOffset));
1703                      }                      }
1704                      wave = dwpl->GetNextSubList();                      wave = dwpl->GetNextSubList();
# Line 1370  namespace DLS { Line 1737  namespace DLS {
1737          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);
1738          if (iter == pSamples->end()) return;          if (iter == pSamples->end()) return;
1739          pSamples->erase(iter);          pSamples->erase(iter);
1740            pSample->DeleteChunks();
1741          delete pSample;          delete pSample;
1742      }      }
1743    
# Line 1429  namespace DLS { Line 1797  namespace DLS {
1797          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);
1798          if (iter == pInstruments->end()) return;          if (iter == pInstruments->end()) return;
1799          pInstruments->erase(iter);          pInstruments->erase(iter);
1800            pInstrument->DeleteChunks();
1801          delete pInstrument;          delete pInstrument;
1802      }      }
1803    
1804        /**
1805         * Returns the underlying RIFF::File used for persistency of this DLS::File
1806         * object.
1807         */
1808        RIFF::File* File::GetRiffFile() {
1809            return pRIFF;
1810        }
1811    
1812        /**
1813         * Returns extension file of given index. Extension files are used
1814         * sometimes to circumvent the 2 GB file size limit of the RIFF format and
1815         * of certain operating systems in general. In this case, instead of just
1816         * using one file, the content is spread among several files with similar
1817         * file name scheme. This is especially used by some GigaStudio sound
1818         * libraries.
1819         *
1820         * @param index - index of extension file
1821         * @returns sought extension file, NULL if index out of bounds
1822         * @see GetFileName()
1823         */
1824        RIFF::File* File::GetExtensionFile(int index) {
1825            if (index < 0 || index >= ExtensionFiles.size()) return NULL;
1826            std::list<RIFF::File*>::iterator iter = ExtensionFiles.begin();
1827            for (int i = 0; iter != ExtensionFiles.end(); ++iter, ++i)
1828                if (i == index) return *iter;
1829            return NULL;
1830        }
1831    
1832      /** @brief File name of this DLS file.      /** @brief File name of this DLS file.
1833       *       *
1834       * This method returns the file name as it was provided when loading       * This method returns the file name as it was provided when loading
1835       * the respective DLS file. However in case the File object associates       * the respective DLS file. However in case the File object associates
1836       * an empty, that is new DLS file, which was not yet saved to disk,       * an empty, that is new DLS file, which was not yet saved to disk,
1837       * this method will return an empty string.       * this method will return an empty string.
1838         *
1839         * @see GetExtensionFile()
1840       */       */
1841      String File::GetFileName() {      String File::GetFileName() {
1842          return pRIFF->GetFileName();          return pRIFF->GetFileName();
1843      }      }
1844        
1845        /**
1846         * You may call this method store a future file name, so you don't have to
1847         * to pass it to the Save() call later on.
1848         */
1849        void File::SetFileName(const String& name) {
1850            pRIFF->SetFileName(name);
1851        }
1852    
1853      /**      /**
1854       * Apply all the DLS file's current instruments, samples and settings to       * Apply all the DLS file's current instruments, samples and settings to
1855       * the respective RIFF chunks. You have to call Save() to make changes       * the respective RIFF chunks. You have to call Save() to make changes
1856       * persistent.       * persistent.
1857       *       *
1858         * @param pProgress - callback function for progress notification
1859       * @throws Exception - on errors       * @throws Exception - on errors
1860       */       */
1861      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
1862          // first update base class's chunks          // first update base class's chunks
1863          Resource::UpdateChunks();          Resource::UpdateChunks(pProgress);
1864    
1865          // if version struct exists, update 'vers' chunk          // if version struct exists, update 'vers' chunk
1866          if (pVersion) {          if (pVersion) {
# Line 1466  namespace DLS { Line 1874  namespace DLS {
1874          }          }
1875    
1876          // update 'colh' chunk          // update 'colh' chunk
1877          Instruments = (pInstruments) ? pInstruments->size() : 0;          Instruments = (pInstruments) ? uint32_t(pInstruments->size()) : 0;
1878          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);          RIFF::Chunk* colh = pRIFF->GetSubChunk(CHUNK_ID_COLH);
1879          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);          if (!colh)   colh = pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
1880          uint8_t* pData = (uint8_t*) colh->LoadChunkData();          uint8_t* pData = (uint8_t*) colh->LoadChunkData();
# Line 1474  namespace DLS { Line 1882  namespace DLS {
1882    
1883          // update instrument's chunks          // update instrument's chunks
1884          if (pInstruments) {          if (pInstruments) {
1885              InstrumentList::iterator iter = pInstruments->begin();              if (pProgress) {
1886              InstrumentList::iterator end  = pInstruments->end();                  // divide local progress into subprogress
1887              for (; iter != end; ++iter) {                  progress_t subprogress;
1888                  (*iter)->UpdateChunks();                  __divide_progress(pProgress, &subprogress, 20.f, 0.f); // arbitrarily subdivided into 5% of total progress
1889    
1890                    // do the actual work
1891                    InstrumentList::iterator iter = pInstruments->begin();
1892                    InstrumentList::iterator end  = pInstruments->end();
1893                    for (int i = 0; iter != end; ++iter, ++i) {
1894                        // divide subprogress into sub-subprogress
1895                        progress_t subsubprogress;
1896                        __divide_progress(&subprogress, &subsubprogress, pInstruments->size(), i);
1897                        // do the actual work
1898                        (*iter)->UpdateChunks(&subsubprogress);
1899                    }
1900    
1901                    __notify_progress(&subprogress, 1.0); // notify subprogress done
1902                } else {
1903                    InstrumentList::iterator iter = pInstruments->begin();
1904                    InstrumentList::iterator end  = pInstruments->end();
1905                    for (int i = 0; iter != end; ++iter, ++i) {
1906                        (*iter)->UpdateChunks(NULL);
1907                    }
1908              }              }
1909          }          }
1910    
1911          // update 'ptbl' chunk          // update 'ptbl' chunk
1912          const int iSamples = (pSamples) ? pSamples->size() : 0;          const int iSamples = (pSamples) ? int(pSamples->size()) : 0;
1913          const int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          int iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
1914          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
1915          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*/);
1916          const int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;          int iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
1917          ptbl->Resize(iPtblSize);          ptbl->Resize(iPtblSize);
1918          pData = (uint8_t*) ptbl->LoadChunkData();          pData = (uint8_t*) ptbl->LoadChunkData();
1919          WavePoolCount = iSamples;          WavePoolCount = iSamples;
# Line 1496  namespace DLS { Line 1923  namespace DLS {
1923    
1924          // update sample's chunks          // update sample's chunks
1925          if (pSamples) {          if (pSamples) {
1926              SampleList::iterator iter = pSamples->begin();              if (pProgress) {
1927              SampleList::iterator end  = pSamples->end();                  // divide local progress into subprogress
1928              for (; iter != end; ++iter) {                  progress_t subprogress;
1929                  (*iter)->UpdateChunks();                  __divide_progress(pProgress, &subprogress, 20.f, 1.f); // arbitrarily subdivided into 95% of total progress
1930    
1931                    // do the actual work
1932                    SampleList::iterator iter = pSamples->begin();
1933                    SampleList::iterator end  = pSamples->end();
1934                    for (int i = 0; iter != end; ++iter, ++i) {
1935                        // divide subprogress into sub-subprogress
1936                        progress_t subsubprogress;
1937                        __divide_progress(&subprogress, &subsubprogress, pSamples->size(), i);
1938                        // do the actual work
1939                        (*iter)->UpdateChunks(&subsubprogress);
1940                    }
1941    
1942                    __notify_progress(&subprogress, 1.0); // notify subprogress done
1943                } else {
1944                    SampleList::iterator iter = pSamples->begin();
1945                    SampleList::iterator end  = pSamples->end();
1946                    for (int i = 0; iter != end; ++iter, ++i) {
1947                        (*iter)->UpdateChunks(NULL);
1948                    }
1949                }
1950            }
1951    
1952            // if there are any extension files, gather which ones are regular
1953            // extension files used as wave pool files (.gx00, .gx01, ... , .gx98)
1954            // and which one is probably a convolution (GigaPulse) file (always to
1955            // be saved as .gx99)
1956            std::list<RIFF::File*> poolFiles;  // < for (.gx00, .gx01, ... , .gx98) files
1957            RIFF::File* pGigaPulseFile = NULL; // < for .gx99 file
1958            if (!ExtensionFiles.empty()) {
1959                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
1960                for (; it != ExtensionFiles.end(); ++it) {
1961                    //FIXME: the .gx99 file is always used by GSt for convolution
1962                    // data (GigaPulse); so we should better detect by subchunk
1963                    // whether the extension file is intended for convolution
1964                    // instead of checkking for a file name, because the latter does
1965                    // not work for saving new gigs created from scratch
1966                    const std::string oldName = (*it)->GetFileName();
1967                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
1968                    if (isGigaPulseFile)
1969                        pGigaPulseFile = *it;
1970                    else
1971                        poolFiles.push_back(*it);
1972                }
1973            }
1974    
1975            // update the 'xfil' chunk which describes all extension files (wave
1976            // pool files) except the .gx99 file
1977            if (!poolFiles.empty()) {
1978                const int n = poolFiles.size();
1979                const int iHeaderSize = 4;
1980                const int iEntrySize = 144;
1981    
1982                // make sure chunk exists, and with correct size
1983                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
1984                if (ckXfil)
1985                    ckXfil->Resize(iHeaderSize + n * iEntrySize);
1986                else
1987                    ckXfil = pRIFF->AddSubChunk(CHUNK_ID_XFIL, iHeaderSize + n * iEntrySize);
1988    
1989                uint8_t* pData = (uint8_t*) ckXfil->LoadChunkData();
1990    
1991                // re-assemble the chunk's content
1992                store32(pData, n);
1993                std::list<RIFF::File*>::iterator itExtFile = poolFiles.begin();
1994                for (int i = 0, iOffset = 4; i < n;
1995                     ++itExtFile, ++i, iOffset += iEntrySize)
1996                {
1997                    // update the filename string and 5 byte extension of each extension file
1998                    std::string file = lastPathComponent(
1999                        (*itExtFile)->GetFileName()
2000                    );
2001                    if (file.length() + 6 > 128)
2002                        throw Exception("Fatal error, extension filename length exceeds 122 byte maximum");
2003                    uint8_t* pStrings = &pData[iOffset];
2004                    memset(pStrings, 0, 128);
2005                    memcpy(pStrings, file.c_str(), file.length());
2006                    pStrings += file.length() + 1;
2007                    std::string ext = file.substr(file.length()-5);
2008                    memcpy(pStrings, ext.c_str(), 5);
2009                    // update the dlsid of the extension file
2010                    uint8_t* pId = &pData[iOffset + 128];
2011                    dlsid_t id;
2012                    RIFF::Chunk* ckDLSID = (*itExtFile)->GetSubChunk(CHUNK_ID_DLID);
2013                    if (ckDLSID) {
2014                        ckDLSID->Read(&id.ulData1, 1, 4);
2015                        ckDLSID->Read(&id.usData2, 1, 2);
2016                        ckDLSID->Read(&id.usData3, 1, 2);
2017                        ckDLSID->Read(id.abData, 8, 1);
2018                    } else {
2019                        ckDLSID = (*itExtFile)->AddSubChunk(CHUNK_ID_DLID, 16);
2020                        Resource::GenerateDLSID(&id);
2021                        uint8_t* pData = (uint8_t*)ckDLSID->LoadChunkData();
2022                        store32(&pData[0], id.ulData1);
2023                        store16(&pData[4], id.usData2);
2024                        store16(&pData[6], id.usData3);
2025                        memcpy(&pData[8], id.abData, 8);
2026                    }
2027                    store32(&pId[0], id.ulData1);
2028                    store16(&pId[4], id.usData2);
2029                    store16(&pId[6], id.usData3);
2030                    memcpy(&pId[8], id.abData, 8);
2031                }
2032            } else {
2033                // in case there was a 'xfil' chunk, remove it
2034                RIFF::Chunk* ckXfil = pRIFF->GetSubChunk(CHUNK_ID_XFIL);
2035                if (ckXfil) pRIFF->DeleteSubChunk(ckXfil);
2036            }
2037    
2038            // update the 'doxf' chunk which describes a .gx99 extension file
2039            // which contains convolution data (GigaPulse)
2040            if (pGigaPulseFile) {
2041                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2042                if (!ckDoxf) ckDoxf = pRIFF->AddSubChunk(CHUNK_ID_DOXF, 148);
2043    
2044                uint8_t* pData = (uint8_t*) ckDoxf->LoadChunkData();
2045    
2046                // update the dlsid from the extension file
2047                uint8_t* pId = &pData[132];
2048                RIFF::Chunk* ckDLSID = pGigaPulseFile->GetSubChunk(CHUNK_ID_DLID);
2049                if (!ckDLSID) { //TODO: auto generate DLS ID if missing
2050                    throw Exception("Fatal error, GigaPulse file does not contain a DLS ID chunk");
2051                } else {
2052                    dlsid_t id;
2053                    // read DLS ID from extension files's DLS ID chunk
2054                    uint8_t* pData = (uint8_t*) ckDLSID->LoadChunkData();
2055                    id.ulData1 = load32(&pData[0]);
2056                    id.usData2 = load16(&pData[4]);
2057                    id.usData3 = load16(&pData[6]);
2058                    memcpy(id.abData, &pData[8], 8);
2059                    // store DLS ID to 'doxf' chunk
2060                    store32(&pId[0], id.ulData1);
2061                    store16(&pId[4], id.usData2);
2062                    store16(&pId[6], id.usData3);
2063                    memcpy(&pId[8], id.abData, 8);
2064              }              }
2065            } else {
2066                // in case there was a 'doxf' chunk, remove it
2067                RIFF::Chunk* ckDoxf = pRIFF->GetSubChunk(CHUNK_ID_DOXF);
2068                if (ckDoxf) pRIFF->DeleteSubChunk(ckDoxf);
2069            }
2070    
2071            // the RIFF file to be written might now been grown >= 4GB or might
2072            // been shrunk < 4GB, so we might need to update the wave pool offset
2073            // size and thus accordingly we would need to resize the wave pool
2074            // chunk
2075            const file_offset_t finalFileSize = pRIFF->GetRequiredFileSize();
2076            const bool bRequires64Bit = (finalFileSize >> 32) != 0 || // < native 64 bit gig file
2077                                         poolFiles.size() > 0;        // < 32 bit gig file where the hi 32 bits are used as extension file nr
2078            if (b64BitWavePoolOffsets != bRequires64Bit) {
2079                b64BitWavePoolOffsets = bRequires64Bit;
2080                iPtblOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2081                iPtblSize = WavePoolHeaderSize + iPtblOffsetSize * iSamples;
2082                ptbl->Resize(iPtblSize);
2083          }          }
2084    
2085            if (pProgress)
2086                __notify_progress(pProgress, 1.0); // notify done
2087      }      }
2088    
2089      /** @brief Save changes to another file.      /** @brief Save changes to another file.
# Line 1516  namespace DLS { Line 2098  namespace DLS {
2098       * the new file (given by \a Path) afterwards.       * the new file (given by \a Path) afterwards.
2099       *       *
2100       * @param Path - path and file name where everything should be written to       * @param Path - path and file name where everything should be written to
2101         * @param pProgress - optional: callback function for progress notification
2102       */       */
2103      void File::Save(const String& Path) {      void File::Save(const String& Path, progress_t* pProgress) {
2104          UpdateChunks();          // calculate number of tasks to notify progress appropriately
2105          pRIFF->Save(Path);          const size_t nExtFiles = ExtensionFiles.size();
2106          __UpdateWavePoolTableChunk();          const float tasks = 2.f + nExtFiles;
2107    
2108            // save extension files (if required)
2109            if (!ExtensionFiles.empty()) {
2110                // for assembling path of extension files to be saved to
2111                const std::string baseName = pathWithoutExtension(Path);
2112                // save the individual extension files
2113                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2114                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2115                    //FIXME: the .gx99 file is always used by GSt for convolution
2116                    // data (GigaPulse); so we should better detect by subchunk
2117                    // whether the extension file is intended for convolution
2118                    // instead of checkking for a file name, because the latter does
2119                    // not work for saving new gigs created from scratch
2120                    const std::string oldName = (*it)->GetFileName();
2121                    const bool isGigaPulseFile = (extensionOfPath(oldName) == "gx99");
2122                    std::string ext = (isGigaPulseFile) ? ".gx99" : strPrint(".gx%02d", i+1);
2123                    std::string newPath = baseName + ext;
2124                    // save extension file to its new location
2125                    if (pProgress) {
2126                         // divide local progress into subprogress
2127                        progress_t subprogress;
2128                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2129                        // do the actual work
2130                        (*it)->Save(newPath, &subprogress);
2131                    } else
2132                        (*it)->Save(newPath);
2133                }
2134            }
2135    
2136            if (pProgress) {
2137                // divide local progress into subprogress
2138                progress_t subprogress;
2139                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2140                // do the actual work
2141                UpdateChunks(&subprogress);
2142            } else
2143                UpdateChunks(NULL);
2144    
2145            if (pProgress) {
2146                // divide local progress into subprogress
2147                progress_t subprogress;
2148                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2149                // do the actual work
2150                pRIFF->Save(Path, &subprogress);
2151            } else
2152                pRIFF->Save(Path);
2153    
2154            UpdateFileOffsets();
2155    
2156            if (pProgress)
2157                __notify_progress(pProgress, 1.0); // notify done
2158      }      }
2159    
2160      /** @brief Save changes to same file.      /** @brief Save changes to same file.
# Line 1529  namespace DLS { Line 2163  namespace DLS {
2163       * 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
2164       * have at the end of the saving process.       * have at the end of the saving process.
2165       *       *
2166       * @throws RIFF::Exception if any kind of IO error occured       * @param pProgress - optional: callback function for progress notification
2167       * @throws DLS::Exception  if any kind of DLS specific error occured       * @throws RIFF::Exception if any kind of IO error occurred
2168         * @throws DLS::Exception  if any kind of DLS specific error occurred
2169         */
2170        void File::Save(progress_t* pProgress) {
2171            // calculate number of tasks to notify progress appropriately
2172            const size_t nExtFiles = ExtensionFiles.size();
2173            const float tasks = 2.f + nExtFiles;
2174    
2175            // save extension files (if required)
2176            if (!ExtensionFiles.empty()) {
2177                std::list<RIFF::File*>::iterator it = ExtensionFiles.begin();
2178                for (int i = 0; it != ExtensionFiles.end(); ++i, ++it) {
2179                    // save extension file
2180                    if (pProgress) {
2181                        // divide local progress into subprogress
2182                        progress_t subprogress;
2183                        __divide_progress(pProgress, &subprogress, tasks, 0.f + i); // subdivided into amount of extension files
2184                        // do the actual work
2185                        (*it)->Save(&subprogress);
2186                    } else
2187                        (*it)->Save();
2188                }
2189            }
2190    
2191            if (pProgress) {
2192                // divide local progress into subprogress
2193                progress_t subprogress;
2194                __divide_progress(pProgress, &subprogress, tasks, 1.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2195                // do the actual work
2196                UpdateChunks(&subprogress);
2197            } else
2198                UpdateChunks(NULL);
2199    
2200            if (pProgress) {
2201                // divide local progress into subprogress
2202                progress_t subprogress;
2203                __divide_progress(pProgress, &subprogress, tasks, 2.f + nExtFiles); // arbitrarily subdivided into 50% (minus extension files progress)
2204                // do the actual work
2205                pRIFF->Save(&subprogress);
2206            } else
2207                pRIFF->Save();
2208    
2209            UpdateFileOffsets();
2210    
2211            if (pProgress)
2212                __notify_progress(pProgress, 1.0); // notify done
2213        }
2214    
2215        /** @brief Updates all file offsets stored all over the file.
2216         *
2217         * This virtual method is called whenever the overall file layout has been
2218         * changed (i.e. file or individual RIFF chunks have been resized). It is
2219         * then the responsibility of this method to update all file offsets stored
2220         * in the file format. For example samples are referenced by instruments by
2221         * file offsets. The gig format also stores references to instrument
2222         * scripts as file offsets, and thus it overrides this method to update
2223         * those file offsets as well.
2224       */       */
2225      void File::Save() {      void File::UpdateFileOffsets() {
         UpdateChunks();  
         pRIFF->Save();  
2226          __UpdateWavePoolTableChunk();          __UpdateWavePoolTableChunk();
2227      }      }
2228    
# Line 1572  namespace DLS { Line 2260  namespace DLS {
2260          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);          RIFF::Chunk* ptbl = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
2261          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;          const int iOffsetSize = (b64BitWavePoolOffsets) ? 8 : 4;
2262          // check if 'ptbl' chunk is large enough          // check if 'ptbl' chunk is large enough
2263          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2264          const unsigned long ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;          const file_offset_t ulRequiredSize = WavePoolHeaderSize + iOffsetSize * WavePoolCount;
2265          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");          if (ptbl->GetSize() < ulRequiredSize) throw Exception("Fatal error, 'ptbl' chunk too small");
2266          // save the 'ptbl' chunk's current read/write position          // save the 'ptbl' chunk's current read/write position
2267          unsigned long ulOriginalPos = ptbl->GetPos();          file_offset_t ullOriginalPos = ptbl->GetPos();
2268          // update headers          // update headers
2269          ptbl->SetPos(0);          ptbl->SetPos(0);
2270          uint32_t tmp = WavePoolHeaderSize;          uint32_t tmp = WavePoolHeaderSize;
# Line 1599  namespace DLS { Line 2287  namespace DLS {
2287              }              }
2288          }          }
2289          // restore 'ptbl' chunk's original read/write position          // restore 'ptbl' chunk's original read/write position
2290          ptbl->SetPos(ulOriginalPos);          ptbl->SetPos(ullOriginalPos);
2291      }      }
2292    
2293      /**      /**
# Line 1608  namespace DLS { Line 2296  namespace DLS {
2296       * exists already.       * exists already.
2297       */       */
2298      void File::__UpdateWavePoolTable() {      void File::__UpdateWavePoolTable() {
2299          WavePoolCount = (pSamples) ? pSamples->size() : 0;          WavePoolCount = (pSamples) ? uint32_t(pSamples->size()) : 0;
2300          // resize wave pool table arrays          // resize wave pool table arrays
2301          if (pWavePoolTable)   delete[] pWavePoolTable;          if (pWavePoolTable)   delete[] pWavePoolTable;
2302          if (pWavePoolTableHi) delete[] pWavePoolTableHi;          if (pWavePoolTableHi) delete[] pWavePoolTableHi;
2303          pWavePoolTable   = new uint32_t[WavePoolCount];          pWavePoolTable   = new uint32_t[WavePoolCount];
2304          pWavePoolTableHi = new uint32_t[WavePoolCount];          pWavePoolTableHi = new uint32_t[WavePoolCount];
2305          if (!pSamples) return;          if (!pSamples) return;
2306          // update offsets int wave pool table          // update offsets in wave pool table
2307          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2308          uint64_t wvplFileOffset = wvpl->GetFilePos();          uint64_t wvplFileOffset = wvpl->GetFilePos() -
2309          if (b64BitWavePoolOffsets) {                                    wvpl->GetPos(); // mandatory, since position might have changed
2310            if (!b64BitWavePoolOffsets) { // conventional 32 bit offsets (and no extension files) ...
2311              SampleList::iterator iter = pSamples->begin();              SampleList::iterator iter = pSamples->begin();
2312              SampleList::iterator end  = pSamples->end();              SampleList::iterator end  = pSamples->end();
2313              for (int i = 0 ; iter != end ; ++iter, i++) {              for (int i = 0 ; iter != end ; ++iter, i++) {
2314                  uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;                  uint64_t _64BitOffset =
2315                  (*iter)->ulWavePoolOffset = _64BitOffset;                      (*iter)->pWaveList->GetFilePos() -
2316                  pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);                      (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2317                  pWavePoolTable[i]   = (uint32_t) _64BitOffset;                      wvplFileOffset -
2318              }                      LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2319          } else { // conventional 32 bit offsets                  (*iter)->ullWavePoolOffset = _64BitOffset;
             SampleList::iterator iter = pSamples->begin();  
             SampleList::iterator end  = pSamples->end();  
             for (int i = 0 ; iter != end ; ++iter, i++) {  
                 uint64_t _64BitOffset = (*iter)->pWaveList->GetFilePos() - wvplFileOffset - LIST_HEADER_SIZE;  
                 (*iter)->ulWavePoolOffset = _64BitOffset;  
2320                  pWavePoolTable[i] = (uint32_t) _64BitOffset;                  pWavePoolTable[i] = (uint32_t) _64BitOffset;
2321              }              }
2322            } else { // a) native 64 bit offsets without extension files or b) 32 bit offsets with extension files ...
2323                if (ExtensionFiles.empty()) { // native 64 bit offsets (and no extension files) [not compatible with GigaStudio] ...
2324                    SampleList::iterator iter = pSamples->begin();
2325                    SampleList::iterator end  = pSamples->end();
2326                    for (int i = 0 ; iter != end ; ++iter, i++) {
2327                        uint64_t _64BitOffset =
2328                            (*iter)->pWaveList->GetFilePos() -
2329                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2330                            wvplFileOffset -
2331                            LIST_HEADER_SIZE(pRIFF->GetFileOffsetSize());
2332                        (*iter)->ullWavePoolOffset = _64BitOffset;
2333                        pWavePoolTableHi[i] = (uint32_t) (_64BitOffset >> 32);
2334                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2335                    }
2336                } else { // 32 bit offsets with extension files (GigaStudio legacy support) ...
2337                    // the main gig and the extension files may contain wave data
2338                    std::vector<RIFF::File*> poolFiles;
2339                    poolFiles.push_back(pRIFF);
2340                    poolFiles.insert(poolFiles.end(), ExtensionFiles.begin(), ExtensionFiles.end());
2341    
2342                    RIFF::File* pCurPoolFile = NULL;
2343                    int fileNo = 0;
2344                    int waveOffset = 0;
2345                    SampleList::iterator iter = pSamples->begin();
2346                    SampleList::iterator end  = pSamples->end();
2347                    for (int i = 0 ; iter != end ; ++iter, i++) {
2348                        RIFF::File* pPoolFile = (*iter)->pWaveList->GetFile();
2349                        // if this sample is located in the same pool file as the
2350                        // last we reuse the previously computed fileNo and waveOffset
2351                        if (pPoolFile != pCurPoolFile) { // it is a different pool file than the last sample ...
2352                            pCurPoolFile = pPoolFile;
2353    
2354                            std::vector<RIFF::File*>::iterator sIter;
2355                            sIter = std::find(poolFiles.begin(), poolFiles.end(), pPoolFile);
2356                            if (sIter != poolFiles.end())
2357                                fileNo = std::distance(poolFiles.begin(), sIter);
2358                            else
2359                                throw DLS::Exception("Fatal error, unknown pool file");
2360    
2361                            RIFF::List* extWvpl = pCurPoolFile->GetSubList(LIST_TYPE_WVPL);
2362                            if (!extWvpl)
2363                                throw DLS::Exception("Fatal error, pool file has no 'wvpl' list chunk");
2364                            waveOffset =
2365                                extWvpl->GetFilePos() -
2366                                extWvpl->GetPos() + // mandatory, since position might have changed
2367                                LIST_HEADER_SIZE(pCurPoolFile->GetFileOffsetSize());
2368                        }
2369                        uint64_t _64BitOffset =
2370                            (*iter)->pWaveList->GetFilePos() -
2371                            (*iter)->pWaveList->GetPos() - // should be zero, but just to be sure
2372                            waveOffset;
2373                        // pWavePoolTableHi stores file number when extension files are in use
2374                        pWavePoolTableHi[i] = (uint32_t) fileNo;
2375                        pWavePoolTable[i]   = (uint32_t) _64BitOffset;
2376                        (*iter)->ullWavePoolOffset = _64BitOffset;
2377                    }
2378                }
2379          }          }
2380      }      }
2381    
2382    
   
2383  // *************** Exception ***************  // *************** Exception ***************
2384  // *  // *
2385    
2386      Exception::Exception(String Message) : RIFF::Exception(Message) {      Exception::Exception() : RIFF::Exception() {
2387        }
2388    
2389        Exception::Exception(String format, ...) : RIFF::Exception() {
2390            va_list arg;
2391            va_start(arg, format);
2392            Message = assemble(format, arg);
2393            va_end(arg);
2394        }
2395    
2396        Exception::Exception(String format, va_list arg) : RIFF::Exception() {
2397            Message = assemble(format, arg);
2398      }      }
2399    
2400      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.2310  
changed lines
  Added in v.3488

  ViewVC Help
Powered by ViewVC