/[svn]/libgig/trunk/src/gig.cpp
ViewVC logotype

Diff of /libgig/trunk/src/gig.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1875 by schoenebeck, Thu Mar 26 13:32:59 2009 UTC revision 3323 by schoenebeck, Thu Jul 20 22:09:54 2017 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-2017 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 "gig.h"  #include "gig.h"
25    
26  #include "helper.h"  #include "helper.h"
27    #include "Serialization.h"
28    
29  #include <algorithm>  #include <algorithm>
30  #include <math.h>  #include <math.h>
31  #include <iostream>  #include <iostream>
32    #include <assert.h>
33    
34    /// libgig's current file format version (for extending the original Giga file
35    /// format with libgig's own custom data / custom features).
36    #define GIG_FILE_EXT_VERSION    2
37    
38  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
39  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 50  Line 56 
56  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
57  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
58    
59  namespace gig {  #define SRLZ(member) \
60        archive->serializeMember(*this, member, #member);
 // *************** progress_t ***************  
 // *  
   
     progress_t::progress_t() {  
         callback    = NULL;  
         custom      = NULL;  
         __range_min = 0.0f;  
         __range_max = 1.0f;  
     }  
   
     // private helper function to convert progress of a subprocess into the global progress  
     static void __notify_progress(progress_t* pProgress, float subprogress) {  
         if (pProgress && pProgress->callback) {  
             const float totalrange    = pProgress->__range_max - pProgress->__range_min;  
             const float totalprogress = pProgress->__range_min + subprogress * totalrange;  
             pProgress->factor         = totalprogress;  
             pProgress->callback(pProgress); // now actually notify about the progress  
         }  
     }  
   
     // private helper function to divide a progress into subprogresses  
     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {  
         if (pParentProgress && pParentProgress->callback) {  
             const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;  
             pSubProgress->callback    = pParentProgress->callback;  
             pSubProgress->custom      = pParentProgress->custom;  
             pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;  
             pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;  
         }  
     }  
61    
62    namespace gig {
63    
64  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
65  // *  // *
# Line 122  namespace { Line 99  namespace {
99      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
100                        int srcStep, int dstStep,                        int srcStep, int dstStep,
101                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
102                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
103                        unsigned long copysamples)                        file_offset_t copysamples)
104      {      {
105          switch (compressionmode) {          switch (compressionmode) {
106              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 159  namespace { Line 136  namespace {
136    
137      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
138                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
139                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
140                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
141      {      {
142          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
143    
# Line 296  namespace { Line 273  namespace {
273       * steps.       * steps.
274       *       *
275       * Once the whole data was processed by __calculateCRC(), one should       * Once the whole data was processed by __calculateCRC(), one should
276       * call __encodeCRC() to get the final CRC result.       * call __finalizeCRC() to get the final CRC result.
277       *       *
278       * @param buf     - pointer to data the CRC shall be calculated of       * @param buf     - pointer to data the CRC shall be calculated of
279       * @param bufSize - size of the data to be processed       * @param bufSize - size of the data to be processed
280       * @param crc     - variable the CRC sum shall be stored to       * @param crc     - variable the CRC sum shall be stored to
281       */       */
282      static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {      static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
283          for (int i = 0 ; i < bufSize ; i++) {          for (size_t i = 0 ; i < bufSize ; i++) {
284              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
285          }          }
286      }      }
# Line 313  namespace { Line 290  namespace {
290       *       *
291       * @param crc - variable previously passed to __calculateCRC()       * @param crc - variable previously passed to __calculateCRC()
292       */       */
293      inline static uint32_t __encodeCRC(const uint32_t& crc) {      inline static void __finalizeCRC(uint32_t& crc) {
294          return crc ^ 0xffffffff;          crc ^= 0xffffffff;
295      }      }
296    
297    
# Line 342  namespace { Line 319  namespace {
319    
320    
321    
322    // *************** leverage_ctrl_t ***************
323    // *
324    
325        void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
326            SRLZ(type);
327            SRLZ(controller_number);
328        }
329    
330    
331    
332    // *************** crossfade_t ***************
333    // *
334    
335        void crossfade_t::serialize(Serialization::Archive* archive) {
336            SRLZ(in_start);
337            SRLZ(in_end);
338            SRLZ(out_start);
339            SRLZ(out_end);
340        }
341    
342    
343    
344    // *************** eg_opt_t ***************
345    // *
346    
347        eg_opt_t::eg_opt_t() {
348            AttackCancel     = true;
349            AttackHoldCancel = true;
350            DecayCancel      = true;
351            ReleaseCancel    = true;
352        }
353    
354        void eg_opt_t::serialize(Serialization::Archive* archive) {
355            SRLZ(AttackCancel);
356            SRLZ(AttackHoldCancel);
357            SRLZ(DecayCancel);
358            SRLZ(ReleaseCancel);
359        }
360    
361    
362    
363  // *************** Sample ***************  // *************** Sample ***************
364  // *  // *
365    
366      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
367      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
368    
369      /** @brief Constructor.      /** @brief Constructor.
# Line 365  namespace { Line 383  namespace {
383       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
384       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
385       *                         is located, 0 otherwise       *                         is located, 0 otherwise
386         * @param index          - wave pool index of sample (may be -1 on new sample)
387       */       */
388      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
389            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
390        {
391          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
392              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
393              { 0, 0 }              { 0, 0 }
# Line 376  namespace { Line 397  namespace {
397          FileNo = fileNo;          FileNo = fileNo;
398    
399          __resetCRC(crc);          __resetCRC(crc);
400            // if this is not a new sample, try to get the sample's already existing
401            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
402            // checksum of the time when the sample was consciously modified by the
403            // user for the last time (by calling Sample::Write() that is).
404            if (index >= 0) { // not a new file ...
405                try {
406                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
407                    this->crc = crc;
408                } catch (...) {}
409            }
410    
411          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
412          if (pCk3gix) {          if (pCk3gix) {
# Line 454  namespace { Line 485  namespace {
485      }      }
486    
487      /**      /**
488         * Make a (semi) deep copy of the Sample object given by @a orig (without
489         * the actual waveform data) and assign it to this object.
490         *
491         * Discussion: copying .gig samples is a bit tricky. It requires three
492         * steps:
493         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
494         *    its new sample waveform data size.
495         * 2. Saving the file (done by File::Save()) so that it gains correct size
496         *    and layout for writing the actual wave form data directly to disc
497         *    in next step.
498         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
499         *
500         * @param orig - original Sample object to be copied from
501         */
502        void Sample::CopyAssignMeta(const Sample* orig) {
503            // handle base classes
504            DLS::Sample::CopyAssignCore(orig);
505            
506            // handle actual own attributes of this class
507            Manufacturer = orig->Manufacturer;
508            Product = orig->Product;
509            SamplePeriod = orig->SamplePeriod;
510            MIDIUnityNote = orig->MIDIUnityNote;
511            FineTune = orig->FineTune;
512            SMPTEFormat = orig->SMPTEFormat;
513            SMPTEOffset = orig->SMPTEOffset;
514            Loops = orig->Loops;
515            LoopID = orig->LoopID;
516            LoopType = orig->LoopType;
517            LoopStart = orig->LoopStart;
518            LoopEnd = orig->LoopEnd;
519            LoopSize = orig->LoopSize;
520            LoopFraction = orig->LoopFraction;
521            LoopPlayCount = orig->LoopPlayCount;
522            
523            // schedule resizing this sample to the given sample's size
524            Resize(orig->GetSize());
525        }
526    
527        /**
528         * Should be called after CopyAssignMeta() and File::Save() sequence.
529         * Read more about it in the discussion of CopyAssignMeta(). This method
530         * copies the actual waveform data by disk streaming.
531         *
532         * @e CAUTION: this method is currently not thread safe! During this
533         * operation the sample must not be used for other purposes by other
534         * threads!
535         *
536         * @param orig - original Sample object to be copied from
537         */
538        void Sample::CopyAssignWave(const Sample* orig) {
539            const int iReadAtOnce = 32*1024;
540            char* buf = new char[iReadAtOnce * orig->FrameSize];
541            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
542            file_offset_t restorePos = pOrig->GetPos();
543            pOrig->SetPos(0);
544            SetPos(0);
545            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
546                               n = pOrig->Read(buf, iReadAtOnce))
547            {
548                Write(buf, n);
549            }
550            pOrig->SetPos(restorePos);
551            delete [] buf;
552        }
553    
554        /**
555       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
556       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
557       *       *
558       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
559       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
560       *       *
561         * @param pProgress - callback function for progress notification
562       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
563       *                        was provided yet       *                        was provided yet
564       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
565       */       */
566      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
567          // first update base class's chunks          // first update base class's chunks
568          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
569    
570          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
571          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 514  namespace { Line 613  namespace {
613          // update '3gix' chunk          // update '3gix' chunk
614          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
615          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
616    
617            // if the library user toggled the "Compressed" attribute from true to
618            // false, then the EWAV chunk associated with compressed samples needs
619            // to be deleted
620            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
621            if (ewav && !Compressed) {
622                pWaveList->DeleteSubChunk(ewav);
623            }
624      }      }
625    
626      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
627      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
628          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
629          this->SamplesTotal = 0;          this->SamplesTotal = 0;
630          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
631    
632          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
633          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 536  namespace { Line 643  namespace {
643                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
644                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
645                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
646                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
647    
648                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
649                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 555  namespace { Line 662  namespace {
662    
663                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
664                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
665                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
666    
667                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
668                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 571  namespace { Line 678  namespace {
678    
679          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
680          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
681          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
682          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
683          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
684          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
685              FrameTable[i] = *iter;              FrameTable[i] = *iter;
686          }          }
# Line 614  namespace { Line 721  namespace {
721       *                      the cached sample data in bytes       *                      the cached sample data in bytes
722       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
723       */       */
724      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
725          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
726      }      }
727    
# Line 673  namespace { Line 780  namespace {
780       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
781       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
782       */       */
783      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
784          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
785          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
786          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
787          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
788          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
789          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 740  namespace { Line 847  namespace {
847       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
848       * other formats will fail!       * other formats will fail!
849       *       *
850       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
851       *                   greater than zero)       *                  greater than zero)
852       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
853       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
854       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
855       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
856       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
857       */       */
858      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
859          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
860          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
861      }      }
862    
863      /**      /**
# Line 774  namespace { Line 881  namespace {
881       * @returns            the new sample position       * @returns            the new sample position
882       * @see                Read()       * @see                Read()
883       */       */
884      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) {
885          if (Compressed) {          if (Compressed) {
886              switch (Whence) {              switch (Whence) {
887                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 792  namespace { Line 899  namespace {
899              }              }
900              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
901    
902              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
903              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
904              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
905              return this->SamplePos;              return this->SamplePos;
906          }          }
907          else { // not compressed          else { // not compressed
908              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
909              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
910              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
911                                              : result / this->FrameSize;                                              : result / this->FrameSize;
912          }          }
# Line 808  namespace { Line 915  namespace {
915      /**      /**
916       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
917       */       */
918      unsigned long Sample::GetPos() {      file_offset_t Sample::GetPos() const {
919          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
920          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
921      }      }
# Line 847  namespace { Line 954  namespace {
954       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
955       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
956       */       */
957      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
958                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
959          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
960          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
961    
962          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 887  namespace { Line 994  namespace {
994                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
995                                  // backward playback                                  // backward playback
996    
997                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
998                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
999                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
1000                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
1001    
1002                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
1003    
# Line 938  namespace { Line 1045  namespace {
1045                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1046                          // backward playback                          // backward playback
1047    
1048                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1049                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1050                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1051                                                                                    : samplestoread;                                                                                    : samplestoread;
1052                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1053    
1054                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1055    
# Line 1022  namespace { Line 1129  namespace {
1129       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1130       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1131       */       */
1132      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1133          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1134          if (!Compressed) {          if (!Compressed) {
1135              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1037  namespace { Line 1144  namespace {
1144          else {          else {
1145              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1146              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1147              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1148                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1149                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1150                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1060  namespace { Line 1167  namespace {
1167              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1168    
1169              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1170                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1171                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1172    
1173                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1174    
# Line 1211  namespace { Line 1318  namespace {
1318       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1319       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1320       */       */
1321      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1322          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1323    
1324          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
# Line 1220  namespace { Line 1327  namespace {
1327              __resetCRC(crc);              __resetCRC(crc);
1328          }          }
1329          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");
1330          unsigned long res;          file_offset_t res;
1331          if (BitDepth == 24) {          if (BitDepth == 24) {
1332              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1333          } else { // 16 bit          } else { // 16 bit
# Line 1232  namespace { Line 1339  namespace {
1339          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1340          // file          // file
1341          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1342                __finalizeCRC(crc);
1343              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1344              pFile->SetSampleChecksum(this, __encodeCRC(crc));              pFile->SetSampleChecksum(this, crc);
1345          }          }
1346          return res;          return res;
1347      }      }
# Line 1254  namespace { Line 1362  namespace {
1362       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1363       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1364       */       */
1365      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1366          buffer_t result;          buffer_t result;
1367          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1368                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1369          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1370          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1371          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1372          return result;          return result;
# Line 1292  namespace { Line 1400  namespace {
1400          return pGroup;          return pGroup;
1401      }      }
1402    
1403        /**
1404         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1405         * time when this sample's wave form data was modified for the last time
1406         * by calling Write(). This checksum only covers the raw wave form data,
1407         * not any meta informations like i.e. bit depth or loop points. Since
1408         * this method just returns the checksum stored for this sample i.e. when
1409         * the gig file was loaded, this method returns immediately. So it does no
1410         * recalcuation of the checksum with the currently available sample wave
1411         * form data.
1412         *
1413         * @see VerifyWaveData()
1414         */
1415        uint32_t Sample::GetWaveDataCRC32Checksum() {
1416            return crc;
1417        }
1418    
1419        /**
1420         * Checks the integrity of this sample's raw audio wave data. Whenever a
1421         * Sample's raw wave data is intentionally modified (i.e. by calling
1422         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1423         * is calculated and stored/updated for this sample, along to the sample's
1424         * meta informations.
1425         *
1426         * Now by calling this method the current raw audio wave data is checked
1427         * against the already stored CRC32 check sum in order to check whether the
1428         * sample data had been damaged unintentionally for some reason. Since by
1429         * calling this method always the entire raw audio wave data has to be
1430         * read, verifying all samples this way may take a long time accordingly.
1431         * And that's also the reason why the sample integrity is not checked by
1432         * default whenever a gig file is loaded. So this method must be called
1433         * explicitly to fulfill this task.
1434         *
1435         * @param pActually - (optional) if provided, will be set to the actually
1436         *                    calculated checksum of the current raw wave form data,
1437         *                    you can get the expected checksum instead by calling
1438         *                    GetWaveDataCRC32Checksum()
1439         * @returns true if sample is OK or false if the sample is damaged
1440         * @throws Exception if no checksum had been stored to disk for this
1441         *         sample yet, or on I/O issues
1442         * @see GetWaveDataCRC32Checksum()
1443         */
1444        bool Sample::VerifyWaveData(uint32_t* pActually) {
1445            //File* pFile = static_cast<File*>(GetParent());
1446            uint32_t crc = CalculateWaveDataChecksum();
1447            if (pActually) *pActually = crc;
1448            return crc == this->crc;
1449        }
1450    
1451        uint32_t Sample::CalculateWaveDataChecksum() {
1452            const size_t sz = 20*1024; // 20kB buffer size
1453            std::vector<uint8_t> buffer(sz);
1454            buffer.resize(sz);
1455    
1456            const size_t n = sz / FrameSize;
1457            SetPos(0);
1458            uint32_t crc = 0;
1459            __resetCRC(crc);
1460            while (true) {
1461                file_offset_t nRead = Read(&buffer[0], n);
1462                if (nRead <= 0) break;
1463                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1464            }
1465            __finalizeCRC(crc);
1466            return crc;
1467        }
1468    
1469      Sample::~Sample() {      Sample::~Sample() {
1470          Instances--;          Instances--;
1471          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1308  namespace { Line 1482  namespace {
1482  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1483  // *  // *
1484    
1485      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1486      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1487    
1488      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1433  namespace { Line 1607  namespace {
1607                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1608              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1609              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1610                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1611              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1612              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1613              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1502  namespace { Line 1676  namespace {
1676              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1677              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1678              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1679              EG2Release                      = 0.3;              EG2Release                      = 60;
1680              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1681              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1682              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1556  namespace { Line 1730  namespace {
1730              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1731              memset(DimensionUpperLimits, 127, 8);              memset(DimensionUpperLimits, 127, 8);
1732          }          }
1733            // format extension for EG behavior options, these will *NOT* work with
1734            // Gigasampler/GigaStudio !
1735            RIFF::Chunk* lsde = _3ewl->GetSubChunk(CHUNK_ID_LSDE);
1736            if (lsde) {
1737                unsigned char byte = lsde->ReadUint8();
1738                EGOptions.AttackCancel     = byte & 1;
1739                EGOptions.AttackHoldCancel = byte & (1 << 1);
1740                EGOptions.DecayCancel      = byte & (1 << 2);
1741                EGOptions.ReleaseCancel    = byte & (1 << 3);
1742            }
1743    
1744          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1745                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
# Line 1581  namespace { Line 1765  namespace {
1765       */       */
1766      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1767          Instances++;          Instances++;
1768            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1769          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1770          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1771    
# Line 1596  namespace { Line 1781  namespace {
1781                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1782          }          }
1783      }      }
1784        
1785        /**
1786         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1787         * and assign it to this object.
1788         *
1789         * Note that all sample pointers referenced by @a orig are simply copied as
1790         * memory address. Thus the respective samples are shared, not duplicated!
1791         *
1792         * @param orig - original DimensionRegion object to be copied from
1793         */
1794        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1795            CopyAssign(orig, NULL);
1796        }
1797    
1798        /**
1799         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1800         * and assign it to this object.
1801         *
1802         * @param orig - original DimensionRegion object to be copied from
1803         * @param mSamples - crosslink map between the foreign file's samples and
1804         *                   this file's samples
1805         */
1806        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1807            // delete all allocated data first
1808            if (VelocityTable) delete [] VelocityTable;
1809            if (pSampleLoops) delete [] pSampleLoops;
1810            
1811            // backup parent list pointer
1812            RIFF::List* p = pParentList;
1813            
1814            gig::Sample* pOriginalSample = pSample;
1815            gig::Region* pOriginalRegion = pRegion;
1816            
1817            //NOTE: copy code copied from assignment constructor above, see comment there as well
1818            
1819            *this = *orig; // default memberwise shallow copy of all parameters
1820            
1821            // restore members that shall not be altered
1822            pParentList = p; // restore the chunk pointer
1823            pRegion = pOriginalRegion;
1824            
1825            // only take the raw sample reference reference if the
1826            // two DimensionRegion objects are part of the same file
1827            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1828                pSample = pOriginalSample;
1829            }
1830            
1831            if (mSamples && mSamples->count(orig->pSample)) {
1832                pSample = mSamples->find(orig->pSample)->second;
1833            }
1834    
1835            // deep copy of owned structures
1836            if (orig->VelocityTable) {
1837                VelocityTable = new uint8_t[128];
1838                for (int k = 0 ; k < 128 ; k++)
1839                    VelocityTable[k] = orig->VelocityTable[k];
1840            }
1841            if (orig->pSampleLoops) {
1842                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1843                for (int k = 0 ; k < orig->SampleLoops ; k++)
1844                    pSampleLoops[k] = orig->pSampleLoops[k];
1845            }
1846        }
1847    
1848        void DimensionRegion::serialize(Serialization::Archive* archive) {
1849            // in case this class will become backward incompatible one day,
1850            // then set a version and minimum version for this class like:
1851            //archive->setVersion(*this, 2);
1852            //archive->setMinVersion(*this, 1);
1853    
1854            SRLZ(VelocityUpperLimit);
1855            SRLZ(EG1PreAttack);
1856            SRLZ(EG1Attack);
1857            SRLZ(EG1Decay1);
1858            SRLZ(EG1Decay2);
1859            SRLZ(EG1InfiniteSustain);
1860            SRLZ(EG1Sustain);
1861            SRLZ(EG1Release);
1862            SRLZ(EG1Hold);
1863            SRLZ(EG1Controller);
1864            SRLZ(EG1ControllerInvert);
1865            SRLZ(EG1ControllerAttackInfluence);
1866            SRLZ(EG1ControllerDecayInfluence);
1867            SRLZ(EG1ControllerReleaseInfluence);
1868            SRLZ(LFO1Frequency);
1869            SRLZ(LFO1InternalDepth);
1870            SRLZ(LFO1ControlDepth);
1871            SRLZ(LFO1Controller);
1872            SRLZ(LFO1FlipPhase);
1873            SRLZ(LFO1Sync);
1874            SRLZ(EG2PreAttack);
1875            SRLZ(EG2Attack);
1876            SRLZ(EG2Decay1);
1877            SRLZ(EG2Decay2);
1878            SRLZ(EG2InfiniteSustain);
1879            SRLZ(EG2Sustain);
1880            SRLZ(EG2Release);
1881            SRLZ(EG2Controller);
1882            SRLZ(EG2ControllerInvert);
1883            SRLZ(EG2ControllerAttackInfluence);
1884            SRLZ(EG2ControllerDecayInfluence);
1885            SRLZ(EG2ControllerReleaseInfluence);
1886            SRLZ(LFO2Frequency);
1887            SRLZ(LFO2InternalDepth);
1888            SRLZ(LFO2ControlDepth);
1889            SRLZ(LFO2Controller);
1890            SRLZ(LFO2FlipPhase);
1891            SRLZ(LFO2Sync);
1892            SRLZ(EG3Attack);
1893            SRLZ(EG3Depth);
1894            SRLZ(LFO3Frequency);
1895            SRLZ(LFO3InternalDepth);
1896            SRLZ(LFO3ControlDepth);
1897            SRLZ(LFO3Controller);
1898            SRLZ(LFO3Sync);
1899            SRLZ(VCFEnabled);
1900            SRLZ(VCFType);
1901            SRLZ(VCFCutoffController);
1902            SRLZ(VCFCutoffControllerInvert);
1903            SRLZ(VCFCutoff);
1904            SRLZ(VCFVelocityCurve);
1905            SRLZ(VCFVelocityScale);
1906            SRLZ(VCFVelocityDynamicRange);
1907            SRLZ(VCFResonance);
1908            SRLZ(VCFResonanceDynamic);
1909            SRLZ(VCFResonanceController);
1910            SRLZ(VCFKeyboardTracking);
1911            SRLZ(VCFKeyboardTrackingBreakpoint);
1912            SRLZ(VelocityResponseCurve);
1913            SRLZ(VelocityResponseDepth);
1914            SRLZ(VelocityResponseCurveScaling);
1915            SRLZ(ReleaseVelocityResponseCurve);
1916            SRLZ(ReleaseVelocityResponseDepth);
1917            SRLZ(ReleaseTriggerDecay);
1918            SRLZ(Crossfade);
1919            SRLZ(PitchTrack);
1920            SRLZ(DimensionBypass);
1921            SRLZ(Pan);
1922            SRLZ(SelfMask);
1923            SRLZ(AttenuationController);
1924            SRLZ(InvertAttenuationController);
1925            SRLZ(AttenuationControllerThreshold);
1926            SRLZ(ChannelOffset);
1927            SRLZ(SustainDefeat);
1928            SRLZ(MSDecode);
1929            //SRLZ(SampleStartOffset);
1930            SRLZ(SampleAttenuation);
1931            SRLZ(EGOptions);
1932    
1933            // derived attributes from DLS::Sampler
1934            SRLZ(FineTune);
1935            SRLZ(Gain);
1936        }
1937    
1938      /**      /**
1939       * Updates the respective member variable and updates @c SampleAttenuation       * Updates the respective member variable and updates @c SampleAttenuation
# Line 1612  namespace { Line 1950  namespace {
1950       *       *
1951       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1952       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1953         *
1954         * @param pProgress - callback function for progress notification
1955       */       */
1956      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1957          // first update base class's chunk          // first update base class's chunk
1958          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1959    
1960          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1961          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 1635  namespace { Line 1975  namespace {
1975    
1976          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1977    
1978          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1979          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1980    
1981          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 1837  namespace { Line 2177  namespace {
2177          }          }
2178    
2179          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2180                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2181          store16(&pData[116], eg3depth);          store16(&pData[116], eg3depth);
2182    
2183          // next 2 bytes unknown          // next 2 bytes unknown
# Line 1885  namespace { Line 2225  namespace {
2225                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2226          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2227    
2228          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2229                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2230          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2231    
# Line 1895  namespace { Line 2235  namespace {
2235          if (chunksize >= 148) {          if (chunksize >= 148) {
2236              memcpy(&pData[140], DimensionUpperLimits, 8);              memcpy(&pData[140], DimensionUpperLimits, 8);
2237          }          }
2238    
2239            // format extension for EG behavior options, these will *NOT* work with
2240            // Gigasampler/GigaStudio !
2241            RIFF::Chunk* lsde = pParentList->GetSubChunk(CHUNK_ID_LSDE);
2242            if (!lsde) {
2243                // only add this "LSDE" chunk if the EG options do not match the
2244                // default EG behavior
2245                eg_opt_t defaultOpt;
2246                if (memcmp(&EGOptions, &defaultOpt, sizeof(eg_opt_t))) {
2247                    lsde = pParentList->AddSubChunk(CHUNK_ID_LSDE, 1);
2248                    // move LSDE chunk to the end of parent list
2249                    pParentList->MoveSubChunk(lsde, (RIFF::Chunk*)NULL);
2250                }
2251            }
2252            if (lsde) {
2253                unsigned char* pByte = (unsigned char*) lsde->LoadChunkData();
2254                *pByte =
2255                    (EGOptions.AttackCancel     ? 1 : 0) |
2256                    (EGOptions.AttackHoldCancel ? (1<<1) : 0) |
2257                    (EGOptions.DecayCancel      ? (1<<2) : 0) |
2258                    (EGOptions.ReleaseCancel    ? (1<<3) : 0);
2259            }
2260      }      }
2261    
2262      double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {      double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
# Line 1950  namespace { Line 2312  namespace {
2312          return pRegion;          return pRegion;
2313      }      }
2314    
2315    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2316    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2317    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2318    //#pragma GCC diagnostic push
2319    //#pragma GCC diagnostic error "-Wswitch"
2320    
2321      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2322          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2323          switch (EncodedController) {          switch (EncodedController) {
# Line 2061  namespace { Line 2429  namespace {
2429                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2430                  break;                  break;
2431    
2432                // format extension (these controllers are so far only supported by
2433                // LinuxSampler & gigedit) they will *NOT* work with
2434                // Gigasampler/GigaStudio !
2435                case _lev_ctrl_CC3_EXT:
2436                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2437                    decodedcontroller.controller_number = 3;
2438                    break;
2439                case _lev_ctrl_CC6_EXT:
2440                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2441                    decodedcontroller.controller_number = 6;
2442                    break;
2443                case _lev_ctrl_CC7_EXT:
2444                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2445                    decodedcontroller.controller_number = 7;
2446                    break;
2447                case _lev_ctrl_CC8_EXT:
2448                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2449                    decodedcontroller.controller_number = 8;
2450                    break;
2451                case _lev_ctrl_CC9_EXT:
2452                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2453                    decodedcontroller.controller_number = 9;
2454                    break;
2455                case _lev_ctrl_CC10_EXT:
2456                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2457                    decodedcontroller.controller_number = 10;
2458                    break;
2459                case _lev_ctrl_CC11_EXT:
2460                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2461                    decodedcontroller.controller_number = 11;
2462                    break;
2463                case _lev_ctrl_CC14_EXT:
2464                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2465                    decodedcontroller.controller_number = 14;
2466                    break;
2467                case _lev_ctrl_CC15_EXT:
2468                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2469                    decodedcontroller.controller_number = 15;
2470                    break;
2471                case _lev_ctrl_CC20_EXT:
2472                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2473                    decodedcontroller.controller_number = 20;
2474                    break;
2475                case _lev_ctrl_CC21_EXT:
2476                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2477                    decodedcontroller.controller_number = 21;
2478                    break;
2479                case _lev_ctrl_CC22_EXT:
2480                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2481                    decodedcontroller.controller_number = 22;
2482                    break;
2483                case _lev_ctrl_CC23_EXT:
2484                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2485                    decodedcontroller.controller_number = 23;
2486                    break;
2487                case _lev_ctrl_CC24_EXT:
2488                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2489                    decodedcontroller.controller_number = 24;
2490                    break;
2491                case _lev_ctrl_CC25_EXT:
2492                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2493                    decodedcontroller.controller_number = 25;
2494                    break;
2495                case _lev_ctrl_CC26_EXT:
2496                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2497                    decodedcontroller.controller_number = 26;
2498                    break;
2499                case _lev_ctrl_CC27_EXT:
2500                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2501                    decodedcontroller.controller_number = 27;
2502                    break;
2503                case _lev_ctrl_CC28_EXT:
2504                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2505                    decodedcontroller.controller_number = 28;
2506                    break;
2507                case _lev_ctrl_CC29_EXT:
2508                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2509                    decodedcontroller.controller_number = 29;
2510                    break;
2511                case _lev_ctrl_CC30_EXT:
2512                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2513                    decodedcontroller.controller_number = 30;
2514                    break;
2515                case _lev_ctrl_CC31_EXT:
2516                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2517                    decodedcontroller.controller_number = 31;
2518                    break;
2519                case _lev_ctrl_CC68_EXT:
2520                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2521                    decodedcontroller.controller_number = 68;
2522                    break;
2523                case _lev_ctrl_CC69_EXT:
2524                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2525                    decodedcontroller.controller_number = 69;
2526                    break;
2527                case _lev_ctrl_CC70_EXT:
2528                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2529                    decodedcontroller.controller_number = 70;
2530                    break;
2531                case _lev_ctrl_CC71_EXT:
2532                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2533                    decodedcontroller.controller_number = 71;
2534                    break;
2535                case _lev_ctrl_CC72_EXT:
2536                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2537                    decodedcontroller.controller_number = 72;
2538                    break;
2539                case _lev_ctrl_CC73_EXT:
2540                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2541                    decodedcontroller.controller_number = 73;
2542                    break;
2543                case _lev_ctrl_CC74_EXT:
2544                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2545                    decodedcontroller.controller_number = 74;
2546                    break;
2547                case _lev_ctrl_CC75_EXT:
2548                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2549                    decodedcontroller.controller_number = 75;
2550                    break;
2551                case _lev_ctrl_CC76_EXT:
2552                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2553                    decodedcontroller.controller_number = 76;
2554                    break;
2555                case _lev_ctrl_CC77_EXT:
2556                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2557                    decodedcontroller.controller_number = 77;
2558                    break;
2559                case _lev_ctrl_CC78_EXT:
2560                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2561                    decodedcontroller.controller_number = 78;
2562                    break;
2563                case _lev_ctrl_CC79_EXT:
2564                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2565                    decodedcontroller.controller_number = 79;
2566                    break;
2567                case _lev_ctrl_CC84_EXT:
2568                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2569                    decodedcontroller.controller_number = 84;
2570                    break;
2571                case _lev_ctrl_CC85_EXT:
2572                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2573                    decodedcontroller.controller_number = 85;
2574                    break;
2575                case _lev_ctrl_CC86_EXT:
2576                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2577                    decodedcontroller.controller_number = 86;
2578                    break;
2579                case _lev_ctrl_CC87_EXT:
2580                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2581                    decodedcontroller.controller_number = 87;
2582                    break;
2583                case _lev_ctrl_CC89_EXT:
2584                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2585                    decodedcontroller.controller_number = 89;
2586                    break;
2587                case _lev_ctrl_CC90_EXT:
2588                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2589                    decodedcontroller.controller_number = 90;
2590                    break;
2591                case _lev_ctrl_CC96_EXT:
2592                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2593                    decodedcontroller.controller_number = 96;
2594                    break;
2595                case _lev_ctrl_CC97_EXT:
2596                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2597                    decodedcontroller.controller_number = 97;
2598                    break;
2599                case _lev_ctrl_CC102_EXT:
2600                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2601                    decodedcontroller.controller_number = 102;
2602                    break;
2603                case _lev_ctrl_CC103_EXT:
2604                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2605                    decodedcontroller.controller_number = 103;
2606                    break;
2607                case _lev_ctrl_CC104_EXT:
2608                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2609                    decodedcontroller.controller_number = 104;
2610                    break;
2611                case _lev_ctrl_CC105_EXT:
2612                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2613                    decodedcontroller.controller_number = 105;
2614                    break;
2615                case _lev_ctrl_CC106_EXT:
2616                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2617                    decodedcontroller.controller_number = 106;
2618                    break;
2619                case _lev_ctrl_CC107_EXT:
2620                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2621                    decodedcontroller.controller_number = 107;
2622                    break;
2623                case _lev_ctrl_CC108_EXT:
2624                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2625                    decodedcontroller.controller_number = 108;
2626                    break;
2627                case _lev_ctrl_CC109_EXT:
2628                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2629                    decodedcontroller.controller_number = 109;
2630                    break;
2631                case _lev_ctrl_CC110_EXT:
2632                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2633                    decodedcontroller.controller_number = 110;
2634                    break;
2635                case _lev_ctrl_CC111_EXT:
2636                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2637                    decodedcontroller.controller_number = 111;
2638                    break;
2639                case _lev_ctrl_CC112_EXT:
2640                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2641                    decodedcontroller.controller_number = 112;
2642                    break;
2643                case _lev_ctrl_CC113_EXT:
2644                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2645                    decodedcontroller.controller_number = 113;
2646                    break;
2647                case _lev_ctrl_CC114_EXT:
2648                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2649                    decodedcontroller.controller_number = 114;
2650                    break;
2651                case _lev_ctrl_CC115_EXT:
2652                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2653                    decodedcontroller.controller_number = 115;
2654                    break;
2655                case _lev_ctrl_CC116_EXT:
2656                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2657                    decodedcontroller.controller_number = 116;
2658                    break;
2659                case _lev_ctrl_CC117_EXT:
2660                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2661                    decodedcontroller.controller_number = 117;
2662                    break;
2663                case _lev_ctrl_CC118_EXT:
2664                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2665                    decodedcontroller.controller_number = 118;
2666                    break;
2667                case _lev_ctrl_CC119_EXT:
2668                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2669                    decodedcontroller.controller_number = 119;
2670                    break;
2671    
2672              // unknown controller type              // unknown controller type
2673              default:              default:
2674                  throw gig::Exception("Unknown leverage controller type.");                  decodedcontroller.type = leverage_ctrl_t::type_none;
2675                    decodedcontroller.controller_number = 0;
2676                    printf("Warning: Unknown leverage controller type (0x%x).\n", EncodedController);
2677                    break;
2678          }          }
2679          return decodedcontroller;          return decodedcontroller;
2680      }      }
2681        
2682    // see above (diagnostic push not supported prior GCC 4.6)
2683    //#pragma GCC diagnostic pop
2684    
2685      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2686          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2154  namespace { Line 2768  namespace {
2768                      case 95:                      case 95:
2769                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2770                          break;                          break;
2771    
2772                        // format extension (these controllers are so far only
2773                        // supported by LinuxSampler & gigedit) they will *NOT*
2774                        // work with Gigasampler/GigaStudio !
2775                        case 3:
2776                            encodedcontroller = _lev_ctrl_CC3_EXT;
2777                            break;
2778                        case 6:
2779                            encodedcontroller = _lev_ctrl_CC6_EXT;
2780                            break;
2781                        case 7:
2782                            encodedcontroller = _lev_ctrl_CC7_EXT;
2783                            break;
2784                        case 8:
2785                            encodedcontroller = _lev_ctrl_CC8_EXT;
2786                            break;
2787                        case 9:
2788                            encodedcontroller = _lev_ctrl_CC9_EXT;
2789                            break;
2790                        case 10:
2791                            encodedcontroller = _lev_ctrl_CC10_EXT;
2792                            break;
2793                        case 11:
2794                            encodedcontroller = _lev_ctrl_CC11_EXT;
2795                            break;
2796                        case 14:
2797                            encodedcontroller = _lev_ctrl_CC14_EXT;
2798                            break;
2799                        case 15:
2800                            encodedcontroller = _lev_ctrl_CC15_EXT;
2801                            break;
2802                        case 20:
2803                            encodedcontroller = _lev_ctrl_CC20_EXT;
2804                            break;
2805                        case 21:
2806                            encodedcontroller = _lev_ctrl_CC21_EXT;
2807                            break;
2808                        case 22:
2809                            encodedcontroller = _lev_ctrl_CC22_EXT;
2810                            break;
2811                        case 23:
2812                            encodedcontroller = _lev_ctrl_CC23_EXT;
2813                            break;
2814                        case 24:
2815                            encodedcontroller = _lev_ctrl_CC24_EXT;
2816                            break;
2817                        case 25:
2818                            encodedcontroller = _lev_ctrl_CC25_EXT;
2819                            break;
2820                        case 26:
2821                            encodedcontroller = _lev_ctrl_CC26_EXT;
2822                            break;
2823                        case 27:
2824                            encodedcontroller = _lev_ctrl_CC27_EXT;
2825                            break;
2826                        case 28:
2827                            encodedcontroller = _lev_ctrl_CC28_EXT;
2828                            break;
2829                        case 29:
2830                            encodedcontroller = _lev_ctrl_CC29_EXT;
2831                            break;
2832                        case 30:
2833                            encodedcontroller = _lev_ctrl_CC30_EXT;
2834                            break;
2835                        case 31:
2836                            encodedcontroller = _lev_ctrl_CC31_EXT;
2837                            break;
2838                        case 68:
2839                            encodedcontroller = _lev_ctrl_CC68_EXT;
2840                            break;
2841                        case 69:
2842                            encodedcontroller = _lev_ctrl_CC69_EXT;
2843                            break;
2844                        case 70:
2845                            encodedcontroller = _lev_ctrl_CC70_EXT;
2846                            break;
2847                        case 71:
2848                            encodedcontroller = _lev_ctrl_CC71_EXT;
2849                            break;
2850                        case 72:
2851                            encodedcontroller = _lev_ctrl_CC72_EXT;
2852                            break;
2853                        case 73:
2854                            encodedcontroller = _lev_ctrl_CC73_EXT;
2855                            break;
2856                        case 74:
2857                            encodedcontroller = _lev_ctrl_CC74_EXT;
2858                            break;
2859                        case 75:
2860                            encodedcontroller = _lev_ctrl_CC75_EXT;
2861                            break;
2862                        case 76:
2863                            encodedcontroller = _lev_ctrl_CC76_EXT;
2864                            break;
2865                        case 77:
2866                            encodedcontroller = _lev_ctrl_CC77_EXT;
2867                            break;
2868                        case 78:
2869                            encodedcontroller = _lev_ctrl_CC78_EXT;
2870                            break;
2871                        case 79:
2872                            encodedcontroller = _lev_ctrl_CC79_EXT;
2873                            break;
2874                        case 84:
2875                            encodedcontroller = _lev_ctrl_CC84_EXT;
2876                            break;
2877                        case 85:
2878                            encodedcontroller = _lev_ctrl_CC85_EXT;
2879                            break;
2880                        case 86:
2881                            encodedcontroller = _lev_ctrl_CC86_EXT;
2882                            break;
2883                        case 87:
2884                            encodedcontroller = _lev_ctrl_CC87_EXT;
2885                            break;
2886                        case 89:
2887                            encodedcontroller = _lev_ctrl_CC89_EXT;
2888                            break;
2889                        case 90:
2890                            encodedcontroller = _lev_ctrl_CC90_EXT;
2891                            break;
2892                        case 96:
2893                            encodedcontroller = _lev_ctrl_CC96_EXT;
2894                            break;
2895                        case 97:
2896                            encodedcontroller = _lev_ctrl_CC97_EXT;
2897                            break;
2898                        case 102:
2899                            encodedcontroller = _lev_ctrl_CC102_EXT;
2900                            break;
2901                        case 103:
2902                            encodedcontroller = _lev_ctrl_CC103_EXT;
2903                            break;
2904                        case 104:
2905                            encodedcontroller = _lev_ctrl_CC104_EXT;
2906                            break;
2907                        case 105:
2908                            encodedcontroller = _lev_ctrl_CC105_EXT;
2909                            break;
2910                        case 106:
2911                            encodedcontroller = _lev_ctrl_CC106_EXT;
2912                            break;
2913                        case 107:
2914                            encodedcontroller = _lev_ctrl_CC107_EXT;
2915                            break;
2916                        case 108:
2917                            encodedcontroller = _lev_ctrl_CC108_EXT;
2918                            break;
2919                        case 109:
2920                            encodedcontroller = _lev_ctrl_CC109_EXT;
2921                            break;
2922                        case 110:
2923                            encodedcontroller = _lev_ctrl_CC110_EXT;
2924                            break;
2925                        case 111:
2926                            encodedcontroller = _lev_ctrl_CC111_EXT;
2927                            break;
2928                        case 112:
2929                            encodedcontroller = _lev_ctrl_CC112_EXT;
2930                            break;
2931                        case 113:
2932                            encodedcontroller = _lev_ctrl_CC113_EXT;
2933                            break;
2934                        case 114:
2935                            encodedcontroller = _lev_ctrl_CC114_EXT;
2936                            break;
2937                        case 115:
2938                            encodedcontroller = _lev_ctrl_CC115_EXT;
2939                            break;
2940                        case 116:
2941                            encodedcontroller = _lev_ctrl_CC116_EXT;
2942                            break;
2943                        case 117:
2944                            encodedcontroller = _lev_ctrl_CC117_EXT;
2945                            break;
2946                        case 118:
2947                            encodedcontroller = _lev_ctrl_CC118_EXT;
2948                            break;
2949                        case 119:
2950                            encodedcontroller = _lev_ctrl_CC119_EXT;
2951                            break;
2952    
2953                      default:                      default:
2954                          throw gig::Exception("leverage controller number is not supported by the gig format");                          throw gig::Exception("leverage controller number is not supported by the gig format");
2955                  }                  }
# Line 2455  namespace { Line 3251  namespace {
3251       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3252       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3253       *       *
3254         * @param pProgress - callback function for progress notification
3255       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3256       */       */
3257      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3258          // in the gig format we don't care about the Region's sample reference          // in the gig format we don't care about the Region's sample reference
3259          // but we still have to provide some existing one to not corrupt the          // but we still have to provide some existing one to not corrupt the
3260          // file, so to avoid the latter we simply always assign the sample of          // file, so to avoid the latter we simply always assign the sample of
# Line 2465  namespace { Line 3262  namespace {
3262          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3263    
3264          // first update base class's chunks          // first update base class's chunks
3265          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3266    
3267          // update dimension region's chunks          // update dimension region's chunks
3268          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3269              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3270          }          }
3271    
3272          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 2485  namespace { Line 3282  namespace {
3282              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3283    
3284              // move 3prg to last position              // move 3prg to last position
3285              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3286          }          }
3287    
3288          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2559  namespace { Line 3356  namespace {
3356          int step = 1;          int step = 1;
3357          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3358          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3359    
3360          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3361          int dim[8] = { 0 };          int dim[8] = { 0 };
3362          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3363                const int end = i + step * pDimensionDefinitions[veldim].zones;
3364    
3365                // create a velocity table for all cases where the velocity zone is zero
3366              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3367                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3368                  // create the velocity table                  // create the velocity table
# Line 2595  namespace { Line 3393  namespace {
3393                  }                  }
3394              }              }
3395    
3396                // jump to the next case where the velocity zone is zero
3397              int j;              int j;
3398              int shift = 0;              int shift = 0;
3399              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 2631  namespace { Line 3430  namespace {
3430       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3431       */       */
3432      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3433            // some initial sanity checks of the given dimension definition
3434            if (pDimDef->zones < 2)
3435                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3436            if (pDimDef->bits < 1)
3437                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3438            if (pDimDef->dimension == dimension_samplechannel) {
3439                if (pDimDef->zones != 2)
3440                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3441                if (pDimDef->bits != 1)
3442                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3443            }
3444    
3445          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3446          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3447          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2806  namespace { Line 3617  namespace {
3617          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3618      }      }
3619    
3620        /** @brief Delete one split zone of a dimension (decrement zone amount).
3621         *
3622         * Instead of deleting an entire dimensions, this method will only delete
3623         * one particular split zone given by @a zone of the Region's dimension
3624         * given by @a type. So this method will simply decrement the amount of
3625         * zones by one of the dimension in question. To be able to do that, the
3626         * respective dimension must exist on this Region and it must have at least
3627         * 3 zones. All DimensionRegion objects associated with the zone will be
3628         * deleted.
3629         *
3630         * @param type - identifies the dimension where a zone shall be deleted
3631         * @param zone - index of the dimension split zone that shall be deleted
3632         * @throws gig::Exception if requested zone could not be deleted
3633         */
3634        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3635            dimension_def_t* oldDef = GetDimensionDefinition(type);
3636            if (!oldDef)
3637                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3638            if (oldDef->zones <= 2)
3639                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3640            if (zone < 0 || zone >= oldDef->zones)
3641                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3642    
3643            const int newZoneSize = oldDef->zones - 1;
3644    
3645            // create a temporary Region which just acts as a temporary copy
3646            // container and will be deleted at the end of this function and will
3647            // also not be visible through the API during this process
3648            gig::Region* tempRgn = NULL;
3649            {
3650                // adding these temporary chunks is probably not even necessary
3651                Instrument* instr = static_cast<Instrument*>(GetParent());
3652                RIFF::List* pCkInstrument = instr->pCkInstrument;
3653                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3654                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3655                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3656                tempRgn = new Region(instr, rgn);
3657            }
3658    
3659            // copy this region's dimensions (with already the dimension split size
3660            // requested by the arguments of this method call) to the temporary
3661            // region, and don't use Region::CopyAssign() here for this task, since
3662            // it would also alter fast lookup helper variables here and there
3663            dimension_def_t newDef;
3664            for (int i = 0; i < Dimensions; ++i) {
3665                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3666                // is this the dimension requested by the method arguments? ...
3667                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3668                    def.zones = newZoneSize;
3669                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3670                    newDef = def;
3671                }
3672                tempRgn->AddDimension(&def);
3673            }
3674    
3675            // find the dimension index in the tempRegion which is the dimension
3676            // type passed to this method (paranoidly expecting different order)
3677            int tempReducedDimensionIndex = -1;
3678            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3679                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3680                    tempReducedDimensionIndex = d;
3681                    break;
3682                }
3683            }
3684    
3685            // copy dimension regions from this region to the temporary region
3686            for (int iDst = 0; iDst < 256; ++iDst) {
3687                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3688                if (!dstDimRgn) continue;
3689                std::map<dimension_t,int> dimCase;
3690                bool isValidZone = true;
3691                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3692                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3693                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3694                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3695                    baseBits += dstBits;
3696                    // there are also DimensionRegion objects of unused zones, skip them
3697                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3698                        isValidZone = false;
3699                        break;
3700                    }
3701                }
3702                if (!isValidZone) continue;
3703                // a bit paranoid: cope with the chance that the dimensions would
3704                // have different order in source and destination regions
3705                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3706                if (dimCase[type] >= zone) dimCase[type]++;
3707                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3708                dstDimRgn->CopyAssign(srcDimRgn);
3709                // if this is the upper most zone of the dimension passed to this
3710                // method, then correct (raise) its upper limit to 127
3711                if (newDef.split_type == split_type_normal && isLastZone)
3712                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3713            }
3714    
3715            // now tempRegion's dimensions and DimensionRegions basically reflect
3716            // what we wanted to get for this actual Region here, so we now just
3717            // delete and recreate the dimension in question with the new amount
3718            // zones and then copy back from tempRegion      
3719            DeleteDimension(oldDef);
3720            AddDimension(&newDef);
3721            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3722                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3723                if (!srcDimRgn) continue;
3724                std::map<dimension_t,int> dimCase;
3725                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3726                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3727                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3728                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3729                    baseBits += srcBits;
3730                }
3731                // a bit paranoid: cope with the chance that the dimensions would
3732                // have different order in source and destination regions
3733                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3734                if (!dstDimRgn) continue;
3735                dstDimRgn->CopyAssign(srcDimRgn);
3736            }
3737    
3738            // delete temporary region
3739            delete tempRgn;
3740    
3741            UpdateVelocityTable();
3742        }
3743    
3744        /** @brief Divide split zone of a dimension in two (increment zone amount).
3745         *
3746         * This will increment the amount of zones for the dimension (given by
3747         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3748         * in the middle of its zone range in two. So the two zones resulting from
3749         * the zone being splitted, will be an equivalent copy regarding all their
3750         * articulation informations and sample reference. The two zones will only
3751         * differ in their zone's upper limit
3752         * (DimensionRegion::DimensionUpperLimits).
3753         *
3754         * @param type - identifies the dimension where a zone shall be splitted
3755         * @param zone - index of the dimension split zone that shall be splitted
3756         * @throws gig::Exception if requested zone could not be splitted
3757         */
3758        void Region::SplitDimensionZone(dimension_t type, int zone) {
3759            dimension_def_t* oldDef = GetDimensionDefinition(type);
3760            if (!oldDef)
3761                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3762            if (zone < 0 || zone >= oldDef->zones)
3763                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3764    
3765            const int newZoneSize = oldDef->zones + 1;
3766    
3767            // create a temporary Region which just acts as a temporary copy
3768            // container and will be deleted at the end of this function and will
3769            // also not be visible through the API during this process
3770            gig::Region* tempRgn = NULL;
3771            {
3772                // adding these temporary chunks is probably not even necessary
3773                Instrument* instr = static_cast<Instrument*>(GetParent());
3774                RIFF::List* pCkInstrument = instr->pCkInstrument;
3775                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3776                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3777                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3778                tempRgn = new Region(instr, rgn);
3779            }
3780    
3781            // copy this region's dimensions (with already the dimension split size
3782            // requested by the arguments of this method call) to the temporary
3783            // region, and don't use Region::CopyAssign() here for this task, since
3784            // it would also alter fast lookup helper variables here and there
3785            dimension_def_t newDef;
3786            for (int i = 0; i < Dimensions; ++i) {
3787                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3788                // is this the dimension requested by the method arguments? ...
3789                if (def.dimension == type) { // ... if yes, increment zone amount by one
3790                    def.zones = newZoneSize;
3791                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3792                    newDef = def;
3793                }
3794                tempRgn->AddDimension(&def);
3795            }
3796    
3797            // find the dimension index in the tempRegion which is the dimension
3798            // type passed to this method (paranoidly expecting different order)
3799            int tempIncreasedDimensionIndex = -1;
3800            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3801                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3802                    tempIncreasedDimensionIndex = d;
3803                    break;
3804                }
3805            }
3806    
3807            // copy dimension regions from this region to the temporary region
3808            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3809                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3810                if (!srcDimRgn) continue;
3811                std::map<dimension_t,int> dimCase;
3812                bool isValidZone = true;
3813                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3814                    const int srcBits = pDimensionDefinitions[d].bits;
3815                    dimCase[pDimensionDefinitions[d].dimension] =
3816                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3817                    // there are also DimensionRegion objects for unused zones, skip them
3818                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3819                        isValidZone = false;
3820                        break;
3821                    }
3822                    baseBits += srcBits;
3823                }
3824                if (!isValidZone) continue;
3825                // a bit paranoid: cope with the chance that the dimensions would
3826                // have different order in source and destination regions            
3827                if (dimCase[type] > zone) dimCase[type]++;
3828                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3829                dstDimRgn->CopyAssign(srcDimRgn);
3830                // if this is the requested zone to be splitted, then also copy
3831                // the source DimensionRegion to the newly created target zone
3832                // and set the old zones upper limit lower
3833                if (dimCase[type] == zone) {
3834                    // lower old zones upper limit
3835                    if (newDef.split_type == split_type_normal) {
3836                        const int high =
3837                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3838                        int low = 0;
3839                        if (zone > 0) {
3840                            std::map<dimension_t,int> lowerCase = dimCase;
3841                            lowerCase[type]--;
3842                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3843                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3844                        }
3845                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3846                    }
3847                    // fill the newly created zone of the divided zone as well
3848                    dimCase[type]++;
3849                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3850                    dstDimRgn->CopyAssign(srcDimRgn);
3851                }
3852            }
3853    
3854            // now tempRegion's dimensions and DimensionRegions basically reflect
3855            // what we wanted to get for this actual Region here, so we now just
3856            // delete and recreate the dimension in question with the new amount
3857            // zones and then copy back from tempRegion      
3858            DeleteDimension(oldDef);
3859            AddDimension(&newDef);
3860            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3861                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3862                if (!srcDimRgn) continue;
3863                std::map<dimension_t,int> dimCase;
3864                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3865                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3866                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3867                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3868                    baseBits += srcBits;
3869                }
3870                // a bit paranoid: cope with the chance that the dimensions would
3871                // have different order in source and destination regions
3872                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3873                if (!dstDimRgn) continue;
3874                dstDimRgn->CopyAssign(srcDimRgn);
3875            }
3876    
3877            // delete temporary region
3878            delete tempRgn;
3879    
3880            UpdateVelocityTable();
3881        }
3882    
3883        /** @brief Change type of an existing dimension.
3884         *
3885         * Alters the dimension type of a dimension already existing on this
3886         * region. If there is currently no dimension on this Region with type
3887         * @a oldType, then this call with throw an Exception. Likewise there are
3888         * cases where the requested dimension type cannot be performed. For example
3889         * if the new dimension type shall be gig::dimension_samplechannel, and the
3890         * current dimension has more than 2 zones. In such cases an Exception is
3891         * thrown as well.
3892         *
3893         * @param oldType - identifies the existing dimension to be changed
3894         * @param newType - to which dimension type it should be changed to
3895         * @throws gig::Exception if requested change cannot be performed
3896         */
3897        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3898            if (oldType == newType) return;
3899            dimension_def_t* def = GetDimensionDefinition(oldType);
3900            if (!def)
3901                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3902            if (newType == dimension_samplechannel && def->zones != 2)
3903                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3904            if (GetDimensionDefinition(newType))
3905                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3906            def->dimension  = newType;
3907            def->split_type = __resolveSplitType(newType);
3908        }
3909    
3910        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3911            uint8_t bits[8] = {};
3912            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3913                 it != DimCase.end(); ++it)
3914            {
3915                for (int d = 0; d < Dimensions; ++d) {
3916                    if (pDimensionDefinitions[d].dimension == it->first) {
3917                        bits[d] = it->second;
3918                        goto nextDimCaseSlice;
3919                    }
3920                }
3921                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3922                nextDimCaseSlice:
3923                ; // noop
3924            }
3925            return GetDimensionRegionByBit(bits);
3926        }
3927    
3928        /**
3929         * Searches in the current Region for a dimension of the given dimension
3930         * type and returns the precise configuration of that dimension in this
3931         * Region.
3932         *
3933         * @param type - dimension type of the sought dimension
3934         * @returns dimension definition or NULL if there is no dimension with
3935         *          sought type in this Region.
3936         */
3937        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3938            for (int i = 0; i < Dimensions; ++i)
3939                if (pDimensionDefinitions[i].dimension == type)
3940                    return &pDimensionDefinitions[i];
3941            return NULL;
3942        }
3943    
3944      Region::~Region() {      Region::~Region() {
3945          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3946              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2833  namespace { Line 3968  namespace {
3968      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3969          uint8_t bits;          uint8_t bits;
3970          int veldim = -1;          int veldim = -1;
3971          int velbitpos;          int velbitpos = 0;
3972          int bitpos = 0;          int bitpos = 0;
3973          int dimregidx = 0;          int dimregidx = 0;
3974          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 2863  namespace { Line 3998  namespace {
3998              }              }
3999              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
4000          }          }
4001          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
4002            if (!dimreg) return NULL;
4003          if (veldim != -1) {          if (veldim != -1) {
4004              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
4005              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
4006                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
4007              else // normal split type              else // normal split type
4008                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
4009    
4010              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4011              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
4012                dimreg = pDimensionRegions[dimregidx & 255];
4013          }          }
4014          return dimreg;          return dimreg;
4015      }      }
4016    
4017        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
4018            uint8_t bits;
4019            int veldim = -1;
4020            int velbitpos = 0;
4021            int bitpos = 0;
4022            int dimregidx = 0;
4023            for (uint i = 0; i < Dimensions; i++) {
4024                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
4025                    // the velocity dimension must be handled after the other dimensions
4026                    veldim = i;
4027                    velbitpos = bitpos;
4028                } else {
4029                    switch (pDimensionDefinitions[i].split_type) {
4030                        case split_type_normal:
4031                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
4032                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
4033                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
4034                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
4035                                }
4036                            } else {
4037                                // gig2: evenly sized zones
4038                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
4039                            }
4040                            break;
4041                        case split_type_bit: // the value is already the sought dimension bit number
4042                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
4043                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
4044                            break;
4045                    }
4046                    dimregidx |= bits << bitpos;
4047                }
4048                bitpos += pDimensionDefinitions[i].bits;
4049            }
4050            dimregidx &= 255;
4051            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
4052            if (!dimreg) return -1;
4053            if (veldim != -1) {
4054                // (dimreg is now the dimension region for the lowest velocity)
4055                if (dimreg->VelocityTable) // custom defined zone ranges
4056                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
4057                else // normal split type
4058                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
4059    
4060                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4061                dimregidx |= (bits & limiter_mask) << velbitpos;
4062                dimregidx &= 255;
4063            }
4064            return dimregidx;
4065        }
4066    
4067      /**      /**
4068       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
4069       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2915  namespace { Line 4102  namespace {
4102          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4103          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4104          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
4105          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4106          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4107          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
4108          while (sample) {              uint64_t soughtoffset =
4109              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4110                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4111              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
4112                while (sample) {
4113                    if (sample->ullWavePoolOffset == soughtoffset)
4114                        return static_cast<gig::Sample*>(sample);
4115                    sample = file->GetNextSample();
4116                }
4117            } else {
4118                // use extension files and 32 bit wave pool offsets
4119                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4120                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4121                Sample* sample = file->GetFirstSample(pProgress);
4122                while (sample) {
4123                    if (sample->ullWavePoolOffset == soughtoffset &&
4124                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4125                    sample = file->GetNextSample();
4126                }
4127          }          }
4128          return NULL;          return NULL;
4129      }      }
4130        
4131        /**
4132         * Make a (semi) deep copy of the Region object given by @a orig
4133         * and assign it to this object.
4134         *
4135         * Note that all sample pointers referenced by @a orig are simply copied as
4136         * memory address. Thus the respective samples are shared, not duplicated!
4137         *
4138         * @param orig - original Region object to be copied from
4139         */
4140        void Region::CopyAssign(const Region* orig) {
4141            CopyAssign(orig, NULL);
4142        }
4143        
4144        /**
4145         * Make a (semi) deep copy of the Region object given by @a orig and
4146         * assign it to this object
4147         *
4148         * @param mSamples - crosslink map between the foreign file's samples and
4149         *                   this file's samples
4150         */
4151        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
4152            // handle base classes
4153            DLS::Region::CopyAssign(orig);
4154            
4155            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
4156                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
4157            }
4158            
4159            // handle own member variables
4160            for (int i = Dimensions - 1; i >= 0; --i) {
4161                DeleteDimension(&pDimensionDefinitions[i]);
4162            }
4163            Layers = 0; // just to be sure
4164            for (int i = 0; i < orig->Dimensions; i++) {
4165                // we need to copy the dim definition here, to avoid the compiler
4166                // complaining about const-ness issue
4167                dimension_def_t def = orig->pDimensionDefinitions[i];
4168                AddDimension(&def);
4169            }
4170            for (int i = 0; i < 256; i++) {
4171                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4172                    pDimensionRegions[i]->CopyAssign(
4173                        orig->pDimensionRegions[i],
4174                        mSamples
4175                    );
4176                }
4177            }
4178            Layers = orig->Layers;
4179        }
4180    
4181    
4182  // *************** MidiRule ***************  // *************** MidiRule ***************
4183  // *  // *
4184    
4185  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {      MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4186      _3ewg->SetPos(36);          _3ewg->SetPos(36);
4187      Triggers = _3ewg->ReadUint8();          Triggers = _3ewg->ReadUint8();
4188      _3ewg->SetPos(40);          _3ewg->SetPos(40);
4189      ControllerNumber = _3ewg->ReadUint8();          ControllerNumber = _3ewg->ReadUint8();
4190      _3ewg->SetPos(46);          _3ewg->SetPos(46);
4191      for (int i = 0 ; i < Triggers ; i++) {          for (int i = 0 ; i < Triggers ; i++) {
4192          pTriggers[i].TriggerPoint = _3ewg->ReadUint8();              pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4193          pTriggers[i].Descending = _3ewg->ReadUint8();              pTriggers[i].Descending = _3ewg->ReadUint8();
4194          pTriggers[i].VelSensitivity = _3ewg->ReadUint8();              pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4195          pTriggers[i].Key = _3ewg->ReadUint8();              pTriggers[i].Key = _3ewg->ReadUint8();
4196          pTriggers[i].NoteOff = _3ewg->ReadUint8();              pTriggers[i].NoteOff = _3ewg->ReadUint8();
4197          pTriggers[i].Velocity = _3ewg->ReadUint8();              pTriggers[i].Velocity = _3ewg->ReadUint8();
4198          pTriggers[i].OverridePedal = _3ewg->ReadUint8();              pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4199          _3ewg->ReadUint8();              _3ewg->ReadUint8();
4200            }
4201        }
4202    
4203        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4204            ControllerNumber(0),
4205            Triggers(0) {
4206        }
4207    
4208        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4209            pData[32] = 4;
4210            pData[33] = 16;
4211            pData[36] = Triggers;
4212            pData[40] = ControllerNumber;
4213            for (int i = 0 ; i < Triggers ; i++) {
4214                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4215                pData[47 + i * 8] = pTriggers[i].Descending;
4216                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4217                pData[49 + i * 8] = pTriggers[i].Key;
4218                pData[50 + i * 8] = pTriggers[i].NoteOff;
4219                pData[51 + i * 8] = pTriggers[i].Velocity;
4220                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4221            }
4222        }
4223    
4224        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4225            _3ewg->SetPos(36);
4226            LegatoSamples = _3ewg->ReadUint8(); // always 12
4227            _3ewg->SetPos(40);
4228            BypassUseController = _3ewg->ReadUint8();
4229            BypassKey = _3ewg->ReadUint8();
4230            BypassController = _3ewg->ReadUint8();
4231            ThresholdTime = _3ewg->ReadUint16();
4232            _3ewg->ReadInt16();
4233            ReleaseTime = _3ewg->ReadUint16();
4234            _3ewg->ReadInt16();
4235            KeyRange.low = _3ewg->ReadUint8();
4236            KeyRange.high = _3ewg->ReadUint8();
4237            _3ewg->SetPos(64);
4238            ReleaseTriggerKey = _3ewg->ReadUint8();
4239            AltSustain1Key = _3ewg->ReadUint8();
4240            AltSustain2Key = _3ewg->ReadUint8();
4241        }
4242    
4243        MidiRuleLegato::MidiRuleLegato() :
4244            LegatoSamples(12),
4245            BypassUseController(false),
4246            BypassKey(0),
4247            BypassController(1),
4248            ThresholdTime(20),
4249            ReleaseTime(20),
4250            ReleaseTriggerKey(0),
4251            AltSustain1Key(0),
4252            AltSustain2Key(0)
4253        {
4254            KeyRange.low = KeyRange.high = 0;
4255        }
4256    
4257        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4258            pData[32] = 0;
4259            pData[33] = 16;
4260            pData[36] = LegatoSamples;
4261            pData[40] = BypassUseController;
4262            pData[41] = BypassKey;
4263            pData[42] = BypassController;
4264            store16(&pData[43], ThresholdTime);
4265            store16(&pData[47], ReleaseTime);
4266            pData[51] = KeyRange.low;
4267            pData[52] = KeyRange.high;
4268            pData[64] = ReleaseTriggerKey;
4269            pData[65] = AltSustain1Key;
4270            pData[66] = AltSustain2Key;
4271        }
4272    
4273        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4274            _3ewg->SetPos(36);
4275            Articulations = _3ewg->ReadUint8();
4276            int flags = _3ewg->ReadUint8();
4277            Polyphonic = flags & 8;
4278            Chained = flags & 4;
4279            Selector = (flags & 2) ? selector_controller :
4280                (flags & 1) ? selector_key_switch : selector_none;
4281            Patterns = _3ewg->ReadUint8();
4282            _3ewg->ReadUint8(); // chosen row
4283            _3ewg->ReadUint8(); // unknown
4284            _3ewg->ReadUint8(); // unknown
4285            _3ewg->ReadUint8(); // unknown
4286            KeySwitchRange.low = _3ewg->ReadUint8();
4287            KeySwitchRange.high = _3ewg->ReadUint8();
4288            Controller = _3ewg->ReadUint8();
4289            PlayRange.low = _3ewg->ReadUint8();
4290            PlayRange.high = _3ewg->ReadUint8();
4291    
4292            int n = std::min(int(Articulations), 32);
4293            for (int i = 0 ; i < n ; i++) {
4294                _3ewg->ReadString(pArticulations[i], 32);
4295            }
4296            _3ewg->SetPos(1072);
4297            n = std::min(int(Patterns), 32);
4298            for (int i = 0 ; i < n ; i++) {
4299                _3ewg->ReadString(pPatterns[i].Name, 16);
4300                pPatterns[i].Size = _3ewg->ReadUint8();
4301                _3ewg->Read(&pPatterns[i][0], 1, 32);
4302            }
4303        }
4304    
4305        MidiRuleAlternator::MidiRuleAlternator() :
4306            Articulations(0),
4307            Patterns(0),
4308            Selector(selector_none),
4309            Controller(0),
4310            Polyphonic(false),
4311            Chained(false)
4312        {
4313            PlayRange.low = PlayRange.high = 0;
4314            KeySwitchRange.low = KeySwitchRange.high = 0;
4315        }
4316    
4317        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4318            pData[32] = 3;
4319            pData[33] = 16;
4320            pData[36] = Articulations;
4321            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4322                (Selector == selector_controller ? 2 :
4323                 (Selector == selector_key_switch ? 1 : 0));
4324            pData[38] = Patterns;
4325    
4326            pData[43] = KeySwitchRange.low;
4327            pData[44] = KeySwitchRange.high;
4328            pData[45] = Controller;
4329            pData[46] = PlayRange.low;
4330            pData[47] = PlayRange.high;
4331    
4332            char* str = reinterpret_cast<char*>(pData);
4333            int pos = 48;
4334            int n = std::min(int(Articulations), 32);
4335            for (int i = 0 ; i < n ; i++, pos += 32) {
4336                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4337            }
4338    
4339            pos = 1072;
4340            n = std::min(int(Patterns), 32);
4341            for (int i = 0 ; i < n ; i++, pos += 49) {
4342                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4343                pData[pos + 16] = pPatterns[i].Size;
4344                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4345            }
4346        }
4347    
4348    // *************** Script ***************
4349    // *
4350    
4351        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4352            pGroup = group;
4353            pChunk = ckScri;
4354            if (ckScri) { // object is loaded from file ...
4355                // read header
4356                uint32_t headerSize = ckScri->ReadUint32();
4357                Compression = (Compression_t) ckScri->ReadUint32();
4358                Encoding    = (Encoding_t) ckScri->ReadUint32();
4359                Language    = (Language_t) ckScri->ReadUint32();
4360                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4361                crc         = ckScri->ReadUint32();
4362                uint32_t nameSize = ckScri->ReadUint32();
4363                Name.resize(nameSize, ' ');
4364                for (int i = 0; i < nameSize; ++i)
4365                    Name[i] = ckScri->ReadUint8();
4366                // to handle potential future extensions of the header
4367                ckScri->SetPos(sizeof(int32_t) + headerSize);
4368                // read actual script data
4369                uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4370                data.resize(scriptSize);
4371                for (int i = 0; i < scriptSize; ++i)
4372                    data[i] = ckScri->ReadUint8();
4373            } else { // this is a new script object, so just initialize it as such ...
4374                Compression = COMPRESSION_NONE;
4375                Encoding = ENCODING_ASCII;
4376                Language = LANGUAGE_NKSP;
4377                Bypass   = false;
4378                crc      = 0;
4379                Name     = "Unnamed Script";
4380            }
4381        }
4382    
4383        Script::~Script() {
4384        }
4385    
4386        /**
4387         * Returns the current script (i.e. as source code) in text format.
4388         */
4389        String Script::GetScriptAsText() {
4390            String s;
4391            s.resize(data.size(), ' ');
4392            memcpy(&s[0], &data[0], data.size());
4393            return s;
4394        }
4395    
4396        /**
4397         * Replaces the current script with the new script source code text given
4398         * by @a text.
4399         *
4400         * @param text - new script source code
4401         */
4402        void Script::SetScriptAsText(const String& text) {
4403            data.resize(text.size());
4404            memcpy(&data[0], &text[0], text.size());
4405        }
4406    
4407        /**
4408         * Apply this script to the respective RIFF chunks. You have to call
4409         * File::Save() to make changes persistent.
4410         *
4411         * Usually there is absolutely no need to call this method explicitly.
4412         * It will be called automatically when File::Save() was called.
4413         *
4414         * @param pProgress - callback function for progress notification
4415         */
4416        void Script::UpdateChunks(progress_t* pProgress) {
4417            // recalculate CRC32 check sum
4418            __resetCRC(crc);
4419            __calculateCRC(&data[0], data.size(), crc);
4420            __finalizeCRC(crc);
4421            // make sure chunk exists and has the required size
4422            const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4423            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4424            else pChunk->Resize(chunkSize);
4425            // fill the chunk data to be written to disk
4426            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4427            int pos = 0;
4428            store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4429            pos += sizeof(int32_t);
4430            store32(&pData[pos], Compression);
4431            pos += sizeof(int32_t);
4432            store32(&pData[pos], Encoding);
4433            pos += sizeof(int32_t);
4434            store32(&pData[pos], Language);
4435            pos += sizeof(int32_t);
4436            store32(&pData[pos], Bypass ? 1 : 0);
4437            pos += sizeof(int32_t);
4438            store32(&pData[pos], crc);
4439            pos += sizeof(int32_t);
4440            store32(&pData[pos], (uint32_t) Name.size());
4441            pos += sizeof(int32_t);
4442            for (int i = 0; i < Name.size(); ++i, ++pos)
4443                pData[pos] = Name[i];
4444            for (int i = 0; i < data.size(); ++i, ++pos)
4445                pData[pos] = data[i];
4446        }
4447    
4448        /**
4449         * Move this script from its current ScriptGroup to another ScriptGroup
4450         * given by @a pGroup.
4451         *
4452         * @param pGroup - script's new group
4453         */
4454        void Script::SetGroup(ScriptGroup* pGroup) {
4455            if (this->pGroup == pGroup) return;
4456            if (pChunk)
4457                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4458            this->pGroup = pGroup;
4459        }
4460    
4461        /**
4462         * Returns the script group this script currently belongs to. Each script
4463         * is a member of exactly one ScriptGroup.
4464         *
4465         * @returns current script group
4466         */
4467        ScriptGroup* Script::GetGroup() const {
4468            return pGroup;
4469        }
4470    
4471        /**
4472         * Make a (semi) deep copy of the Script object given by @a orig
4473         * and assign it to this object. Note: the ScriptGroup this Script
4474         * object belongs to remains untouched by this call.
4475         *
4476         * @param orig - original Script object to be copied from
4477         */
4478        void Script::CopyAssign(const Script* orig) {
4479            Name        = orig->Name;
4480            Compression = orig->Compression;
4481            Encoding    = orig->Encoding;
4482            Language    = orig->Language;
4483            Bypass      = orig->Bypass;
4484            data        = orig->data;
4485      }      }
 }  
4486    
4487        void Script::RemoveAllScriptReferences() {
4488            File* pFile = pGroup->pFile;
4489            for (int i = 0; pFile->GetInstrument(i); ++i) {
4490                Instrument* instr = pFile->GetInstrument(i);
4491                instr->RemoveScript(this);
4492            }
4493        }
4494    
4495    // *************** ScriptGroup ***************
4496    // *
4497    
4498        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4499            pFile = file;
4500            pList = lstRTIS;
4501            pScripts = NULL;
4502            if (lstRTIS) {
4503                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4504                ::LoadString(ckName, Name);
4505            } else {
4506                Name = "Default Group";
4507            }
4508        }
4509    
4510        ScriptGroup::~ScriptGroup() {
4511            if (pScripts) {
4512                std::list<Script*>::iterator iter = pScripts->begin();
4513                std::list<Script*>::iterator end  = pScripts->end();
4514                while (iter != end) {
4515                    delete *iter;
4516                    ++iter;
4517                }
4518                delete pScripts;
4519            }
4520        }
4521    
4522        /**
4523         * Apply this script group to the respective RIFF chunks. You have to call
4524         * File::Save() to make changes persistent.
4525         *
4526         * Usually there is absolutely no need to call this method explicitly.
4527         * It will be called automatically when File::Save() was called.
4528         *
4529         * @param pProgress - callback function for progress notification
4530         */
4531        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4532            if (pScripts) {
4533                if (!pList)
4534                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4535    
4536                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4537                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4538    
4539                for (std::list<Script*>::iterator it = pScripts->begin();
4540                     it != pScripts->end(); ++it)
4541                {
4542                    (*it)->UpdateChunks(pProgress);
4543                }
4544            }
4545        }
4546    
4547        /** @brief Get instrument script.
4548         *
4549         * Returns the real-time instrument script with the given index.
4550         *
4551         * @param index - number of the sought script (0..n)
4552         * @returns sought script or NULL if there's no such script
4553         */
4554        Script* ScriptGroup::GetScript(uint index) {
4555            if (!pScripts) LoadScripts();
4556            std::list<Script*>::iterator it = pScripts->begin();
4557            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4558                if (i == index) return *it;
4559            return NULL;
4560        }
4561    
4562        /** @brief Add new instrument script.
4563         *
4564         * Adds a new real-time instrument script to the file. The script is not
4565         * actually used / executed unless it is referenced by an instrument to be
4566         * used. This is similar to samples, which you can add to a file, without
4567         * an instrument necessarily actually using it.
4568         *
4569         * You have to call Save() to make this persistent to the file.
4570         *
4571         * @return new empty script object
4572         */
4573        Script* ScriptGroup::AddScript() {
4574            if (!pScripts) LoadScripts();
4575            Script* pScript = new Script(this, NULL);
4576            pScripts->push_back(pScript);
4577            return pScript;
4578        }
4579    
4580        /** @brief Delete an instrument script.
4581         *
4582         * This will delete the given real-time instrument script. References of
4583         * instruments that are using that script will be removed accordingly.
4584         *
4585         * You have to call Save() to make this persistent to the file.
4586         *
4587         * @param pScript - script to delete
4588         * @throws gig::Exception if given script could not be found
4589         */
4590        void ScriptGroup::DeleteScript(Script* pScript) {
4591            if (!pScripts) LoadScripts();
4592            std::list<Script*>::iterator iter =
4593                find(pScripts->begin(), pScripts->end(), pScript);
4594            if (iter == pScripts->end())
4595                throw gig::Exception("Could not delete script, could not find given script");
4596            pScripts->erase(iter);
4597            pScript->RemoveAllScriptReferences();
4598            if (pScript->pChunk)
4599                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4600            delete pScript;
4601        }
4602    
4603        void ScriptGroup::LoadScripts() {
4604            if (pScripts) return;
4605            pScripts = new std::list<Script*>;
4606            if (!pList) return;
4607    
4608            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4609                 ck = pList->GetNextSubChunk())
4610            {
4611                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4612                    pScripts->push_back(new Script(this, ck));
4613                }
4614            }
4615        }
4616    
4617  // *************** Instrument ***************  // *************** Instrument ***************
4618  // *  // *
# Line 2965  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4630  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4630          EffectSend = 0;          EffectSend = 0;
4631          Attenuation = 0;          Attenuation = 0;
4632          FineTune = 0;          FineTune = 0;
4633          PitchbendRange = 0;          PitchbendRange = 2;
4634          PianoReleaseMode = false;          PianoReleaseMode = false;
4635          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4636          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4637          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4638          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4639            pScriptRefs = NULL;
4640    
4641          // Loading          // Loading
4642          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2993  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4659  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4659                      uint8_t id1 = _3ewg->ReadUint8();                      uint8_t id1 = _3ewg->ReadUint8();
4660                      uint8_t id2 = _3ewg->ReadUint8();                      uint8_t id2 = _3ewg->ReadUint8();
4661    
4662                      if (id1 == 4 && id2 == 16) {                      if (id2 == 16) {
4663                          pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);                          if (id1 == 4) {
4664                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4665                            } else if (id1 == 0) {
4666                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4667                            } else if (id1 == 3) {
4668                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4669                            } else {
4670                                pMidiRules[i++] = new MidiRuleUnknown;
4671                            }
4672                        }
4673                        else if (id1 != 0 || id2 != 0) {
4674                            pMidiRules[i++] = new MidiRuleUnknown;
4675                      }                      }
4676                      //TODO: all the other types of rules                      //TODO: all the other types of rules
4677    
# Line 3020  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4697  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4697              }              }
4698          }          }
4699    
4700            // own gig format extensions
4701            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4702            if (lst3LS) {
4703                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4704                if (ckSCSL) {
4705                    int headerSize = ckSCSL->ReadUint32();
4706                    int slotCount  = ckSCSL->ReadUint32();
4707                    if (slotCount) {
4708                        int slotSize  = ckSCSL->ReadUint32();
4709                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4710                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4711                        for (int i = 0; i < slotCount; ++i) {
4712                            _ScriptPooolEntry e;
4713                            e.fileOffset = ckSCSL->ReadUint32();
4714                            e.bypass     = ckSCSL->ReadUint32() & 1;
4715                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4716                            scriptPoolFileOffsets.push_back(e);
4717                        }
4718                    }
4719                }
4720            }
4721    
4722          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4723      }      }
4724    
# Line 3036  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4735  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4735      }      }
4736    
4737      Instrument::~Instrument() {      Instrument::~Instrument() {
4738            for (int i = 0 ; pMidiRules[i] ; i++) {
4739                delete pMidiRules[i];
4740            }
4741          delete[] pMidiRules;          delete[] pMidiRules;
4742            if (pScriptRefs) delete pScriptRefs;
4743      }      }
4744    
4745      /**      /**
# Line 3046  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4749  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4749       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4750       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4751       *       *
4752         * @param pProgress - callback function for progress notification
4753       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4754       */       */
4755      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4756          // first update base classes' chunks          // first update base classes' chunks
4757          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4758    
4759          // update Regions' chunks          // update Regions' chunks
4760          {          {
4761              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4762              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4763              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4764                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4765          }          }
4766    
4767          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 3083  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4787  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4787                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4788          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4789          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4790    
4791            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4792                pData[32] = 0;
4793                pData[33] = 0;
4794            } else {
4795                for (int i = 0 ; pMidiRules[i] ; i++) {
4796                    pMidiRules[i]->UpdateChunks(pData);
4797                }
4798            }
4799    
4800            // own gig format extensions
4801           if (ScriptSlotCount()) {
4802               // make sure we have converted the original loaded script file
4803               // offsets into valid Script object pointers
4804               LoadScripts();
4805    
4806               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4807               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4808               const int slotCount = (int) pScriptRefs->size();
4809               const int headerSize = 3 * sizeof(uint32_t);
4810               const int slotSize  = 2 * sizeof(uint32_t);
4811               const int totalChunkSize = headerSize + slotCount * slotSize;
4812               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4813               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4814               else ckSCSL->Resize(totalChunkSize);
4815               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4816               int pos = 0;
4817               store32(&pData[pos], headerSize);
4818               pos += sizeof(uint32_t);
4819               store32(&pData[pos], slotCount);
4820               pos += sizeof(uint32_t);
4821               store32(&pData[pos], slotSize);
4822               pos += sizeof(uint32_t);
4823               for (int i = 0; i < slotCount; ++i) {
4824                   // arbitrary value, the actual file offset will be updated in
4825                   // UpdateScriptFileOffsets() after the file has been resized
4826                   int bogusFileOffset = 0;
4827                   store32(&pData[pos], bogusFileOffset);
4828                   pos += sizeof(uint32_t);
4829                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4830                   pos += sizeof(uint32_t);
4831               }
4832           } else {
4833               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4834               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4835               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4836           }
4837        }
4838    
4839        void Instrument::UpdateScriptFileOffsets() {
4840           // own gig format extensions
4841           if (pScriptRefs && pScriptRefs->size() > 0) {
4842               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4843               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4844               const int slotCount = (int) pScriptRefs->size();
4845               const int headerSize = 3 * sizeof(uint32_t);
4846               ckSCSL->SetPos(headerSize);
4847               for (int i = 0; i < slotCount; ++i) {
4848                   uint32_t fileOffset = uint32_t(
4849                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4850                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4851                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4852                   );
4853                   ckSCSL->WriteUint32(&fileOffset);
4854                   // jump over flags entry (containing the bypass flag)
4855                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4856               }
4857           }        
4858      }      }
4859    
4860      /**      /**
# Line 3137  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4909  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4909          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4910          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4911          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4912          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4913          // update Region key table for fast lookup          // update Region key table for fast lookup
4914          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4915          // done          // done
# Line 3152  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4924  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4924      }      }
4925    
4926      /**      /**
4927         * Move this instrument at the position before @arg dst.
4928         *
4929         * This method can be used to reorder the sequence of instruments in a
4930         * .gig file. This might be helpful especially on large .gig files which
4931         * contain a large number of instruments within the same .gig file. So
4932         * grouping such instruments to similar ones, can help to keep track of them
4933         * when working with such complex .gig files.
4934         *
4935         * When calling this method, this instrument will be removed from in its
4936         * current position in the instruments list and moved to the requested
4937         * target position provided by @param dst. You may also pass NULL as
4938         * argument to this method, in that case this intrument will be moved to the
4939         * very end of the .gig file's instrument list.
4940         *
4941         * You have to call Save() to make the order change persistent to the .gig
4942         * file.
4943         *
4944         * Currently this method is limited to moving the instrument within the same
4945         * .gig file. Trying to move it to another .gig file by calling this method
4946         * will throw an exception.
4947         *
4948         * @param dst - destination instrument at which this instrument will be
4949         *              moved to, or pass NULL for moving to end of list
4950         * @throw gig::Exception if this instrument and target instrument are not
4951         *                       part of the same file
4952         */
4953        void Instrument::MoveTo(Instrument* dst) {
4954            if (dst && GetParent() != dst->GetParent())
4955                throw Exception(
4956                    "gig::Instrument::MoveTo() can only be used for moving within "
4957                    "the same gig file."
4958                );
4959    
4960            File* pFile = (File*) GetParent();
4961    
4962            // move this instrument within the instrument list
4963            {
4964                File::InstrumentList& list = *pFile->pInstruments;
4965    
4966                File::InstrumentList::iterator itFrom =
4967                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4968    
4969                File::InstrumentList::iterator itTo =
4970                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4971    
4972                list.splice(itTo, list, itFrom);
4973            }
4974    
4975            // move the instrument's actual list RIFF chunk appropriately
4976            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4977            lstCkInstruments->MoveSubChunk(
4978                this->pCkInstrument,
4979                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4980            );
4981        }
4982    
4983        /**
4984       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4985       *       *
4986       * The list of MIDI rules, at least in gig v3, always contains at       * The list of MIDI rules, at least in gig v3, always contains at
# Line 3165  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 4994  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
4994          return pMidiRules[i];          return pMidiRules[i];
4995      }      }
4996    
4997        /**
4998         * Adds the "controller trigger" MIDI rule to the instrument.
4999         *
5000         * @returns the new MIDI rule
5001         */
5002        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
5003            delete pMidiRules[0];
5004            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
5005            pMidiRules[0] = r;
5006            pMidiRules[1] = 0;
5007            return r;
5008        }
5009    
5010        /**
5011         * Adds the legato MIDI rule to the instrument.
5012         *
5013         * @returns the new MIDI rule
5014         */
5015        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
5016            delete pMidiRules[0];
5017            MidiRuleLegato* r = new MidiRuleLegato;
5018            pMidiRules[0] = r;
5019            pMidiRules[1] = 0;
5020            return r;
5021        }
5022    
5023        /**
5024         * Adds the alternator MIDI rule to the instrument.
5025         *
5026         * @returns the new MIDI rule
5027         */
5028        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
5029            delete pMidiRules[0];
5030            MidiRuleAlternator* r = new MidiRuleAlternator;
5031            pMidiRules[0] = r;
5032            pMidiRules[1] = 0;
5033            return r;
5034        }
5035    
5036        /**
5037         * Deletes a MIDI rule from the instrument.
5038         *
5039         * @param i - MIDI rule number
5040         */
5041        void Instrument::DeleteMidiRule(int i) {
5042            delete pMidiRules[i];
5043            pMidiRules[i] = 0;
5044        }
5045    
5046        void Instrument::LoadScripts() {
5047            if (pScriptRefs) return;
5048            pScriptRefs = new std::vector<_ScriptPooolRef>;
5049            if (scriptPoolFileOffsets.empty()) return;
5050            File* pFile = (File*) GetParent();
5051            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
5052                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
5053                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
5054                    ScriptGroup* group = pFile->GetScriptGroup(i);
5055                    for (uint s = 0; group->GetScript(s); ++s) {
5056                        Script* script = group->GetScript(s);
5057                        if (script->pChunk) {
5058                            uint32_t offset = uint32_t(
5059                                script->pChunk->GetFilePos() -
5060                                script->pChunk->GetPos() -
5061                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5062                            );
5063                            if (offset == soughtOffset)
5064                            {
5065                                _ScriptPooolRef ref;
5066                                ref.script = script;
5067                                ref.bypass = scriptPoolFileOffsets[k].bypass;
5068                                pScriptRefs->push_back(ref);
5069                                break;
5070                            }
5071                        }
5072                    }
5073                }
5074            }
5075            // we don't need that anymore
5076            scriptPoolFileOffsets.clear();
5077        }
5078    
5079        /** @brief Get instrument script (gig format extension).
5080         *
5081         * Returns the real-time instrument script of instrument script slot
5082         * @a index.
5083         *
5084         * @note This is an own format extension which did not exist i.e. in the
5085         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5086         * gigedit.
5087         *
5088         * @param index - instrument script slot index
5089         * @returns script or NULL if index is out of bounds
5090         */
5091        Script* Instrument::GetScriptOfSlot(uint index) {
5092            LoadScripts();
5093            if (index >= pScriptRefs->size()) return NULL;
5094            return pScriptRefs->at(index).script;
5095        }
5096    
5097        /** @brief Add new instrument script slot (gig format extension).
5098         *
5099         * Add the given real-time instrument script reference to this instrument,
5100         * which shall be executed by the sampler for for this instrument. The
5101         * script will be added to the end of the script list of this instrument.
5102         * The positions of the scripts in the Instrument's Script list are
5103         * relevant, because they define in which order they shall be executed by
5104         * the sampler. For this reason it is also legal to add the same script
5105         * twice to an instrument, for example you might have a script called
5106         * "MyFilter" which performs an event filter task, and you might have
5107         * another script called "MyNoteTrigger" which triggers new notes, then you
5108         * might for example have the following list of scripts on the instrument:
5109         *
5110         * 1. Script "MyFilter"
5111         * 2. Script "MyNoteTrigger"
5112         * 3. Script "MyFilter"
5113         *
5114         * Which would make sense, because the 2nd script launched new events, which
5115         * you might need to filter as well.
5116         *
5117         * There are two ways to disable / "bypass" scripts. You can either disable
5118         * a script locally for the respective script slot on an instrument (i.e. by
5119         * passing @c false to the 2nd argument of this method, or by calling
5120         * SetScriptBypassed()). Or you can disable a script globally for all slots
5121         * and all instruments by setting Script::Bypass.
5122         *
5123         * @note This is an own format extension which did not exist i.e. in the
5124         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5125         * gigedit.
5126         *
5127         * @param pScript - script that shall be executed for this instrument
5128         * @param bypass  - if enabled, the sampler shall skip executing this
5129         *                  script (in the respective list position)
5130         * @see SetScriptBypassed()
5131         */
5132        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
5133            LoadScripts();
5134            _ScriptPooolRef ref = { pScript, bypass };
5135            pScriptRefs->push_back(ref);
5136        }
5137    
5138        /** @brief Flip two script slots with each other (gig format extension).
5139         *
5140         * Swaps the position of the two given scripts in the Instrument's Script
5141         * list. The positions of the scripts in the Instrument's Script list are
5142         * relevant, because they define in which order they shall be executed by
5143         * the sampler.
5144         *
5145         * @note This is an own format extension which did not exist i.e. in the
5146         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5147         * gigedit.
5148         *
5149         * @param index1 - index of the first script slot to swap
5150         * @param index2 - index of the second script slot to swap
5151         */
5152        void Instrument::SwapScriptSlots(uint index1, uint index2) {
5153            LoadScripts();
5154            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
5155                return;
5156            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
5157            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
5158            (*pScriptRefs)[index2] = tmp;
5159        }
5160    
5161        /** @brief Remove script slot.
5162         *
5163         * Removes the script slot with the given slot index.
5164         *
5165         * @param index - index of script slot to remove
5166         */
5167        void Instrument::RemoveScriptSlot(uint index) {
5168            LoadScripts();
5169            if (index >= pScriptRefs->size()) return;
5170            pScriptRefs->erase( pScriptRefs->begin() + index );
5171        }
5172    
5173        /** @brief Remove reference to given Script (gig format extension).
5174         *
5175         * This will remove all script slots on the instrument which are referencing
5176         * the given script.
5177         *
5178         * @note This is an own format extension which did not exist i.e. in the
5179         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5180         * gigedit.
5181         *
5182         * @param pScript - script reference to remove from this instrument
5183         * @see RemoveScriptSlot()
5184         */
5185        void Instrument::RemoveScript(Script* pScript) {
5186            LoadScripts();
5187            for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5188                if ((*pScriptRefs)[i].script == pScript) {
5189                    pScriptRefs->erase( pScriptRefs->begin() + i );
5190                }
5191            }
5192        }
5193    
5194        /** @brief Instrument's amount of script slots.
5195         *
5196         * This method returns the amount of script slots this instrument currently
5197         * uses.
5198         *
5199         * A script slot is a reference of a real-time instrument script to be
5200         * executed by the sampler. The scripts will be executed by the sampler in
5201         * sequence of the slots. One (same) script may be referenced multiple
5202         * times in different slots.
5203         *
5204         * @note This is an own format extension which did not exist i.e. in the
5205         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5206         * gigedit.
5207         */
5208        uint Instrument::ScriptSlotCount() const {
5209            return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5210        }
5211    
5212        /** @brief Whether script execution shall be skipped.
5213         *
5214         * Defines locally for the Script reference slot in the Instrument's Script
5215         * list, whether the script shall be skipped by the sampler regarding
5216         * execution.
5217         *
5218         * It is also possible to ignore exeuction of the script globally, for all
5219         * slots and for all instruments by setting Script::Bypass.
5220         *
5221         * @note This is an own format extension which did not exist i.e. in the
5222         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5223         * gigedit.
5224         *
5225         * @param index - index of the script slot on this instrument
5226         * @see Script::Bypass
5227         */
5228        bool Instrument::IsScriptSlotBypassed(uint index) {
5229            if (index >= ScriptSlotCount()) return false;
5230            return pScriptRefs ? pScriptRefs->at(index).bypass
5231                               : scriptPoolFileOffsets.at(index).bypass;
5232            
5233        }
5234    
5235        /** @brief Defines whether execution shall be skipped.
5236         *
5237         * You can call this method to define locally whether or whether not the
5238         * given script slot shall be executed by the sampler.
5239         *
5240         * @note This is an own format extension which did not exist i.e. in the
5241         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5242         * gigedit.
5243         *
5244         * @param index - script slot index on this instrument
5245         * @param bBypass - if true, the script slot will be skipped by the sampler
5246         * @see Script::Bypass
5247         */
5248        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5249            if (index >= ScriptSlotCount()) return;
5250            if (pScriptRefs)
5251                pScriptRefs->at(index).bypass = bBypass;
5252            else
5253                scriptPoolFileOffsets.at(index).bypass = bBypass;
5254        }
5255    
5256        /**
5257         * Make a (semi) deep copy of the Instrument object given by @a orig
5258         * and assign it to this object.
5259         *
5260         * Note that all sample pointers referenced by @a orig are simply copied as
5261         * memory address. Thus the respective samples are shared, not duplicated!
5262         *
5263         * @param orig - original Instrument object to be copied from
5264         */
5265        void Instrument::CopyAssign(const Instrument* orig) {
5266            CopyAssign(orig, NULL);
5267        }
5268            
5269        /**
5270         * Make a (semi) deep copy of the Instrument object given by @a orig
5271         * and assign it to this object.
5272         *
5273         * @param orig - original Instrument object to be copied from
5274         * @param mSamples - crosslink map between the foreign file's samples and
5275         *                   this file's samples
5276         */
5277        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5278            // handle base class
5279            // (without copying DLS region stuff)
5280            DLS::Instrument::CopyAssignCore(orig);
5281            
5282            // handle own member variables
5283            Attenuation = orig->Attenuation;
5284            EffectSend = orig->EffectSend;
5285            FineTune = orig->FineTune;
5286            PitchbendRange = orig->PitchbendRange;
5287            PianoReleaseMode = orig->PianoReleaseMode;
5288            DimensionKeyRange = orig->DimensionKeyRange;
5289            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5290            pScriptRefs = orig->pScriptRefs;
5291            
5292            // free old midi rules
5293            for (int i = 0 ; pMidiRules[i] ; i++) {
5294                delete pMidiRules[i];
5295            }
5296            //TODO: MIDI rule copying
5297            pMidiRules[0] = NULL;
5298            
5299            // delete all old regions
5300            while (Regions) DeleteRegion(GetFirstRegion());
5301            // create new regions and copy them from original
5302            {
5303                RegionList::const_iterator it = orig->pRegions->begin();
5304                for (int i = 0; i < orig->Regions; ++i, ++it) {
5305                    Region* dstRgn = AddRegion();
5306                    //NOTE: Region does semi-deep copy !
5307                    dstRgn->CopyAssign(
5308                        static_cast<gig::Region*>(*it),
5309                        mSamples
5310                    );
5311                }
5312            }
5313    
5314            UpdateRegionKeyTable();
5315        }
5316    
5317    
5318  // *************** Group ***************  // *************** Group ***************
5319  // *  // *
# Line 3193  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5342  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5342       *       *
5343       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5344       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5345         *
5346         * @param pProgress - callback function for progress notification
5347       */       */
5348      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5349          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5350          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5351          if (!_3gri) {          if (!_3gri) {
# Line 3324  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5475  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5475          bAutoLoad = true;          bAutoLoad = true;
5476          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5477          pGroups = NULL;          pGroups = NULL;
5478            pScriptGroups = NULL;
5479          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5480          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5481    
# Line 3339  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5491  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5491      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5492          bAutoLoad = true;          bAutoLoad = true;
5493          pGroups = NULL;          pGroups = NULL;
5494            pScriptGroups = NULL;
5495          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5496      }      }
5497    
# Line 3352  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5505  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5505              }              }
5506              delete pGroups;              delete pGroups;
5507          }          }
5508            if (pScriptGroups) {
5509                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5510                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5511                while (iter != end) {
5512                    delete *iter;
5513                    ++iter;
5514                }
5515                delete pScriptGroups;
5516            }
5517      }      }
5518    
5519      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3366  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5528  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5528          SamplesIterator++;          SamplesIterator++;
5529          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5530      }      }
5531        
5532        /**
5533         * Returns Sample object of @a index.
5534         *
5535         * @returns sample object or NULL if index is out of bounds
5536         */
5537        Sample* File::GetSample(uint index) {
5538            if (!pSamples) LoadSamples();
5539            if (!pSamples) return NULL;
5540            DLS::File::SampleList::iterator it = pSamples->begin();
5541            for (int i = 0; i < index; ++i) {
5542                ++it;
5543                if (it == pSamples->end()) return NULL;
5544            }
5545            if (it == pSamples->end()) return NULL;
5546            return static_cast<gig::Sample*>( *it );
5547        }
5548    
5549      /** @brief Add a new sample.      /** @brief Add a new sample.
5550       *       *
# Line 3443  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5622  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5622          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5623    
5624          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5625            // (only for old gig files < 2 GB)
5626          int lastFileNo = 0;          int lastFileNo = 0;
5627          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5628              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5629                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5630                }
5631          }          }
5632          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5633          int nameLen = name.length();          int nameLen = (int) name.length();
5634          char suffix[6];          char suffix[6];
5635          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5636    
5637          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5638              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5639              if (wvpl) {              if (wvpl) {
5640                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5641                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5642                  while (wave) {                  while (wave) {
5643                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 3463  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5645  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5645                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5646                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5647    
5648                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5649                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5650    
5651                          iSampleIndex++;                          iSampleIndex++;
5652                      }                      }
# Line 3563  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5745  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5745         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5746         return pInstrument;         return pInstrument;
5747      }      }
5748        
5749        /** @brief Add a duplicate of an existing instrument.
5750         *
5751         * Duplicates the instrument definition given by @a orig and adds it
5752         * to this file. This allows in an instrument editor application to
5753         * easily create variations of an instrument, which will be stored in
5754         * the same .gig file, sharing i.e. the same samples.
5755         *
5756         * Note that all sample pointers referenced by @a orig are simply copied as
5757         * memory address. Thus the respective samples are shared, not duplicated!
5758         *
5759         * You have to call Save() to make this persistent to the file.
5760         *
5761         * @param orig - original instrument to be copied
5762         * @returns duplicated copy of the given instrument
5763         */
5764        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5765            Instrument* instr = AddInstrument();
5766            instr->CopyAssign(orig);
5767            return instr;
5768        }
5769        
5770        /** @brief Add content of another existing file.
5771         *
5772         * Duplicates the samples, groups and instruments of the original file
5773         * given by @a pFile and adds them to @c this File. In case @c this File is
5774         * a new one that you haven't saved before, then you have to call
5775         * SetFileName() before calling AddContentOf(), because this method will
5776         * automatically save this file during operation, which is required for
5777         * writing the sample waveform data by disk streaming.
5778         *
5779         * @param pFile - original file whose's content shall be copied from
5780         */
5781        void File::AddContentOf(File* pFile) {
5782            static int iCallCount = -1;
5783            iCallCount++;
5784            std::map<Group*,Group*> mGroups;
5785            std::map<Sample*,Sample*> mSamples;
5786            
5787            // clone sample groups
5788            for (int i = 0; pFile->GetGroup(i); ++i) {
5789                Group* g = AddGroup();
5790                g->Name =
5791                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5792                mGroups[pFile->GetGroup(i)] = g;
5793            }
5794            
5795            // clone samples (not waveform data here yet)
5796            for (int i = 0; pFile->GetSample(i); ++i) {
5797                Sample* s = AddSample();
5798                s->CopyAssignMeta(pFile->GetSample(i));
5799                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5800                mSamples[pFile->GetSample(i)] = s;
5801            }
5802    
5803            // clone script groups and their scripts
5804            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5805                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5806                ScriptGroup* dg = AddScriptGroup();
5807                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5808                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5809                    Script* ss = sg->GetScript(iScript);
5810                    Script* ds = dg->AddScript();
5811                    ds->CopyAssign(ss);
5812                }
5813            }
5814    
5815            //BUG: For some reason this method only works with this additional
5816            //     Save() call in between here.
5817            //
5818            // Important: The correct one of the 2 Save() methods has to be called
5819            // here, depending on whether the file is completely new or has been
5820            // saved to disk already, otherwise it will result in data corruption.
5821            if (pRIFF->IsNew())
5822                Save(GetFileName());
5823            else
5824                Save();
5825            
5826            // clone instruments
5827            // (passing the crosslink table here for the cloned samples)
5828            for (int i = 0; pFile->GetInstrument(i); ++i) {
5829                Instrument* instr = AddInstrument();
5830                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5831            }
5832            
5833            // Mandatory: file needs to be saved to disk at this point, so this
5834            // file has the correct size and data layout for writing the samples'
5835            // waveform data to disk.
5836            Save();
5837            
5838            // clone samples' waveform data
5839            // (using direct read & write disk streaming)
5840            for (int i = 0; pFile->GetSample(i); ++i) {
5841                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5842            }
5843        }
5844    
5845      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5846       *       *
# Line 3618  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 5896  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
5896          if (!_3crc) return;          if (!_3crc) return;
5897    
5898          // get the index of the sample          // get the index of the sample
5899          int iWaveIndex = -1;          int iWaveIndex = GetWaveTableIndexOf(pSample);
         File::SampleList::iterator iter = pSamples->begin();  
         File::SampleList::iterator end  = pSamples->end();  
         for (int index = 0; iter != end; ++iter, ++index) {  
             if (*iter == pSample) {  
                 iWaveIndex = index;  
                 break;  
             }  
         }  
5900          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5901    
5902          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5903          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5904          uint32_t tmp = 1;          uint32_t one = 1;
5905          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5906          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5907      }      }
5908    
5909        uint32_t File::GetSampleChecksum(Sample* pSample) {
5910            // get the index of the sample
5911            int iWaveIndex = GetWaveTableIndexOf(pSample);
5912            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5913    
5914            return GetSampleChecksumByIndex(iWaveIndex);
5915        }
5916    
5917        uint32_t File::GetSampleChecksumByIndex(int index) {
5918            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5919    
5920            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5921            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5922            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5923            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5924    
5925            // read the CRC-32 checksum directly from disk
5926            size_t pos = index * 8;
5927            if (pos + 8 > _3crc->GetNewSize())
5928                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5929    
5930            uint32_t one = load32(&pData[pos]); // always 1
5931            if (one != 1)
5932                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5933    
5934            return load32(&pData[pos+4]);
5935        }
5936    
5937        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5938            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5939            File::SampleList::iterator iter = pSamples->begin();
5940            File::SampleList::iterator end  = pSamples->end();
5941            for (int index = 0; iter != end; ++iter, ++index)
5942                if (*iter == pSample)
5943                    return index;
5944            return -1;
5945        }
5946    
5947        /**
5948         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5949         * the CRC32 check sums of all samples' raw wave data.
5950         *
5951         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5952         */
5953        bool File::VerifySampleChecksumTable() {
5954            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5955            if (!_3crc) return false;
5956            if (_3crc->GetNewSize() <= 0) return false;
5957            if (_3crc->GetNewSize() % 8) return false;
5958            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5959            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5960    
5961            const file_offset_t n = _3crc->GetNewSize() / 8;
5962    
5963            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5964            if (!pData) return false;
5965    
5966            for (file_offset_t i = 0; i < n; ++i) {
5967                uint32_t one = pData[i*2];
5968                if (one != 1) return false;
5969            }
5970    
5971            return true;
5972        }
5973    
5974        /**
5975         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5976         * file's checksum table with those new checksums. This might usually
5977         * just be necessary if the checksum table was damaged.
5978         *
5979         * @e IMPORTANT: The current implementation of this method only works
5980         * with files that have not been modified since it was loaded, because
5981         * it expects that no externally caused file structure changes are
5982         * required!
5983         *
5984         * Due to the expectation above, this method is currently protected
5985         * and actually only used by the command line tool "gigdump" yet.
5986         *
5987         * @returns true if Save() is required to be called after this call,
5988         *          false if no further action is required
5989         */
5990        bool File::RebuildSampleChecksumTable() {
5991            // make sure sample chunks were scanned
5992            if (!pSamples) GetFirstSample();
5993    
5994            bool bRequiresSave = false;
5995    
5996            // make sure "3CRC" chunk exists with required size
5997            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5998            if (!_3crc) {
5999                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6000                // the order of einf and 3crc is not the same in v2 and v3
6001                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
6002                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6003                bRequiresSave = true;
6004            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
6005                _3crc->Resize(pSamples->size() * 8);
6006                bRequiresSave = true;
6007            }
6008    
6009            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
6010                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6011                {
6012                    File::SampleList::iterator iter = pSamples->begin();
6013                    File::SampleList::iterator end  = pSamples->end();
6014                    for (; iter != end; ++iter) {
6015                        gig::Sample* pSample = (gig::Sample*) *iter;
6016                        int index = GetWaveTableIndexOf(pSample);
6017                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
6018                        pData[index*2]   = 1; // always 1
6019                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
6020                    }
6021                }
6022            } else { // no file structure changes necessary, so directly write to disk and we are done ...
6023                // make sure file is in write mode
6024                pRIFF->SetMode(RIFF::stream_mode_read_write);
6025                {
6026                    File::SampleList::iterator iter = pSamples->begin();
6027                    File::SampleList::iterator end  = pSamples->end();
6028                    for (; iter != end; ++iter) {
6029                        gig::Sample* pSample = (gig::Sample*) *iter;
6030                        int index = GetWaveTableIndexOf(pSample);
6031                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
6032                        pSample->crc  = pSample->CalculateWaveDataChecksum();
6033                        SetSampleChecksum(pSample, pSample->crc);
6034                    }
6035                }
6036            }
6037    
6038            return bRequiresSave;
6039        }
6040    
6041      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
6042          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
6043          // there must always be at least one group          // there must always be at least one group
# Line 3665  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6067  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6067          return NULL;          return NULL;
6068      }      }
6069    
6070        /**
6071         * Returns the group with the given group name.
6072         *
6073         * Note: group names don't have to be unique in the gig format! So there
6074         * can be multiple groups with the same name. This method will simply
6075         * return the first group found with the given name.
6076         *
6077         * @param name - name of the sought group
6078         * @returns sought group or NULL if there's no group with that name
6079         */
6080        Group* File::GetGroup(String name) {
6081            if (!pGroups) LoadGroups();
6082            GroupsIterator = pGroups->begin();
6083            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
6084                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
6085            return NULL;
6086        }
6087    
6088      Group* File::AddGroup() {      Group* File::AddGroup() {
6089          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
6090          // there must always be at least one group          // there must always be at least one group
# Line 3745  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6165  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6165          }          }
6166      }      }
6167    
6168        /** @brief Get instrument script group (by index).
6169         *
6170         * Returns the real-time instrument script group with the given index.
6171         *
6172         * @param index - number of the sought group (0..n)
6173         * @returns sought script group or NULL if there's no such group
6174         */
6175        ScriptGroup* File::GetScriptGroup(uint index) {
6176            if (!pScriptGroups) LoadScriptGroups();
6177            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6178            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6179                if (i == index) return *it;
6180            return NULL;
6181        }
6182    
6183        /** @brief Get instrument script group (by name).
6184         *
6185         * Returns the first real-time instrument script group found with the given
6186         * group name. Note that group names may not necessarily be unique.
6187         *
6188         * @param name - name of the sought script group
6189         * @returns sought script group or NULL if there's no such group
6190         */
6191        ScriptGroup* File::GetScriptGroup(const String& name) {
6192            if (!pScriptGroups) LoadScriptGroups();
6193            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6194            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6195                if ((*it)->Name == name) return *it;
6196            return NULL;
6197        }
6198    
6199        /** @brief Add new instrument script group.
6200         *
6201         * Adds a new, empty real-time instrument script group to the file.
6202         *
6203         * You have to call Save() to make this persistent to the file.
6204         *
6205         * @return new empty script group
6206         */
6207        ScriptGroup* File::AddScriptGroup() {
6208            if (!pScriptGroups) LoadScriptGroups();
6209            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6210            pScriptGroups->push_back(pScriptGroup);
6211            return pScriptGroup;
6212        }
6213    
6214        /** @brief Delete an instrument script group.
6215         *
6216         * This will delete the given real-time instrument script group and all its
6217         * instrument scripts it contains. References inside instruments that are
6218         * using the deleted scripts will be removed from the respective instruments
6219         * accordingly.
6220         *
6221         * You have to call Save() to make this persistent to the file.
6222         *
6223         * @param pScriptGroup - script group to delete
6224         * @throws gig::Exception if given script group could not be found
6225         */
6226        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6227            if (!pScriptGroups) LoadScriptGroups();
6228            std::list<ScriptGroup*>::iterator iter =
6229                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6230            if (iter == pScriptGroups->end())
6231                throw gig::Exception("Could not delete script group, could not find given script group");
6232            pScriptGroups->erase(iter);
6233            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6234                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6235            if (pScriptGroup->pList)
6236                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6237            delete pScriptGroup;
6238        }
6239    
6240        void File::LoadScriptGroups() {
6241            if (pScriptGroups) return;
6242            pScriptGroups = new std::list<ScriptGroup*>;
6243            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6244            if (lstLS) {
6245                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6246                     lst = lstLS->GetNextSubList())
6247                {
6248                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6249                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6250                    }
6251                }
6252            }
6253        }
6254    
6255      /**      /**
6256       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6257       * to the respective RIFF chunks. You have to call Save() to make changes       * to the respective RIFF chunks. You have to call Save() to make changes
# Line 3753  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6260  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6260       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6261       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6262       *       *
6263         * @param pProgress - callback function for progress notification
6264       * @throws Exception - on errors       * @throws Exception - on errors
6265       */       */
6266      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6267          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6268    
6269          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6270            // (not part of the GigaStudio 4 format)
6271            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6272            if (!lst3LS) {
6273                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6274            }
6275            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6276            // location of <3LS > is irrelevant, however it should be located
6277            // before  the actual wave data
6278            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6279            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6280    
6281            // This must be performed before writing the chunks for instruments,
6282            // because the instruments' script slots will write the file offsets
6283            // of the respective instrument script chunk as reference.
6284            if (pScriptGroups) {
6285                // Update instrument script (group) chunks.
6286                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6287                     it != pScriptGroups->end(); ++it)
6288                {
6289                    (*it)->UpdateChunks(pProgress);
6290                }
6291            }
6292    
6293            // in case no libgig custom format data was added, then remove the
6294            // custom "3LS " chunk again
6295            if (!lst3LS->CountSubChunks()) {
6296                pRIFF->DeleteSubChunk(lst3LS);
6297                lst3LS = NULL;
6298            }
6299    
6300          // first update base class's chunks          // first update base class's chunks
6301          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6302    
6303          if (newFile) {          if (newFile) {
6304              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 3775  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6312  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6312    
6313          // update group's chunks          // update group's chunks
6314          if (pGroups) {          if (pGroups) {
6315              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
6316              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
6317              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6318                  (*iter)->UpdateChunks();              if (!_3gri) {
6319                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6320                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6321              }              }
6322                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6323                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6324    
6325              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
6326                // (before updating the Group chunks)
6327              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
6328                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6329                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
6330                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6331                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6332                  }                  }
6333              }              }
6334    
6335                std::list<Group*>::iterator iter = pGroups->begin();
6336                std::list<Group*>::iterator end  = pGroups->end();
6337                for (; iter != end; ++iter) {
6338                    (*iter)->UpdateChunks(pProgress);
6339                }
6340          }          }
6341    
6342          // update einf chunk          // update einf chunk
# Line 3808  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6355  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6355          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6356          // are set to zero.          // are set to zero.
6357    
6358          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6359          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6360    
6361          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 3881  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6428  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6428                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6429                  // next 8 bytes unknown                  // next 8 bytes unknown
6430                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6431                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6432                  // next 4 bytes unknown                  // next 4 bytes unknown
6433    
6434                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 3899  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6446  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6446              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6447              // next 8 bytes unknown              // next 8 bytes unknown
6448              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6449              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6450              // next 4 bytes unknown              // next 4 bytes unknown
6451          }          }
6452    
6453          // update 3crc chunk          // update 3crc chunk
6454    
6455          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6456          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6457          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6458            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6459            // member variable). This step is required, because samples might have
6460            // been deleted by the user since the file was opened, which in turn
6461            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6462            // If a sample was conciously modified by the user (that is if
6463            // Sample::Write() was called later on) then Sample::Write() will just
6464            // update the respective individual checksum(s) directly on disk and
6465            // leaves all other sample checksums untouched.
6466    
6467          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6468          if (_3crc) {          if (_3crc) {
6469              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6470          } else if (newFile) {          } else /*if (newFile)*/ {
6471              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6472              // the order of einf and 3crc is not the same in v2 and v3              // the order of einf and 3crc is not the same in v2 and v3
6473              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6474          }          }
6475            { // must be performed in RAM here ...
6476                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6477                if (pData) {
6478                    File::SampleList::iterator iter = pSamples->begin();
6479                    File::SampleList::iterator end  = pSamples->end();
6480                    for (int index = 0; iter != end; ++iter, ++index) {
6481                        gig::Sample* pSample = (gig::Sample*) *iter;
6482                        pData[index*2]   = 1; // always 1
6483                        pData[index*2+1] = pSample->crc;
6484                    }
6485                }
6486            }
6487        }
6488        
6489        void File::UpdateFileOffsets() {
6490            DLS::File::UpdateFileOffsets();
6491    
6492            for (Instrument* instrument = GetFirstInstrument(); instrument;
6493                 instrument = GetNextInstrument())
6494            {
6495                instrument->UpdateScriptFileOffsets();
6496            }
6497      }      }
6498    
6499      /**      /**
# Line 3953  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger Line 6528  MidiRuleCtrlTrigger::MidiRuleCtrlTrigger
6528  // *************** Exception ***************  // *************** Exception ***************
6529  // *  // *
6530    
6531      Exception::Exception(String Message) : DLS::Exception(Message) {      Exception::Exception() : DLS::Exception() {
6532        }
6533    
6534        Exception::Exception(String format, ...) : DLS::Exception() {
6535            va_list arg;
6536            va_start(arg, format);
6537            Message = assemble(format, arg);
6538            va_end(arg);
6539        }
6540    
6541        Exception::Exception(String format, va_list arg) : DLS::Exception() {
6542            Message = assemble(format, arg);
6543      }      }
6544    
6545      void Exception::PrintMessage() {      void Exception::PrintMessage() {

Legend:
Removed from v.1875  
changed lines
  Added in v.3323

  ViewVC Help
Powered by ViewVC