/[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 1335 by schoenebeck, Sun Sep 9 21:22:58 2007 UTC revision 3138 by schoenebeck, Wed May 3 14:41:58 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-2007 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 25  Line 25 
25    
26  #include "helper.h"  #include "helper.h"
27    
28    #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33    /// libgig's current file format version (for extending the original Giga file
34    /// format with libgig's own custom data / custom features).
35    #define GIG_FILE_EXT_VERSION    2
36    
37  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
38  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 49  Line 55 
55  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)  #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
56  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)  #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
57    
58  namespace gig {  #define SRLZ(member) \
59        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;  
         }  
     }  
60    
61    namespace gig {
62    
63  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
64  // *  // *
# Line 121  namespace { Line 98  namespace {
98      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
99                        int srcStep, int dstStep,                        int srcStep, int dstStep,
100                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
101                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
102                        unsigned long copysamples)                        file_offset_t copysamples)
103      {      {
104          switch (compressionmode) {          switch (compressionmode) {
105              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 158  namespace { Line 135  namespace {
135    
136      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
137                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
138                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
139                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
140      {      {
141          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
142    
# Line 255  namespace { Line 232  namespace {
232    
233    
234    
235    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
236    // *
237    
238        static uint32_t* __initCRCTable() {
239            static uint32_t res[256];
240    
241            for (int i = 0 ; i < 256 ; i++) {
242                uint32_t c = i;
243                for (int j = 0 ; j < 8 ; j++) {
244                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
245                }
246                res[i] = c;
247            }
248            return res;
249        }
250    
251        static const uint32_t* __CRCTable = __initCRCTable();
252    
253        /**
254         * Initialize a CRC variable.
255         *
256         * @param crc - variable to be initialized
257         */
258        inline static void __resetCRC(uint32_t& crc) {
259            crc = 0xffffffff;
260        }
261    
262        /**
263         * Used to calculate checksums of the sample data in a gig file. The
264         * checksums are stored in the 3crc chunk of the gig file and
265         * automatically updated when a sample is written with Sample::Write().
266         *
267         * One should call __resetCRC() to initialize the CRC variable to be
268         * used before calling this function the first time.
269         *
270         * After initializing the CRC variable one can call this function
271         * arbitrary times, i.e. to split the overall CRC calculation into
272         * steps.
273         *
274         * Once the whole data was processed by __calculateCRC(), one should
275         * call __finalizeCRC() to get the final CRC result.
276         *
277         * @param buf     - pointer to data the CRC shall be calculated of
278         * @param bufSize - size of the data to be processed
279         * @param crc     - variable the CRC sum shall be stored to
280         */
281        static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
282            for (size_t i = 0 ; i < bufSize ; i++) {
283                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
284            }
285        }
286    
287        /**
288         * Returns the final CRC result.
289         *
290         * @param crc - variable previously passed to __calculateCRC()
291         */
292        inline static void __finalizeCRC(uint32_t& crc) {
293            crc ^= 0xffffffff;
294        }
295    
296    
297    
298  // *************** Other Internal functions  ***************  // *************** Other Internal functions  ***************
299  // *  // *
300    
# Line 278  namespace { Line 318  namespace {
318    
319    
320    
321  // *************** CRC ***************  // *************** leverage_ctrl_t ***************
322  // *  // *
323    
324      const uint32_t* CRC::table(initTable());      void leverage_ctrl_t::serialize(Serialization::Archive* archive) {
325            SRLZ(type);
326            SRLZ(controller_number);
327        }
328    
     uint32_t* CRC::initTable() {  
         uint32_t* res = new uint32_t[256];  
329    
330          for (int i = 0 ; i < 256 ; i++) {  
331              uint32_t c = i;  // *************** crossfade_t ***************
332              for (int j = 0 ; j < 8 ; j++) {  // *
333                  c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;  
334              }      void crossfade_t::serialize(Serialization::Archive* archive) {
335              res[i] = c;          SRLZ(in_start);
336          }          SRLZ(in_end);
337          return res;          SRLZ(out_start);
338            SRLZ(out_end);
339      }      }
340    
341    
# Line 301  namespace { Line 343  namespace {
343  // *************** Sample ***************  // *************** Sample ***************
344  // *  // *
345    
346      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
347      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
348    
349      /** @brief Constructor.      /** @brief Constructor.
# Line 321  namespace { Line 363  namespace {
363       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
364       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
365       *                         is located, 0 otherwise       *                         is located, 0 otherwise
366         * @param index          - wave pool index of sample (may be -1 on new sample)
367       */       */
368      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)
369          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
370        {
371            static const DLS::Info::string_length_t fixedStringLengths[] = {
372              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
373              { 0, 0 }              { 0, 0 }
374          };          };
375          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
376          Instances++;          Instances++;
377          FileNo = fileNo;          FileNo = fileNo;
378    
379            __resetCRC(crc);
380            // if this is not a new sample, try to get the sample's already existing
381            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
382            // checksum of the time when the sample was consciously modified by the
383            // user for the last time (by calling Sample::Write() that is).
384            if (index >= 0) { // not a new file ...
385                try {
386                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
387                    this->crc = crc;
388                } catch (...) {}
389            }
390    
391          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
392          if (pCk3gix) {          if (pCk3gix) {
393              uint16_t iSampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
# Line 408  namespace { Line 465  namespace {
465      }      }
466    
467      /**      /**
468         * Make a (semi) deep copy of the Sample object given by @a orig (without
469         * the actual waveform data) and assign it to this object.
470         *
471         * Discussion: copying .gig samples is a bit tricky. It requires three
472         * steps:
473         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
474         *    its new sample waveform data size.
475         * 2. Saving the file (done by File::Save()) so that it gains correct size
476         *    and layout for writing the actual wave form data directly to disc
477         *    in next step.
478         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
479         *
480         * @param orig - original Sample object to be copied from
481         */
482        void Sample::CopyAssignMeta(const Sample* orig) {
483            // handle base classes
484            DLS::Sample::CopyAssignCore(orig);
485            
486            // handle actual own attributes of this class
487            Manufacturer = orig->Manufacturer;
488            Product = orig->Product;
489            SamplePeriod = orig->SamplePeriod;
490            MIDIUnityNote = orig->MIDIUnityNote;
491            FineTune = orig->FineTune;
492            SMPTEFormat = orig->SMPTEFormat;
493            SMPTEOffset = orig->SMPTEOffset;
494            Loops = orig->Loops;
495            LoopID = orig->LoopID;
496            LoopType = orig->LoopType;
497            LoopStart = orig->LoopStart;
498            LoopEnd = orig->LoopEnd;
499            LoopSize = orig->LoopSize;
500            LoopFraction = orig->LoopFraction;
501            LoopPlayCount = orig->LoopPlayCount;
502            
503            // schedule resizing this sample to the given sample's size
504            Resize(orig->GetSize());
505        }
506    
507        /**
508         * Should be called after CopyAssignMeta() and File::Save() sequence.
509         * Read more about it in the discussion of CopyAssignMeta(). This method
510         * copies the actual waveform data by disk streaming.
511         *
512         * @e CAUTION: this method is currently not thread safe! During this
513         * operation the sample must not be used for other purposes by other
514         * threads!
515         *
516         * @param orig - original Sample object to be copied from
517         */
518        void Sample::CopyAssignWave(const Sample* orig) {
519            const int iReadAtOnce = 32*1024;
520            char* buf = new char[iReadAtOnce * orig->FrameSize];
521            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
522            file_offset_t restorePos = pOrig->GetPos();
523            pOrig->SetPos(0);
524            SetPos(0);
525            for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
526                               n = pOrig->Read(buf, iReadAtOnce))
527            {
528                Write(buf, n);
529            }
530            pOrig->SetPos(restorePos);
531            delete [] buf;
532        }
533    
534        /**
535       * Apply sample and its settings to the respective RIFF chunks. You have       * Apply sample and its settings to the respective RIFF chunks. You have
536       * to call File::Save() to make changes persistent.       * to call File::Save() to make changes persistent.
537       *       *
538       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
539       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
540       *       *
541         * @param pProgress - callback function for progress notification
542       * @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
543       *                        was provided yet       *                        was provided yet
544       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
545       */       */
546      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
547          // first update base class's chunks          // first update base class's chunks
548          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
549    
550          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
551          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 468  namespace { Line 593  namespace {
593          // update '3gix' chunk          // update '3gix' chunk
594          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
595          store16(&pData[0], iSampleGroup);          store16(&pData[0], iSampleGroup);
596    
597            // if the library user toggled the "Compressed" attribute from true to
598            // false, then the EWAV chunk associated with compressed samples needs
599            // to be deleted
600            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
601            if (ewav && !Compressed) {
602                pWaveList->DeleteSubChunk(ewav);
603            }
604      }      }
605    
606      /// 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).
607      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
608          //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)
609          this->SamplesTotal = 0;          this->SamplesTotal = 0;
610          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
611    
612          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
613          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 490  namespace { Line 623  namespace {
623                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
624                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
625                  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");
626                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
627    
628                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
629                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 509  namespace { Line 642  namespace {
642    
643                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
644                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
645                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
646    
647                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
648                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 525  namespace { Line 658  namespace {
658    
659          // 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)
660          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
661          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
662          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
663          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
664          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
665              FrameTable[i] = *iter;              FrameTable[i] = *iter;
666          }          }
# Line 568  namespace { Line 701  namespace {
701       *                      the cached sample data in bytes       *                      the cached sample data in bytes
702       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
703       */       */
704      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
705          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
706      }      }
707    
# Line 627  namespace { Line 760  namespace {
760       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
761       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
762       */       */
763      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
764          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
765          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
766          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
767            SetPos(0); // reset read position to begin of sample
768          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
769          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
770          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 668  namespace { Line 802  namespace {
802          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
803          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
804          RAMCache.Size   = 0;          RAMCache.Size   = 0;
805            RAMCache.NullExtensionSize = 0;
806      }      }
807    
808      /** @brief Resize sample.      /** @brief Resize sample.
# Line 692  namespace { Line 827  namespace {
827       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
828       * other formats will fail!       * other formats will fail!
829       *       *
830       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
831       *                   greater than zero)       *                  greater than zero)
832       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
833       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
834       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
835       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
836       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
837       */       */
838      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
839          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)");
840          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
841      }      }
842    
843      /**      /**
# Line 726  namespace { Line 861  namespace {
861       * @returns            the new sample position       * @returns            the new sample position
862       * @see                Read()       * @see                Read()
863       */       */
864      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) {
865          if (Compressed) {          if (Compressed) {
866              switch (Whence) {              switch (Whence) {
867                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 744  namespace { Line 879  namespace {
879              }              }
880              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
881    
882              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
883              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
884              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
885              return this->SamplePos;              return this->SamplePos;
886          }          }
887          else { // not compressed          else { // not compressed
888              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
889              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
890              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
891                                              : result / this->FrameSize;                                              : result / this->FrameSize;
892          }          }
# Line 760  namespace { Line 895  namespace {
895      /**      /**
896       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
897       */       */
898      unsigned long Sample::GetPos() {      file_offset_t Sample::GetPos() const {
899          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
900          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
901      }      }
# Line 799  namespace { Line 934  namespace {
934       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
935       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
936       */       */
937      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,
938                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
939          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
940          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
941    
942          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 839  namespace { Line 974  namespace {
974                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
975                                  // backward playback                                  // backward playback
976    
977                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
978                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
979                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
980                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
981    
982                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
983    
# Line 862  namespace { Line 997  namespace {
997                                  }                                  }
998    
999                                  // reverse the sample frames for backward playback                                  // reverse the sample frames for backward playback
1000                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                                  if (totalreadsamples > swapareastart) //FIXME: this if() is just a crash workaround for now (#102), but totalreadsamples <= swapareastart should never be the case, so there's probably still a bug above!
1001                                        SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1002                              }                              }
1003                          } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1004                          break;                          break;
# Line 889  namespace { Line 1025  namespace {
1025                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1026                          // backward playback                          // backward playback
1027    
1028                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1029                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1030                          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)
1031                                                                                    : samplestoread;                                                                                    : samplestoread;
1032                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1033    
1034                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1035    
# Line 973  namespace { Line 1109  namespace {
1109       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1110       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1111       */       */
1112      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) {
1113          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1114          if (!Compressed) {          if (!Compressed) {
1115              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 988  namespace { Line 1124  namespace {
1124          else {          else {
1125              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1126              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1127              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1128                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1129                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1130                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1011  namespace { Line 1147  namespace {
1147              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1148    
1149              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1150                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1151                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1152    
1153                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1154    
# Line 1162  namespace { Line 1298  namespace {
1298       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1299       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1300       */       */
1301      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1302          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)");
1303    
1304          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
1305          // checksum calculator          // checksum calculator
1306          if (pCkData->GetPos() == 0) {          if (pCkData->GetPos() == 0) {
1307              crc.reset();              __resetCRC(crc);
1308          }          }
1309          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");
1310          unsigned long res;          file_offset_t res;
1311          if (BitDepth == 24) {          if (BitDepth == 24) {
1312              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1313          } else { // 16 bit          } else { // 16 bit
1314              res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1              res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1315                                  : pCkData->Write(pBuffer, SampleCount, 2);                                  : pCkData->Write(pBuffer, SampleCount, 2);
1316          }          }
1317          crc.update((unsigned char *)pBuffer, SampleCount * FrameSize);          __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1318    
1319          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1320          // file          // file
1321          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1322                __finalizeCRC(crc);
1323              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1324              pFile->SetSampleChecksum(this, crc.getValue());              pFile->SetSampleChecksum(this, crc);
1325          }          }
1326          return res;          return res;
1327      }      }
# Line 1205  namespace { Line 1342  namespace {
1342       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1343       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1344       */       */
1345      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1346          buffer_t result;          buffer_t result;
1347          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1348                  (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;
1349          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);
1350          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1351          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1352          return result;          return result;
# Line 1243  namespace { Line 1380  namespace {
1380          return pGroup;          return pGroup;
1381      }      }
1382    
1383        /**
1384         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1385         * time when this sample's wave form data was modified for the last time
1386         * by calling Write(). This checksum only covers the raw wave form data,
1387         * not any meta informations like i.e. bit depth or loop points. Since
1388         * this method just returns the checksum stored for this sample i.e. when
1389         * the gig file was loaded, this method returns immediately. So it does no
1390         * recalcuation of the checksum with the currently available sample wave
1391         * form data.
1392         *
1393         * @see VerifyWaveData()
1394         */
1395        uint32_t Sample::GetWaveDataCRC32Checksum() {
1396            return crc;
1397        }
1398    
1399        /**
1400         * Checks the integrity of this sample's raw audio wave data. Whenever a
1401         * Sample's raw wave data is intentionally modified (i.e. by calling
1402         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1403         * is calculated and stored/updated for this sample, along to the sample's
1404         * meta informations.
1405         *
1406         * Now by calling this method the current raw audio wave data is checked
1407         * against the already stored CRC32 check sum in order to check whether the
1408         * sample data had been damaged unintentionally for some reason. Since by
1409         * calling this method always the entire raw audio wave data has to be
1410         * read, verifying all samples this way may take a long time accordingly.
1411         * And that's also the reason why the sample integrity is not checked by
1412         * default whenever a gig file is loaded. So this method must be called
1413         * explicitly to fulfill this task.
1414         *
1415         * @param pActually - (optional) if provided, will be set to the actually
1416         *                    calculated checksum of the current raw wave form data,
1417         *                    you can get the expected checksum instead by calling
1418         *                    GetWaveDataCRC32Checksum()
1419         * @returns true if sample is OK or false if the sample is damaged
1420         * @throws Exception if no checksum had been stored to disk for this
1421         *         sample yet, or on I/O issues
1422         * @see GetWaveDataCRC32Checksum()
1423         */
1424        bool Sample::VerifyWaveData(uint32_t* pActually) {
1425            //File* pFile = static_cast<File*>(GetParent());
1426            uint32_t crc = CalculateWaveDataChecksum();
1427            if (pActually) *pActually = crc;
1428            return crc == this->crc;
1429        }
1430    
1431        uint32_t Sample::CalculateWaveDataChecksum() {
1432            const size_t sz = 20*1024; // 20kB buffer size
1433            std::vector<uint8_t> buffer(sz);
1434            buffer.resize(sz);
1435    
1436            const size_t n = sz / FrameSize;
1437            SetPos(0);
1438            uint32_t crc = 0;
1439            __resetCRC(crc);
1440            while (true) {
1441                file_offset_t nRead = Read(&buffer[0], n);
1442                if (nRead <= 0) break;
1443                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1444            }
1445            __finalizeCRC(crc);
1446            return crc;
1447        }
1448    
1449      Sample::~Sample() {      Sample::~Sample() {
1450          Instances--;          Instances--;
1451          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1259  namespace { Line 1462  namespace {
1462  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1463  // *  // *
1464    
1465      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1466      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1467    
1468      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1384  namespace { Line 1587  namespace {
1587                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1588              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1589              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1590                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1591              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1592              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1593              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1453  namespace { Line 1656  namespace {
1656              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1657              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1658              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1659              EG2Release                      = 0.3;              EG2Release                      = 60;
1660              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1661              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1662              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1512  namespace { Line 1715  namespace {
1715                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1716                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1717    
1718          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1719          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1720                                        ReleaseVelocityResponseDepth
1721          // this models a strange behaviour or bug in GSt: two of the                                  );
1722          // velocity response curves for release time are not used even  
1723          // if specified, instead another curve is chosen.          pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1724          if ((curveType == curve_type_nonlinear && depth == 0) ||                                                        VCFVelocityDynamicRange,
1725              (curveType == curve_type_special   && depth == 4)) {                                                        VCFVelocityScale,
1726              curveType = curve_type_nonlinear;                                                        VCFCutoffController);
             depth = 3;  
         }  
         pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);  
   
         curveType = VCFVelocityCurve;  
         depth = VCFVelocityDynamicRange;  
   
         // even stranger GSt: two of the velocity response curves for  
         // filter cutoff are not used, instead another special curve  
         // is chosen. This curve is not used anywhere else.  
         if ((curveType == curve_type_nonlinear && depth == 0) ||  
             (curveType == curve_type_special   && depth == 4)) {  
             curveType = curve_type_special;  
             depth = 5;  
         }  
         pVelocityCutoffTable = GetVelocityTable(curveType, depth,  
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1727    
1728          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1729          VelocityTable = 0;          VelocityTable = 0;
# Line 1549  namespace { Line 1735  namespace {
1735       */       */
1736      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1737          Instances++;          Instances++;
1738            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1739          *this = src; // default memberwise shallow copy of all parameters          *this = src; // default memberwise shallow copy of all parameters
1740          pParentList = _3ewl; // restore the chunk pointer          pParentList = _3ewl; // restore the chunk pointer
1741    
# Line 1564  namespace { Line 1751  namespace {
1751                  pSampleLoops[k] = src.pSampleLoops[k];                  pSampleLoops[k] = src.pSampleLoops[k];
1752          }          }
1753      }      }
1754        
1755        /**
1756         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1757         * and assign it to this object.
1758         *
1759         * Note that all sample pointers referenced by @a orig are simply copied as
1760         * memory address. Thus the respective samples are shared, not duplicated!
1761         *
1762         * @param orig - original DimensionRegion object to be copied from
1763         */
1764        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1765            CopyAssign(orig, NULL);
1766        }
1767    
1768        /**
1769         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1770         * and assign it to this object.
1771         *
1772         * @param orig - original DimensionRegion object to be copied from
1773         * @param mSamples - crosslink map between the foreign file's samples and
1774         *                   this file's samples
1775         */
1776        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1777            // delete all allocated data first
1778            if (VelocityTable) delete [] VelocityTable;
1779            if (pSampleLoops) delete [] pSampleLoops;
1780            
1781            // backup parent list pointer
1782            RIFF::List* p = pParentList;
1783            
1784            gig::Sample* pOriginalSample = pSample;
1785            gig::Region* pOriginalRegion = pRegion;
1786            
1787            //NOTE: copy code copied from assignment constructor above, see comment there as well
1788            
1789            *this = *orig; // default memberwise shallow copy of all parameters
1790            
1791            // restore members that shall not be altered
1792            pParentList = p; // restore the chunk pointer
1793            pRegion = pOriginalRegion;
1794            
1795            // only take the raw sample reference reference if the
1796            // two DimensionRegion objects are part of the same file
1797            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1798                pSample = pOriginalSample;
1799            }
1800            
1801            if (mSamples && mSamples->count(orig->pSample)) {
1802                pSample = mSamples->find(orig->pSample)->second;
1803            }
1804    
1805            // deep copy of owned structures
1806            if (orig->VelocityTable) {
1807                VelocityTable = new uint8_t[128];
1808                for (int k = 0 ; k < 128 ; k++)
1809                    VelocityTable[k] = orig->VelocityTable[k];
1810            }
1811            if (orig->pSampleLoops) {
1812                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1813                for (int k = 0 ; k < orig->SampleLoops ; k++)
1814                    pSampleLoops[k] = orig->pSampleLoops[k];
1815            }
1816        }
1817    
1818        void DimensionRegion::serialize(Serialization::Archive* archive) {
1819            SRLZ(VelocityUpperLimit);
1820            SRLZ(EG1PreAttack);
1821            SRLZ(EG1Attack);
1822            SRLZ(EG1Decay1);
1823            SRLZ(EG1Decay2);
1824            SRLZ(EG1InfiniteSustain);
1825            SRLZ(EG1Sustain);
1826            SRLZ(EG1Release);
1827            SRLZ(EG1Hold);
1828            SRLZ(EG1Controller);
1829            SRLZ(EG1ControllerInvert);
1830            SRLZ(EG1ControllerAttackInfluence);
1831            SRLZ(EG1ControllerDecayInfluence);
1832            SRLZ(EG1ControllerReleaseInfluence);
1833            SRLZ(LFO1Frequency);
1834            SRLZ(LFO1InternalDepth);
1835            SRLZ(LFO1ControlDepth);
1836            SRLZ(LFO1Controller);
1837            SRLZ(LFO1FlipPhase);
1838            SRLZ(LFO1Sync);
1839            SRLZ(EG2PreAttack);
1840            SRLZ(EG2Attack);
1841            SRLZ(EG2Decay1);
1842            SRLZ(EG2Decay2);
1843            SRLZ(EG2InfiniteSustain);
1844            SRLZ(EG2Sustain);
1845            SRLZ(EG2Release);
1846            SRLZ(EG2Controller);
1847            SRLZ(EG2ControllerInvert);
1848            SRLZ(EG2ControllerAttackInfluence);
1849            SRLZ(EG2ControllerDecayInfluence);
1850            SRLZ(EG2ControllerReleaseInfluence);
1851            SRLZ(LFO2Frequency);
1852            SRLZ(LFO2InternalDepth);
1853            SRLZ(LFO2ControlDepth);
1854            SRLZ(LFO2Controller);
1855            SRLZ(LFO2FlipPhase);
1856            SRLZ(LFO2Sync);
1857            SRLZ(EG3Attack);
1858            SRLZ(EG3Depth);
1859            SRLZ(LFO3Frequency);
1860            SRLZ(LFO3InternalDepth);
1861            SRLZ(LFO3ControlDepth);
1862            SRLZ(LFO3Controller);
1863            SRLZ(LFO3Sync);
1864            SRLZ(VCFEnabled);
1865            SRLZ(VCFType);
1866            SRLZ(VCFCutoffController);
1867            SRLZ(VCFCutoffControllerInvert);
1868            SRLZ(VCFCutoff);
1869            SRLZ(VCFVelocityCurve);
1870            SRLZ(VCFVelocityScale);
1871            SRLZ(VCFVelocityDynamicRange);
1872            SRLZ(VCFResonance);
1873            SRLZ(VCFResonanceDynamic);
1874            SRLZ(VCFResonanceController);
1875            SRLZ(VCFKeyboardTracking);
1876            SRLZ(VCFKeyboardTrackingBreakpoint);
1877            SRLZ(VelocityResponseCurve);
1878            SRLZ(VelocityResponseDepth);
1879            SRLZ(VelocityResponseCurveScaling);
1880            SRLZ(ReleaseVelocityResponseCurve);
1881            SRLZ(ReleaseVelocityResponseDepth);
1882            SRLZ(ReleaseTriggerDecay);
1883            SRLZ(Crossfade);
1884            SRLZ(PitchTrack);
1885            SRLZ(DimensionBypass);
1886            SRLZ(Pan);
1887            SRLZ(SelfMask);
1888            SRLZ(AttenuationController);
1889            SRLZ(InvertAttenuationController);
1890            SRLZ(AttenuationControllerThreshold);
1891            SRLZ(ChannelOffset);
1892            SRLZ(SustainDefeat);
1893            SRLZ(MSDecode);
1894            //SRLZ(SampleStartOffset);
1895            SRLZ(SampleAttenuation);
1896    
1897            // derived attributes from DLS::Sampler
1898            SRLZ(FineTune);
1899            SRLZ(Gain);
1900        }
1901    
1902        /**
1903         * Updates the respective member variable and updates @c SampleAttenuation
1904         * which depends on this value.
1905         */
1906        void DimensionRegion::SetGain(int32_t gain) {
1907            DLS::Sampler::SetGain(gain);
1908            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1909        }
1910    
1911      /**      /**
1912       * Apply dimension region settings to the respective RIFF chunks. You       * Apply dimension region settings to the respective RIFF chunks. You
# Line 1571  namespace { Line 1914  namespace {
1914       *       *
1915       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1916       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1917         *
1918         * @param pProgress - callback function for progress notification
1919       */       */
1920      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1921          // first update base class's chunk          // first update base class's chunk
1922          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1923    
1924          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1925          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 1594  namespace { Line 1939  namespace {
1939    
1940          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1941    
1942          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1943          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1944    
1945          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 1796  namespace { Line 2141  namespace {
2141          }          }
2142    
2143          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
2144                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
2145          pData[116] = eg3depth;          store16(&pData[116], eg3depth);
2146    
2147          // next 2 bytes unknown          // next 2 bytes unknown
2148    
# Line 1844  namespace { Line 2189  namespace {
2189                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
2190          pData[137] = vcfbreakpoint;          pData[137] = vcfbreakpoint;
2191    
2192          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2193                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2194          pData[138] = vcfvelocity;          pData[138] = vcfvelocity;
2195    
# Line 1856  namespace { Line 2201  namespace {
2201          }          }
2202      }      }
2203    
2204        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2205            curve_type_t curveType = releaseVelocityResponseCurve;
2206            uint8_t depth = releaseVelocityResponseDepth;
2207            // this models a strange behaviour or bug in GSt: two of the
2208            // velocity response curves for release time are not used even
2209            // if specified, instead another curve is chosen.
2210            if ((curveType == curve_type_nonlinear && depth == 0) ||
2211                (curveType == curve_type_special   && depth == 4)) {
2212                curveType = curve_type_nonlinear;
2213                depth = 3;
2214            }
2215            return GetVelocityTable(curveType, depth, 0);
2216        }
2217    
2218        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2219                                                        uint8_t vcfVelocityDynamicRange,
2220                                                        uint8_t vcfVelocityScale,
2221                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2222        {
2223            curve_type_t curveType = vcfVelocityCurve;
2224            uint8_t depth = vcfVelocityDynamicRange;
2225            // even stranger GSt: two of the velocity response curves for
2226            // filter cutoff are not used, instead another special curve
2227            // is chosen. This curve is not used anywhere else.
2228            if ((curveType == curve_type_nonlinear && depth == 0) ||
2229                (curveType == curve_type_special   && depth == 4)) {
2230                curveType = curve_type_special;
2231                depth = 5;
2232            }
2233            return GetVelocityTable(curveType, depth,
2234                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2235                                        ? vcfVelocityScale : 0);
2236        }
2237    
2238      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
2239      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
2240      {      {
# Line 1875  namespace { Line 2254  namespace {
2254          return pRegion;          return pRegion;
2255      }      }
2256    
2257    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2258    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2259    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2260    //#pragma GCC diagnostic push
2261    //#pragma GCC diagnostic error "-Wswitch"
2262    
2263      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2264          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2265          switch (EncodedController) {          switch (EncodedController) {
# Line 1986  namespace { Line 2371  namespace {
2371                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2372                  break;                  break;
2373    
2374                // format extension (these controllers are so far only supported by
2375                // LinuxSampler & gigedit) they will *NOT* work with
2376                // Gigasampler/GigaStudio !
2377                case _lev_ctrl_CC3_EXT:
2378                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2379                    decodedcontroller.controller_number = 3;
2380                    break;
2381                case _lev_ctrl_CC6_EXT:
2382                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2383                    decodedcontroller.controller_number = 6;
2384                    break;
2385                case _lev_ctrl_CC7_EXT:
2386                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2387                    decodedcontroller.controller_number = 7;
2388                    break;
2389                case _lev_ctrl_CC8_EXT:
2390                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2391                    decodedcontroller.controller_number = 8;
2392                    break;
2393                case _lev_ctrl_CC9_EXT:
2394                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2395                    decodedcontroller.controller_number = 9;
2396                    break;
2397                case _lev_ctrl_CC10_EXT:
2398                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2399                    decodedcontroller.controller_number = 10;
2400                    break;
2401                case _lev_ctrl_CC11_EXT:
2402                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2403                    decodedcontroller.controller_number = 11;
2404                    break;
2405                case _lev_ctrl_CC14_EXT:
2406                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2407                    decodedcontroller.controller_number = 14;
2408                    break;
2409                case _lev_ctrl_CC15_EXT:
2410                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2411                    decodedcontroller.controller_number = 15;
2412                    break;
2413                case _lev_ctrl_CC20_EXT:
2414                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2415                    decodedcontroller.controller_number = 20;
2416                    break;
2417                case _lev_ctrl_CC21_EXT:
2418                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2419                    decodedcontroller.controller_number = 21;
2420                    break;
2421                case _lev_ctrl_CC22_EXT:
2422                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2423                    decodedcontroller.controller_number = 22;
2424                    break;
2425                case _lev_ctrl_CC23_EXT:
2426                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2427                    decodedcontroller.controller_number = 23;
2428                    break;
2429                case _lev_ctrl_CC24_EXT:
2430                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2431                    decodedcontroller.controller_number = 24;
2432                    break;
2433                case _lev_ctrl_CC25_EXT:
2434                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2435                    decodedcontroller.controller_number = 25;
2436                    break;
2437                case _lev_ctrl_CC26_EXT:
2438                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2439                    decodedcontroller.controller_number = 26;
2440                    break;
2441                case _lev_ctrl_CC27_EXT:
2442                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2443                    decodedcontroller.controller_number = 27;
2444                    break;
2445                case _lev_ctrl_CC28_EXT:
2446                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2447                    decodedcontroller.controller_number = 28;
2448                    break;
2449                case _lev_ctrl_CC29_EXT:
2450                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2451                    decodedcontroller.controller_number = 29;
2452                    break;
2453                case _lev_ctrl_CC30_EXT:
2454                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2455                    decodedcontroller.controller_number = 30;
2456                    break;
2457                case _lev_ctrl_CC31_EXT:
2458                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2459                    decodedcontroller.controller_number = 31;
2460                    break;
2461                case _lev_ctrl_CC68_EXT:
2462                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2463                    decodedcontroller.controller_number = 68;
2464                    break;
2465                case _lev_ctrl_CC69_EXT:
2466                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2467                    decodedcontroller.controller_number = 69;
2468                    break;
2469                case _lev_ctrl_CC70_EXT:
2470                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2471                    decodedcontroller.controller_number = 70;
2472                    break;
2473                case _lev_ctrl_CC71_EXT:
2474                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2475                    decodedcontroller.controller_number = 71;
2476                    break;
2477                case _lev_ctrl_CC72_EXT:
2478                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2479                    decodedcontroller.controller_number = 72;
2480                    break;
2481                case _lev_ctrl_CC73_EXT:
2482                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2483                    decodedcontroller.controller_number = 73;
2484                    break;
2485                case _lev_ctrl_CC74_EXT:
2486                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2487                    decodedcontroller.controller_number = 74;
2488                    break;
2489                case _lev_ctrl_CC75_EXT:
2490                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2491                    decodedcontroller.controller_number = 75;
2492                    break;
2493                case _lev_ctrl_CC76_EXT:
2494                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2495                    decodedcontroller.controller_number = 76;
2496                    break;
2497                case _lev_ctrl_CC77_EXT:
2498                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2499                    decodedcontroller.controller_number = 77;
2500                    break;
2501                case _lev_ctrl_CC78_EXT:
2502                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2503                    decodedcontroller.controller_number = 78;
2504                    break;
2505                case _lev_ctrl_CC79_EXT:
2506                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2507                    decodedcontroller.controller_number = 79;
2508                    break;
2509                case _lev_ctrl_CC84_EXT:
2510                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2511                    decodedcontroller.controller_number = 84;
2512                    break;
2513                case _lev_ctrl_CC85_EXT:
2514                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2515                    decodedcontroller.controller_number = 85;
2516                    break;
2517                case _lev_ctrl_CC86_EXT:
2518                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2519                    decodedcontroller.controller_number = 86;
2520                    break;
2521                case _lev_ctrl_CC87_EXT:
2522                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2523                    decodedcontroller.controller_number = 87;
2524                    break;
2525                case _lev_ctrl_CC89_EXT:
2526                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2527                    decodedcontroller.controller_number = 89;
2528                    break;
2529                case _lev_ctrl_CC90_EXT:
2530                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2531                    decodedcontroller.controller_number = 90;
2532                    break;
2533                case _lev_ctrl_CC96_EXT:
2534                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2535                    decodedcontroller.controller_number = 96;
2536                    break;
2537                case _lev_ctrl_CC97_EXT:
2538                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2539                    decodedcontroller.controller_number = 97;
2540                    break;
2541                case _lev_ctrl_CC102_EXT:
2542                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2543                    decodedcontroller.controller_number = 102;
2544                    break;
2545                case _lev_ctrl_CC103_EXT:
2546                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2547                    decodedcontroller.controller_number = 103;
2548                    break;
2549                case _lev_ctrl_CC104_EXT:
2550                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2551                    decodedcontroller.controller_number = 104;
2552                    break;
2553                case _lev_ctrl_CC105_EXT:
2554                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2555                    decodedcontroller.controller_number = 105;
2556                    break;
2557                case _lev_ctrl_CC106_EXT:
2558                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2559                    decodedcontroller.controller_number = 106;
2560                    break;
2561                case _lev_ctrl_CC107_EXT:
2562                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2563                    decodedcontroller.controller_number = 107;
2564                    break;
2565                case _lev_ctrl_CC108_EXT:
2566                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2567                    decodedcontroller.controller_number = 108;
2568                    break;
2569                case _lev_ctrl_CC109_EXT:
2570                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2571                    decodedcontroller.controller_number = 109;
2572                    break;
2573                case _lev_ctrl_CC110_EXT:
2574                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2575                    decodedcontroller.controller_number = 110;
2576                    break;
2577                case _lev_ctrl_CC111_EXT:
2578                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2579                    decodedcontroller.controller_number = 111;
2580                    break;
2581                case _lev_ctrl_CC112_EXT:
2582                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2583                    decodedcontroller.controller_number = 112;
2584                    break;
2585                case _lev_ctrl_CC113_EXT:
2586                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2587                    decodedcontroller.controller_number = 113;
2588                    break;
2589                case _lev_ctrl_CC114_EXT:
2590                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2591                    decodedcontroller.controller_number = 114;
2592                    break;
2593                case _lev_ctrl_CC115_EXT:
2594                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2595                    decodedcontroller.controller_number = 115;
2596                    break;
2597                case _lev_ctrl_CC116_EXT:
2598                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2599                    decodedcontroller.controller_number = 116;
2600                    break;
2601                case _lev_ctrl_CC117_EXT:
2602                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2603                    decodedcontroller.controller_number = 117;
2604                    break;
2605                case _lev_ctrl_CC118_EXT:
2606                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2607                    decodedcontroller.controller_number = 118;
2608                    break;
2609                case _lev_ctrl_CC119_EXT:
2610                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2611                    decodedcontroller.controller_number = 119;
2612                    break;
2613    
2614              // unknown controller type              // unknown controller type
2615              default:              default:
2616                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2617          }          }
2618          return decodedcontroller;          return decodedcontroller;
2619      }      }
2620        
2621    // see above (diagnostic push not supported prior GCC 4.6)
2622    //#pragma GCC diagnostic pop
2623    
2624      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2625          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 2079  namespace { Line 2707  namespace {
2707                      case 95:                      case 95:
2708                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2709                          break;                          break;
2710    
2711                        // format extension (these controllers are so far only
2712                        // supported by LinuxSampler & gigedit) they will *NOT*
2713                        // work with Gigasampler/GigaStudio !
2714                        case 3:
2715                            encodedcontroller = _lev_ctrl_CC3_EXT;
2716                            break;
2717                        case 6:
2718                            encodedcontroller = _lev_ctrl_CC6_EXT;
2719                            break;
2720                        case 7:
2721                            encodedcontroller = _lev_ctrl_CC7_EXT;
2722                            break;
2723                        case 8:
2724                            encodedcontroller = _lev_ctrl_CC8_EXT;
2725                            break;
2726                        case 9:
2727                            encodedcontroller = _lev_ctrl_CC9_EXT;
2728                            break;
2729                        case 10:
2730                            encodedcontroller = _lev_ctrl_CC10_EXT;
2731                            break;
2732                        case 11:
2733                            encodedcontroller = _lev_ctrl_CC11_EXT;
2734                            break;
2735                        case 14:
2736                            encodedcontroller = _lev_ctrl_CC14_EXT;
2737                            break;
2738                        case 15:
2739                            encodedcontroller = _lev_ctrl_CC15_EXT;
2740                            break;
2741                        case 20:
2742                            encodedcontroller = _lev_ctrl_CC20_EXT;
2743                            break;
2744                        case 21:
2745                            encodedcontroller = _lev_ctrl_CC21_EXT;
2746                            break;
2747                        case 22:
2748                            encodedcontroller = _lev_ctrl_CC22_EXT;
2749                            break;
2750                        case 23:
2751                            encodedcontroller = _lev_ctrl_CC23_EXT;
2752                            break;
2753                        case 24:
2754                            encodedcontroller = _lev_ctrl_CC24_EXT;
2755                            break;
2756                        case 25:
2757                            encodedcontroller = _lev_ctrl_CC25_EXT;
2758                            break;
2759                        case 26:
2760                            encodedcontroller = _lev_ctrl_CC26_EXT;
2761                            break;
2762                        case 27:
2763                            encodedcontroller = _lev_ctrl_CC27_EXT;
2764                            break;
2765                        case 28:
2766                            encodedcontroller = _lev_ctrl_CC28_EXT;
2767                            break;
2768                        case 29:
2769                            encodedcontroller = _lev_ctrl_CC29_EXT;
2770                            break;
2771                        case 30:
2772                            encodedcontroller = _lev_ctrl_CC30_EXT;
2773                            break;
2774                        case 31:
2775                            encodedcontroller = _lev_ctrl_CC31_EXT;
2776                            break;
2777                        case 68:
2778                            encodedcontroller = _lev_ctrl_CC68_EXT;
2779                            break;
2780                        case 69:
2781                            encodedcontroller = _lev_ctrl_CC69_EXT;
2782                            break;
2783                        case 70:
2784                            encodedcontroller = _lev_ctrl_CC70_EXT;
2785                            break;
2786                        case 71:
2787                            encodedcontroller = _lev_ctrl_CC71_EXT;
2788                            break;
2789                        case 72:
2790                            encodedcontroller = _lev_ctrl_CC72_EXT;
2791                            break;
2792                        case 73:
2793                            encodedcontroller = _lev_ctrl_CC73_EXT;
2794                            break;
2795                        case 74:
2796                            encodedcontroller = _lev_ctrl_CC74_EXT;
2797                            break;
2798                        case 75:
2799                            encodedcontroller = _lev_ctrl_CC75_EXT;
2800                            break;
2801                        case 76:
2802                            encodedcontroller = _lev_ctrl_CC76_EXT;
2803                            break;
2804                        case 77:
2805                            encodedcontroller = _lev_ctrl_CC77_EXT;
2806                            break;
2807                        case 78:
2808                            encodedcontroller = _lev_ctrl_CC78_EXT;
2809                            break;
2810                        case 79:
2811                            encodedcontroller = _lev_ctrl_CC79_EXT;
2812                            break;
2813                        case 84:
2814                            encodedcontroller = _lev_ctrl_CC84_EXT;
2815                            break;
2816                        case 85:
2817                            encodedcontroller = _lev_ctrl_CC85_EXT;
2818                            break;
2819                        case 86:
2820                            encodedcontroller = _lev_ctrl_CC86_EXT;
2821                            break;
2822                        case 87:
2823                            encodedcontroller = _lev_ctrl_CC87_EXT;
2824                            break;
2825                        case 89:
2826                            encodedcontroller = _lev_ctrl_CC89_EXT;
2827                            break;
2828                        case 90:
2829                            encodedcontroller = _lev_ctrl_CC90_EXT;
2830                            break;
2831                        case 96:
2832                            encodedcontroller = _lev_ctrl_CC96_EXT;
2833                            break;
2834                        case 97:
2835                            encodedcontroller = _lev_ctrl_CC97_EXT;
2836                            break;
2837                        case 102:
2838                            encodedcontroller = _lev_ctrl_CC102_EXT;
2839                            break;
2840                        case 103:
2841                            encodedcontroller = _lev_ctrl_CC103_EXT;
2842                            break;
2843                        case 104:
2844                            encodedcontroller = _lev_ctrl_CC104_EXT;
2845                            break;
2846                        case 105:
2847                            encodedcontroller = _lev_ctrl_CC105_EXT;
2848                            break;
2849                        case 106:
2850                            encodedcontroller = _lev_ctrl_CC106_EXT;
2851                            break;
2852                        case 107:
2853                            encodedcontroller = _lev_ctrl_CC107_EXT;
2854                            break;
2855                        case 108:
2856                            encodedcontroller = _lev_ctrl_CC108_EXT;
2857                            break;
2858                        case 109:
2859                            encodedcontroller = _lev_ctrl_CC109_EXT;
2860                            break;
2861                        case 110:
2862                            encodedcontroller = _lev_ctrl_CC110_EXT;
2863                            break;
2864                        case 111:
2865                            encodedcontroller = _lev_ctrl_CC111_EXT;
2866                            break;
2867                        case 112:
2868                            encodedcontroller = _lev_ctrl_CC112_EXT;
2869                            break;
2870                        case 113:
2871                            encodedcontroller = _lev_ctrl_CC113_EXT;
2872                            break;
2873                        case 114:
2874                            encodedcontroller = _lev_ctrl_CC114_EXT;
2875                            break;
2876                        case 115:
2877                            encodedcontroller = _lev_ctrl_CC115_EXT;
2878                            break;
2879                        case 116:
2880                            encodedcontroller = _lev_ctrl_CC116_EXT;
2881                            break;
2882                        case 117:
2883                            encodedcontroller = _lev_ctrl_CC117_EXT;
2884                            break;
2885                        case 118:
2886                            encodedcontroller = _lev_ctrl_CC118_EXT;
2887                            break;
2888                        case 119:
2889                            encodedcontroller = _lev_ctrl_CC119_EXT;
2890                            break;
2891    
2892                      default:                      default:
2893                          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");
2894                  }                  }
# Line 2128  namespace { Line 2938  namespace {
2938          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2939      }      }
2940    
2941        /**
2942         * Updates the respective member variable and the lookup table / cache
2943         * that depends on this value.
2944         */
2945        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2946            pVelocityAttenuationTable =
2947                GetVelocityTable(
2948                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2949                );
2950            VelocityResponseCurve = curve;
2951        }
2952    
2953        /**
2954         * Updates the respective member variable and the lookup table / cache
2955         * that depends on this value.
2956         */
2957        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2958            pVelocityAttenuationTable =
2959                GetVelocityTable(
2960                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2961                );
2962            VelocityResponseDepth = depth;
2963        }
2964    
2965        /**
2966         * Updates the respective member variable and the lookup table / cache
2967         * that depends on this value.
2968         */
2969        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2970            pVelocityAttenuationTable =
2971                GetVelocityTable(
2972                    VelocityResponseCurve, VelocityResponseDepth, scaling
2973                );
2974            VelocityResponseCurveScaling = scaling;
2975        }
2976    
2977        /**
2978         * Updates the respective member variable and the lookup table / cache
2979         * that depends on this value.
2980         */
2981        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2982            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2983            ReleaseVelocityResponseCurve = curve;
2984        }
2985    
2986        /**
2987         * Updates the respective member variable and the lookup table / cache
2988         * that depends on this value.
2989         */
2990        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2991            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2992            ReleaseVelocityResponseDepth = depth;
2993        }
2994    
2995        /**
2996         * Updates the respective member variable and the lookup table / cache
2997         * that depends on this value.
2998         */
2999        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
3000            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
3001            VCFCutoffController = controller;
3002        }
3003    
3004        /**
3005         * Updates the respective member variable and the lookup table / cache
3006         * that depends on this value.
3007         */
3008        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
3009            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
3010            VCFVelocityCurve = curve;
3011        }
3012    
3013        /**
3014         * Updates the respective member variable and the lookup table / cache
3015         * that depends on this value.
3016         */
3017        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
3018            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
3019            VCFVelocityDynamicRange = range;
3020        }
3021    
3022        /**
3023         * Updates the respective member variable and the lookup table / cache
3024         * that depends on this value.
3025         */
3026        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
3027            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
3028            VCFVelocityScale = scaling;
3029        }
3030    
3031      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {      double* DimensionRegion::CreateVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling) {
3032    
3033          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2211  namespace { Line 3111  namespace {
3111    
3112          // Actual Loading          // Actual Loading
3113    
3114            if (!file->GetAutoLoad()) return;
3115    
3116          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
3117    
3118          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2254  namespace { Line 3156  namespace {
3156              else              else
3157                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
3158    
3159              // load sample references              // load sample references (if auto loading is enabled)
3160              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
3161                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
3162                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
3163                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
3164                    }
3165                    GetSample(); // load global region sample reference
3166              }              }
             GetSample(); // load global region sample reference  
3167          } else {          } else {
3168              DimensionRegions = 0;              DimensionRegions = 0;
3169              for (int i = 0 ; i < 8 ; i++) {              for (int i = 0 ; i < 8 ; i++) {
# Line 2286  namespace { Line 3190  namespace {
3190       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3191       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3192       *       *
3193         * @param pProgress - callback function for progress notification
3194       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3195       */       */
3196      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3197          // 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
3198          // 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
3199          // 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 2296  namespace { Line 3201  namespace {
3201          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3202    
3203          // first update base class's chunks          // first update base class's chunks
3204          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3205    
3206          // update dimension region's chunks          // update dimension region's chunks
3207          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3208              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3209          }          }
3210    
3211          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 2316  namespace { Line 3221  namespace {
3221              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3222    
3223              // move 3prg to last position              // move 3prg to last position
3224              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3225          }          }
3226    
3227          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 2390  namespace { Line 3295  namespace {
3295          int step = 1;          int step = 1;
3296          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3297          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3298    
3299          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3300          int dim[8] = { 0 };          int dim[8] = { 0 };
3301          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3302                const int end = i + step * pDimensionDefinitions[veldim].zones;
3303    
3304                // create a velocity table for all cases where the velocity zone is zero
3305              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3306                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3307                  // create the velocity table                  // create the velocity table
# Line 2426  namespace { Line 3332  namespace {
3332                  }                  }
3333              }              }
3334    
3335                // jump to the next case where the velocity zone is zero
3336              int j;              int j;
3337              int shift = 0;              int shift = 0;
3338              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 2462  namespace { Line 3369  namespace {
3369       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3370       */       */
3371      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3372            // some initial sanity checks of the given dimension definition
3373            if (pDimDef->zones < 2)
3374                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3375            if (pDimDef->bits < 1)
3376                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3377            if (pDimDef->dimension == dimension_samplechannel) {
3378                if (pDimDef->zones != 2)
3379                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3380                if (pDimDef->bits != 1)
3381                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3382            }
3383    
3384          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3385          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3386          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2637  namespace { Line 3556  namespace {
3556          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3557      }      }
3558    
3559        /** @brief Delete one split zone of a dimension (decrement zone amount).
3560         *
3561         * Instead of deleting an entire dimensions, this method will only delete
3562         * one particular split zone given by @a zone of the Region's dimension
3563         * given by @a type. So this method will simply decrement the amount of
3564         * zones by one of the dimension in question. To be able to do that, the
3565         * respective dimension must exist on this Region and it must have at least
3566         * 3 zones. All DimensionRegion objects associated with the zone will be
3567         * deleted.
3568         *
3569         * @param type - identifies the dimension where a zone shall be deleted
3570         * @param zone - index of the dimension split zone that shall be deleted
3571         * @throws gig::Exception if requested zone could not be deleted
3572         */
3573        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3574            dimension_def_t* oldDef = GetDimensionDefinition(type);
3575            if (!oldDef)
3576                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3577            if (oldDef->zones <= 2)
3578                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3579            if (zone < 0 || zone >= oldDef->zones)
3580                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3581    
3582            const int newZoneSize = oldDef->zones - 1;
3583    
3584            // create a temporary Region which just acts as a temporary copy
3585            // container and will be deleted at the end of this function and will
3586            // also not be visible through the API during this process
3587            gig::Region* tempRgn = NULL;
3588            {
3589                // adding these temporary chunks is probably not even necessary
3590                Instrument* instr = static_cast<Instrument*>(GetParent());
3591                RIFF::List* pCkInstrument = instr->pCkInstrument;
3592                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3593                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3594                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3595                tempRgn = new Region(instr, rgn);
3596            }
3597    
3598            // copy this region's dimensions (with already the dimension split size
3599            // requested by the arguments of this method call) to the temporary
3600            // region, and don't use Region::CopyAssign() here for this task, since
3601            // it would also alter fast lookup helper variables here and there
3602            dimension_def_t newDef;
3603            for (int i = 0; i < Dimensions; ++i) {
3604                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3605                // is this the dimension requested by the method arguments? ...
3606                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3607                    def.zones = newZoneSize;
3608                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3609                    newDef = def;
3610                }
3611                tempRgn->AddDimension(&def);
3612            }
3613    
3614            // find the dimension index in the tempRegion which is the dimension
3615            // type passed to this method (paranoidly expecting different order)
3616            int tempReducedDimensionIndex = -1;
3617            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3618                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3619                    tempReducedDimensionIndex = d;
3620                    break;
3621                }
3622            }
3623    
3624            // copy dimension regions from this region to the temporary region
3625            for (int iDst = 0; iDst < 256; ++iDst) {
3626                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3627                if (!dstDimRgn) continue;
3628                std::map<dimension_t,int> dimCase;
3629                bool isValidZone = true;
3630                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3631                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3632                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3633                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3634                    baseBits += dstBits;
3635                    // there are also DimensionRegion objects of unused zones, skip them
3636                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3637                        isValidZone = false;
3638                        break;
3639                    }
3640                }
3641                if (!isValidZone) continue;
3642                // a bit paranoid: cope with the chance that the dimensions would
3643                // have different order in source and destination regions
3644                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3645                if (dimCase[type] >= zone) dimCase[type]++;
3646                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3647                dstDimRgn->CopyAssign(srcDimRgn);
3648                // if this is the upper most zone of the dimension passed to this
3649                // method, then correct (raise) its upper limit to 127
3650                if (newDef.split_type == split_type_normal && isLastZone)
3651                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3652            }
3653    
3654            // now tempRegion's dimensions and DimensionRegions basically reflect
3655            // what we wanted to get for this actual Region here, so we now just
3656            // delete and recreate the dimension in question with the new amount
3657            // zones and then copy back from tempRegion      
3658            DeleteDimension(oldDef);
3659            AddDimension(&newDef);
3660            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3661                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3662                if (!srcDimRgn) continue;
3663                std::map<dimension_t,int> dimCase;
3664                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3665                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3666                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3667                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3668                    baseBits += srcBits;
3669                }
3670                // a bit paranoid: cope with the chance that the dimensions would
3671                // have different order in source and destination regions
3672                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3673                if (!dstDimRgn) continue;
3674                dstDimRgn->CopyAssign(srcDimRgn);
3675            }
3676    
3677            // delete temporary region
3678            delete tempRgn;
3679    
3680            UpdateVelocityTable();
3681        }
3682    
3683        /** @brief Divide split zone of a dimension in two (increment zone amount).
3684         *
3685         * This will increment the amount of zones for the dimension (given by
3686         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3687         * in the middle of its zone range in two. So the two zones resulting from
3688         * the zone being splitted, will be an equivalent copy regarding all their
3689         * articulation informations and sample reference. The two zones will only
3690         * differ in their zone's upper limit
3691         * (DimensionRegion::DimensionUpperLimits).
3692         *
3693         * @param type - identifies the dimension where a zone shall be splitted
3694         * @param zone - index of the dimension split zone that shall be splitted
3695         * @throws gig::Exception if requested zone could not be splitted
3696         */
3697        void Region::SplitDimensionZone(dimension_t type, int zone) {
3698            dimension_def_t* oldDef = GetDimensionDefinition(type);
3699            if (!oldDef)
3700                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3701            if (zone < 0 || zone >= oldDef->zones)
3702                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3703    
3704            const int newZoneSize = oldDef->zones + 1;
3705    
3706            // create a temporary Region which just acts as a temporary copy
3707            // container and will be deleted at the end of this function and will
3708            // also not be visible through the API during this process
3709            gig::Region* tempRgn = NULL;
3710            {
3711                // adding these temporary chunks is probably not even necessary
3712                Instrument* instr = static_cast<Instrument*>(GetParent());
3713                RIFF::List* pCkInstrument = instr->pCkInstrument;
3714                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3715                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3716                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3717                tempRgn = new Region(instr, rgn);
3718            }
3719    
3720            // copy this region's dimensions (with already the dimension split size
3721            // requested by the arguments of this method call) to the temporary
3722            // region, and don't use Region::CopyAssign() here for this task, since
3723            // it would also alter fast lookup helper variables here and there
3724            dimension_def_t newDef;
3725            for (int i = 0; i < Dimensions; ++i) {
3726                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3727                // is this the dimension requested by the method arguments? ...
3728                if (def.dimension == type) { // ... if yes, increment zone amount by one
3729                    def.zones = newZoneSize;
3730                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3731                    newDef = def;
3732                }
3733                tempRgn->AddDimension(&def);
3734            }
3735    
3736            // find the dimension index in the tempRegion which is the dimension
3737            // type passed to this method (paranoidly expecting different order)
3738            int tempIncreasedDimensionIndex = -1;
3739            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3740                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3741                    tempIncreasedDimensionIndex = d;
3742                    break;
3743                }
3744            }
3745    
3746            // copy dimension regions from this region to the temporary region
3747            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3748                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3749                if (!srcDimRgn) continue;
3750                std::map<dimension_t,int> dimCase;
3751                bool isValidZone = true;
3752                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3753                    const int srcBits = pDimensionDefinitions[d].bits;
3754                    dimCase[pDimensionDefinitions[d].dimension] =
3755                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3756                    // there are also DimensionRegion objects for unused zones, skip them
3757                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3758                        isValidZone = false;
3759                        break;
3760                    }
3761                    baseBits += srcBits;
3762                }
3763                if (!isValidZone) continue;
3764                // a bit paranoid: cope with the chance that the dimensions would
3765                // have different order in source and destination regions            
3766                if (dimCase[type] > zone) dimCase[type]++;
3767                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3768                dstDimRgn->CopyAssign(srcDimRgn);
3769                // if this is the requested zone to be splitted, then also copy
3770                // the source DimensionRegion to the newly created target zone
3771                // and set the old zones upper limit lower
3772                if (dimCase[type] == zone) {
3773                    // lower old zones upper limit
3774                    if (newDef.split_type == split_type_normal) {
3775                        const int high =
3776                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3777                        int low = 0;
3778                        if (zone > 0) {
3779                            std::map<dimension_t,int> lowerCase = dimCase;
3780                            lowerCase[type]--;
3781                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3782                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3783                        }
3784                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3785                    }
3786                    // fill the newly created zone of the divided zone as well
3787                    dimCase[type]++;
3788                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3789                    dstDimRgn->CopyAssign(srcDimRgn);
3790                }
3791            }
3792    
3793            // now tempRegion's dimensions and DimensionRegions basically reflect
3794            // what we wanted to get for this actual Region here, so we now just
3795            // delete and recreate the dimension in question with the new amount
3796            // zones and then copy back from tempRegion      
3797            DeleteDimension(oldDef);
3798            AddDimension(&newDef);
3799            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3800                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3801                if (!srcDimRgn) continue;
3802                std::map<dimension_t,int> dimCase;
3803                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3804                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3805                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3806                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3807                    baseBits += srcBits;
3808                }
3809                // a bit paranoid: cope with the chance that the dimensions would
3810                // have different order in source and destination regions
3811                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3812                if (!dstDimRgn) continue;
3813                dstDimRgn->CopyAssign(srcDimRgn);
3814            }
3815    
3816            // delete temporary region
3817            delete tempRgn;
3818    
3819            UpdateVelocityTable();
3820        }
3821    
3822        /** @brief Change type of an existing dimension.
3823         *
3824         * Alters the dimension type of a dimension already existing on this
3825         * region. If there is currently no dimension on this Region with type
3826         * @a oldType, then this call with throw an Exception. Likewise there are
3827         * cases where the requested dimension type cannot be performed. For example
3828         * if the new dimension type shall be gig::dimension_samplechannel, and the
3829         * current dimension has more than 2 zones. In such cases an Exception is
3830         * thrown as well.
3831         *
3832         * @param oldType - identifies the existing dimension to be changed
3833         * @param newType - to which dimension type it should be changed to
3834         * @throws gig::Exception if requested change cannot be performed
3835         */
3836        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3837            if (oldType == newType) return;
3838            dimension_def_t* def = GetDimensionDefinition(oldType);
3839            if (!def)
3840                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3841            if (newType == dimension_samplechannel && def->zones != 2)
3842                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3843            if (GetDimensionDefinition(newType))
3844                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3845            def->dimension  = newType;
3846            def->split_type = __resolveSplitType(newType);
3847        }
3848    
3849        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3850            uint8_t bits[8] = {};
3851            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3852                 it != DimCase.end(); ++it)
3853            {
3854                for (int d = 0; d < Dimensions; ++d) {
3855                    if (pDimensionDefinitions[d].dimension == it->first) {
3856                        bits[d] = it->second;
3857                        goto nextDimCaseSlice;
3858                    }
3859                }
3860                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3861                nextDimCaseSlice:
3862                ; // noop
3863            }
3864            return GetDimensionRegionByBit(bits);
3865        }
3866    
3867        /**
3868         * Searches in the current Region for a dimension of the given dimension
3869         * type and returns the precise configuration of that dimension in this
3870         * Region.
3871         *
3872         * @param type - dimension type of the sought dimension
3873         * @returns dimension definition or NULL if there is no dimension with
3874         *          sought type in this Region.
3875         */
3876        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3877            for (int i = 0; i < Dimensions; ++i)
3878                if (pDimensionDefinitions[i].dimension == type)
3879                    return &pDimensionDefinitions[i];
3880            return NULL;
3881        }
3882    
3883      Region::~Region() {      Region::~Region() {
3884          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3885              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2664  namespace { Line 3907  namespace {
3907      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3908          uint8_t bits;          uint8_t bits;
3909          int veldim = -1;          int veldim = -1;
3910          int velbitpos;          int velbitpos = 0;
3911          int bitpos = 0;          int bitpos = 0;
3912          int dimregidx = 0;          int dimregidx = 0;
3913          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 2694  namespace { Line 3937  namespace {
3937              }              }
3938              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3939          }          }
3940          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3941            if (!dimreg) return NULL;
3942          if (veldim != -1) {          if (veldim != -1) {
3943              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3944              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3945                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3946              else // normal split type              else // normal split type
3947                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3948    
3949              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3950              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3951                dimreg = pDimensionRegions[dimregidx & 255];
3952          }          }
3953          return dimreg;          return dimreg;
3954      }      }
3955    
3956        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3957            uint8_t bits;
3958            int veldim = -1;
3959            int velbitpos = 0;
3960            int bitpos = 0;
3961            int dimregidx = 0;
3962            for (uint i = 0; i < Dimensions; i++) {
3963                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3964                    // the velocity dimension must be handled after the other dimensions
3965                    veldim = i;
3966                    velbitpos = bitpos;
3967                } else {
3968                    switch (pDimensionDefinitions[i].split_type) {
3969                        case split_type_normal:
3970                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3971                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3972                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3973                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3974                                }
3975                            } else {
3976                                // gig2: evenly sized zones
3977                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3978                            }
3979                            break;
3980                        case split_type_bit: // the value is already the sought dimension bit number
3981                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3982                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3983                            break;
3984                    }
3985                    dimregidx |= bits << bitpos;
3986                }
3987                bitpos += pDimensionDefinitions[i].bits;
3988            }
3989            dimregidx &= 255;
3990            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3991            if (!dimreg) return -1;
3992            if (veldim != -1) {
3993                // (dimreg is now the dimension region for the lowest velocity)
3994                if (dimreg->VelocityTable) // custom defined zone ranges
3995                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3996                else // normal split type
3997                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3998    
3999                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
4000                dimregidx |= (bits & limiter_mask) << velbitpos;
4001                dimregidx &= 255;
4002            }
4003            return dimregidx;
4004        }
4005    
4006      /**      /**
4007       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
4008       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2746  namespace { Line 4041  namespace {
4041          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
4042          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
4043          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
4044          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
4045          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
4046          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
4047          while (sample) {              uint64_t soughtoffset =
4048              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
4049                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
4050              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
4051                while (sample) {
4052                    if (sample->ullWavePoolOffset == soughtoffset)
4053                        return static_cast<gig::Sample*>(sample);
4054                    sample = file->GetNextSample();
4055                }
4056            } else {
4057                // use extension files and 32 bit wave pool offsets
4058                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
4059                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
4060                Sample* sample = file->GetFirstSample(pProgress);
4061                while (sample) {
4062                    if (sample->ullWavePoolOffset == soughtoffset &&
4063                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
4064                    sample = file->GetNextSample();
4065                }
4066          }          }
4067          return NULL;          return NULL;
4068      }      }
4069        
4070        /**
4071         * Make a (semi) deep copy of the Region object given by @a orig
4072         * and assign it to this object.
4073         *
4074         * Note that all sample pointers referenced by @a orig are simply copied as
4075         * memory address. Thus the respective samples are shared, not duplicated!
4076         *
4077         * @param orig - original Region object to be copied from
4078         */
4079        void Region::CopyAssign(const Region* orig) {
4080            CopyAssign(orig, NULL);
4081        }
4082        
4083        /**
4084         * Make a (semi) deep copy of the Region object given by @a orig and
4085         * assign it to this object
4086         *
4087         * @param mSamples - crosslink map between the foreign file's samples and
4088         *                   this file's samples
4089         */
4090        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
4091            // handle base classes
4092            DLS::Region::CopyAssign(orig);
4093            
4094            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
4095                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
4096            }
4097            
4098            // handle own member variables
4099            for (int i = Dimensions - 1; i >= 0; --i) {
4100                DeleteDimension(&pDimensionDefinitions[i]);
4101            }
4102            Layers = 0; // just to be sure
4103            for (int i = 0; i < orig->Dimensions; i++) {
4104                // we need to copy the dim definition here, to avoid the compiler
4105                // complaining about const-ness issue
4106                dimension_def_t def = orig->pDimensionDefinitions[i];
4107                AddDimension(&def);
4108            }
4109            for (int i = 0; i < 256; i++) {
4110                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
4111                    pDimensionRegions[i]->CopyAssign(
4112                        orig->pDimensionRegions[i],
4113                        mSamples
4114                    );
4115                }
4116            }
4117            Layers = orig->Layers;
4118        }
4119    
4120    
4121    // *************** MidiRule ***************
4122    // *
4123    
4124        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
4125            _3ewg->SetPos(36);
4126            Triggers = _3ewg->ReadUint8();
4127            _3ewg->SetPos(40);
4128            ControllerNumber = _3ewg->ReadUint8();
4129            _3ewg->SetPos(46);
4130            for (int i = 0 ; i < Triggers ; i++) {
4131                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
4132                pTriggers[i].Descending = _3ewg->ReadUint8();
4133                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
4134                pTriggers[i].Key = _3ewg->ReadUint8();
4135                pTriggers[i].NoteOff = _3ewg->ReadUint8();
4136                pTriggers[i].Velocity = _3ewg->ReadUint8();
4137                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
4138                _3ewg->ReadUint8();
4139            }
4140        }
4141    
4142        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
4143            ControllerNumber(0),
4144            Triggers(0) {
4145        }
4146    
4147        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
4148            pData[32] = 4;
4149            pData[33] = 16;
4150            pData[36] = Triggers;
4151            pData[40] = ControllerNumber;
4152            for (int i = 0 ; i < Triggers ; i++) {
4153                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
4154                pData[47 + i * 8] = pTriggers[i].Descending;
4155                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
4156                pData[49 + i * 8] = pTriggers[i].Key;
4157                pData[50 + i * 8] = pTriggers[i].NoteOff;
4158                pData[51 + i * 8] = pTriggers[i].Velocity;
4159                pData[52 + i * 8] = pTriggers[i].OverridePedal;
4160            }
4161        }
4162    
4163        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
4164            _3ewg->SetPos(36);
4165            LegatoSamples = _3ewg->ReadUint8(); // always 12
4166            _3ewg->SetPos(40);
4167            BypassUseController = _3ewg->ReadUint8();
4168            BypassKey = _3ewg->ReadUint8();
4169            BypassController = _3ewg->ReadUint8();
4170            ThresholdTime = _3ewg->ReadUint16();
4171            _3ewg->ReadInt16();
4172            ReleaseTime = _3ewg->ReadUint16();
4173            _3ewg->ReadInt16();
4174            KeyRange.low = _3ewg->ReadUint8();
4175            KeyRange.high = _3ewg->ReadUint8();
4176            _3ewg->SetPos(64);
4177            ReleaseTriggerKey = _3ewg->ReadUint8();
4178            AltSustain1Key = _3ewg->ReadUint8();
4179            AltSustain2Key = _3ewg->ReadUint8();
4180        }
4181    
4182        MidiRuleLegato::MidiRuleLegato() :
4183            LegatoSamples(12),
4184            BypassUseController(false),
4185            BypassKey(0),
4186            BypassController(1),
4187            ThresholdTime(20),
4188            ReleaseTime(20),
4189            ReleaseTriggerKey(0),
4190            AltSustain1Key(0),
4191            AltSustain2Key(0)
4192        {
4193            KeyRange.low = KeyRange.high = 0;
4194        }
4195    
4196        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
4197            pData[32] = 0;
4198            pData[33] = 16;
4199            pData[36] = LegatoSamples;
4200            pData[40] = BypassUseController;
4201            pData[41] = BypassKey;
4202            pData[42] = BypassController;
4203            store16(&pData[43], ThresholdTime);
4204            store16(&pData[47], ReleaseTime);
4205            pData[51] = KeyRange.low;
4206            pData[52] = KeyRange.high;
4207            pData[64] = ReleaseTriggerKey;
4208            pData[65] = AltSustain1Key;
4209            pData[66] = AltSustain2Key;
4210        }
4211    
4212        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4213            _3ewg->SetPos(36);
4214            Articulations = _3ewg->ReadUint8();
4215            int flags = _3ewg->ReadUint8();
4216            Polyphonic = flags & 8;
4217            Chained = flags & 4;
4218            Selector = (flags & 2) ? selector_controller :
4219                (flags & 1) ? selector_key_switch : selector_none;
4220            Patterns = _3ewg->ReadUint8();
4221            _3ewg->ReadUint8(); // chosen row
4222            _3ewg->ReadUint8(); // unknown
4223            _3ewg->ReadUint8(); // unknown
4224            _3ewg->ReadUint8(); // unknown
4225            KeySwitchRange.low = _3ewg->ReadUint8();
4226            KeySwitchRange.high = _3ewg->ReadUint8();
4227            Controller = _3ewg->ReadUint8();
4228            PlayRange.low = _3ewg->ReadUint8();
4229            PlayRange.high = _3ewg->ReadUint8();
4230    
4231            int n = std::min(int(Articulations), 32);
4232            for (int i = 0 ; i < n ; i++) {
4233                _3ewg->ReadString(pArticulations[i], 32);
4234            }
4235            _3ewg->SetPos(1072);
4236            n = std::min(int(Patterns), 32);
4237            for (int i = 0 ; i < n ; i++) {
4238                _3ewg->ReadString(pPatterns[i].Name, 16);
4239                pPatterns[i].Size = _3ewg->ReadUint8();
4240                _3ewg->Read(&pPatterns[i][0], 1, 32);
4241            }
4242        }
4243    
4244        MidiRuleAlternator::MidiRuleAlternator() :
4245            Articulations(0),
4246            Patterns(0),
4247            Selector(selector_none),
4248            Controller(0),
4249            Polyphonic(false),
4250            Chained(false)
4251        {
4252            PlayRange.low = PlayRange.high = 0;
4253            KeySwitchRange.low = KeySwitchRange.high = 0;
4254        }
4255    
4256        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4257            pData[32] = 3;
4258            pData[33] = 16;
4259            pData[36] = Articulations;
4260            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4261                (Selector == selector_controller ? 2 :
4262                 (Selector == selector_key_switch ? 1 : 0));
4263            pData[38] = Patterns;
4264    
4265            pData[43] = KeySwitchRange.low;
4266            pData[44] = KeySwitchRange.high;
4267            pData[45] = Controller;
4268            pData[46] = PlayRange.low;
4269            pData[47] = PlayRange.high;
4270    
4271            char* str = reinterpret_cast<char*>(pData);
4272            int pos = 48;
4273            int n = std::min(int(Articulations), 32);
4274            for (int i = 0 ; i < n ; i++, pos += 32) {
4275                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4276            }
4277    
4278            pos = 1072;
4279            n = std::min(int(Patterns), 32);
4280            for (int i = 0 ; i < n ; i++, pos += 49) {
4281                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4282                pData[pos + 16] = pPatterns[i].Size;
4283                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4284            }
4285        }
4286    
4287    // *************** Script ***************
4288    // *
4289    
4290        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4291            pGroup = group;
4292            pChunk = ckScri;
4293            if (ckScri) { // object is loaded from file ...
4294                // read header
4295                uint32_t headerSize = ckScri->ReadUint32();
4296                Compression = (Compression_t) ckScri->ReadUint32();
4297                Encoding    = (Encoding_t) ckScri->ReadUint32();
4298                Language    = (Language_t) ckScri->ReadUint32();
4299                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4300                crc         = ckScri->ReadUint32();
4301                uint32_t nameSize = ckScri->ReadUint32();
4302                Name.resize(nameSize, ' ');
4303                for (int i = 0; i < nameSize; ++i)
4304                    Name[i] = ckScri->ReadUint8();
4305                // to handle potential future extensions of the header
4306                ckScri->SetPos(sizeof(int32_t) + headerSize);
4307                // read actual script data
4308                uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4309                data.resize(scriptSize);
4310                for (int i = 0; i < scriptSize; ++i)
4311                    data[i] = ckScri->ReadUint8();
4312            } else { // this is a new script object, so just initialize it as such ...
4313                Compression = COMPRESSION_NONE;
4314                Encoding = ENCODING_ASCII;
4315                Language = LANGUAGE_NKSP;
4316                Bypass   = false;
4317                crc      = 0;
4318                Name     = "Unnamed Script";
4319            }
4320        }
4321    
4322        Script::~Script() {
4323        }
4324    
4325        /**
4326         * Returns the current script (i.e. as source code) in text format.
4327         */
4328        String Script::GetScriptAsText() {
4329            String s;
4330            s.resize(data.size(), ' ');
4331            memcpy(&s[0], &data[0], data.size());
4332            return s;
4333        }
4334    
4335        /**
4336         * Replaces the current script with the new script source code text given
4337         * by @a text.
4338         *
4339         * @param text - new script source code
4340         */
4341        void Script::SetScriptAsText(const String& text) {
4342            data.resize(text.size());
4343            memcpy(&data[0], &text[0], text.size());
4344        }
4345    
4346        /**
4347         * Apply this script to the respective RIFF chunks. You have to call
4348         * File::Save() to make changes persistent.
4349         *
4350         * Usually there is absolutely no need to call this method explicitly.
4351         * It will be called automatically when File::Save() was called.
4352         *
4353         * @param pProgress - callback function for progress notification
4354         */
4355        void Script::UpdateChunks(progress_t* pProgress) {
4356            // recalculate CRC32 check sum
4357            __resetCRC(crc);
4358            __calculateCRC(&data[0], data.size(), crc);
4359            __finalizeCRC(crc);
4360            // make sure chunk exists and has the required size
4361            const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4362            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4363            else pChunk->Resize(chunkSize);
4364            // fill the chunk data to be written to disk
4365            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4366            int pos = 0;
4367            store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4368            pos += sizeof(int32_t);
4369            store32(&pData[pos], Compression);
4370            pos += sizeof(int32_t);
4371            store32(&pData[pos], Encoding);
4372            pos += sizeof(int32_t);
4373            store32(&pData[pos], Language);
4374            pos += sizeof(int32_t);
4375            store32(&pData[pos], Bypass ? 1 : 0);
4376            pos += sizeof(int32_t);
4377            store32(&pData[pos], crc);
4378            pos += sizeof(int32_t);
4379            store32(&pData[pos], (uint32_t) Name.size());
4380            pos += sizeof(int32_t);
4381            for (int i = 0; i < Name.size(); ++i, ++pos)
4382                pData[pos] = Name[i];
4383            for (int i = 0; i < data.size(); ++i, ++pos)
4384                pData[pos] = data[i];
4385        }
4386    
4387        /**
4388         * Move this script from its current ScriptGroup to another ScriptGroup
4389         * given by @a pGroup.
4390         *
4391         * @param pGroup - script's new group
4392         */
4393        void Script::SetGroup(ScriptGroup* pGroup) {
4394            if (this->pGroup == pGroup) return;
4395            if (pChunk)
4396                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4397            this->pGroup = pGroup;
4398        }
4399    
4400        /**
4401         * Returns the script group this script currently belongs to. Each script
4402         * is a member of exactly one ScriptGroup.
4403         *
4404         * @returns current script group
4405         */
4406        ScriptGroup* Script::GetGroup() const {
4407            return pGroup;
4408        }
4409    
4410        /**
4411         * Make a (semi) deep copy of the Script object given by @a orig
4412         * and assign it to this object. Note: the ScriptGroup this Script
4413         * object belongs to remains untouched by this call.
4414         *
4415         * @param orig - original Script object to be copied from
4416         */
4417        void Script::CopyAssign(const Script* orig) {
4418            Name        = orig->Name;
4419            Compression = orig->Compression;
4420            Encoding    = orig->Encoding;
4421            Language    = orig->Language;
4422            Bypass      = orig->Bypass;
4423            data        = orig->data;
4424        }
4425    
4426        void Script::RemoveAllScriptReferences() {
4427            File* pFile = pGroup->pFile;
4428            for (int i = 0; pFile->GetInstrument(i); ++i) {
4429                Instrument* instr = pFile->GetInstrument(i);
4430                instr->RemoveScript(this);
4431            }
4432        }
4433    
4434    // *************** ScriptGroup ***************
4435    // *
4436    
4437        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4438            pFile = file;
4439            pList = lstRTIS;
4440            pScripts = NULL;
4441            if (lstRTIS) {
4442                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4443                ::LoadString(ckName, Name);
4444            } else {
4445                Name = "Default Group";
4446            }
4447        }
4448    
4449        ScriptGroup::~ScriptGroup() {
4450            if (pScripts) {
4451                std::list<Script*>::iterator iter = pScripts->begin();
4452                std::list<Script*>::iterator end  = pScripts->end();
4453                while (iter != end) {
4454                    delete *iter;
4455                    ++iter;
4456                }
4457                delete pScripts;
4458            }
4459        }
4460    
4461        /**
4462         * Apply this script group to the respective RIFF chunks. You have to call
4463         * File::Save() to make changes persistent.
4464         *
4465         * Usually there is absolutely no need to call this method explicitly.
4466         * It will be called automatically when File::Save() was called.
4467         *
4468         * @param pProgress - callback function for progress notification
4469         */
4470        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4471            if (pScripts) {
4472                if (!pList)
4473                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4474    
4475                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4476                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4477    
4478                for (std::list<Script*>::iterator it = pScripts->begin();
4479                     it != pScripts->end(); ++it)
4480                {
4481                    (*it)->UpdateChunks(pProgress);
4482                }
4483            }
4484        }
4485    
4486        /** @brief Get instrument script.
4487         *
4488         * Returns the real-time instrument script with the given index.
4489         *
4490         * @param index - number of the sought script (0..n)
4491         * @returns sought script or NULL if there's no such script
4492         */
4493        Script* ScriptGroup::GetScript(uint index) {
4494            if (!pScripts) LoadScripts();
4495            std::list<Script*>::iterator it = pScripts->begin();
4496            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4497                if (i == index) return *it;
4498            return NULL;
4499        }
4500    
4501        /** @brief Add new instrument script.
4502         *
4503         * Adds a new real-time instrument script to the file. The script is not
4504         * actually used / executed unless it is referenced by an instrument to be
4505         * used. This is similar to samples, which you can add to a file, without
4506         * an instrument necessarily actually using it.
4507         *
4508         * You have to call Save() to make this persistent to the file.
4509         *
4510         * @return new empty script object
4511         */
4512        Script* ScriptGroup::AddScript() {
4513            if (!pScripts) LoadScripts();
4514            Script* pScript = new Script(this, NULL);
4515            pScripts->push_back(pScript);
4516            return pScript;
4517        }
4518    
4519        /** @brief Delete an instrument script.
4520         *
4521         * This will delete the given real-time instrument script. References of
4522         * instruments that are using that script will be removed accordingly.
4523         *
4524         * You have to call Save() to make this persistent to the file.
4525         *
4526         * @param pScript - script to delete
4527         * @throws gig::Exception if given script could not be found
4528         */
4529        void ScriptGroup::DeleteScript(Script* pScript) {
4530            if (!pScripts) LoadScripts();
4531            std::list<Script*>::iterator iter =
4532                find(pScripts->begin(), pScripts->end(), pScript);
4533            if (iter == pScripts->end())
4534                throw gig::Exception("Could not delete script, could not find given script");
4535            pScripts->erase(iter);
4536            pScript->RemoveAllScriptReferences();
4537            if (pScript->pChunk)
4538                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4539            delete pScript;
4540        }
4541    
4542        void ScriptGroup::LoadScripts() {
4543            if (pScripts) return;
4544            pScripts = new std::list<Script*>;
4545            if (!pList) return;
4546    
4547            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4548                 ck = pList->GetNextSubChunk())
4549            {
4550                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4551                    pScripts->push_back(new Script(this, ck));
4552                }
4553            }
4554        }
4555    
4556  // *************** Instrument ***************  // *************** Instrument ***************
4557  // *  // *
4558    
4559      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
4560          static const DLS::Info::FixedStringLength fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
4561              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
4562              { CHUNK_ID_ISFT, 12 },              { CHUNK_ID_ISFT, 12 },
4563              { 0, 0 }              { 0, 0 }
4564          };          };
4565          pInfo->FixedStringLengths = fixedStringLengths;          pInfo->SetFixedStringLengths(fixedStringLengths);
4566    
4567          // Initialization          // Initialization
4568          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4569          EffectSend = 0;          EffectSend = 0;
4570          Attenuation = 0;          Attenuation = 0;
4571          FineTune = 0;          FineTune = 0;
4572          PitchbendRange = 0;          PitchbendRange = 2;
4573          PianoReleaseMode = false;          PianoReleaseMode = false;
4574          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4575          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4576            pMidiRules = new MidiRule*[3];
4577            pMidiRules[0] = NULL;
4578            pScriptRefs = NULL;
4579    
4580          // Loading          // Loading
4581          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2793  namespace { Line 4590  namespace {
4590                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4591                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4592                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4593    
4594                    if (_3ewg->GetSize() > 32) {
4595                        // read MIDI rules
4596                        int i = 0;
4597                        _3ewg->SetPos(32);
4598                        uint8_t id1 = _3ewg->ReadUint8();
4599                        uint8_t id2 = _3ewg->ReadUint8();
4600    
4601                        if (id2 == 16) {
4602                            if (id1 == 4) {
4603                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4604                            } else if (id1 == 0) {
4605                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4606                            } else if (id1 == 3) {
4607                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4608                            } else {
4609                                pMidiRules[i++] = new MidiRuleUnknown;
4610                            }
4611                        }
4612                        else if (id1 != 0 || id2 != 0) {
4613                            pMidiRules[i++] = new MidiRuleUnknown;
4614                        }
4615                        //TODO: all the other types of rules
4616    
4617                        pMidiRules[i] = NULL;
4618                    }
4619              }              }
4620          }          }
4621    
4622          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
4623          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
4624          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4625              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
4626              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
4627                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
4628                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4629                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4630                            pRegions->push_back(new Region(this, rgn));
4631                        }
4632                        rgn = lrgn->GetNextSubList();
4633                    }
4634                    // Creating Region Key Table for fast lookup
4635                    UpdateRegionKeyTable();
4636                }
4637            }
4638    
4639            // own gig format extensions
4640            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4641            if (lst3LS) {
4642                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4643                if (ckSCSL) {
4644                    int headerSize = ckSCSL->ReadUint32();
4645                    int slotCount  = ckSCSL->ReadUint32();
4646                    if (slotCount) {
4647                        int slotSize  = ckSCSL->ReadUint32();
4648                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4649                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4650                        for (int i = 0; i < slotCount; ++i) {
4651                            _ScriptPooolEntry e;
4652                            e.fileOffset = ckSCSL->ReadUint32();
4653                            e.bypass     = ckSCSL->ReadUint32() & 1;
4654                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4655                            scriptPoolFileOffsets.push_back(e);
4656                        }
4657                  }                  }
                 rgn = lrgn->GetNextSubList();  
4658              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4659          }          }
4660    
4661          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
# Line 2827  namespace { Line 4674  namespace {
4674      }      }
4675    
4676      Instrument::~Instrument() {      Instrument::~Instrument() {
4677            for (int i = 0 ; pMidiRules[i] ; i++) {
4678                delete pMidiRules[i];
4679            }
4680            delete[] pMidiRules;
4681            if (pScriptRefs) delete pScriptRefs;
4682      }      }
4683    
4684      /**      /**
# Line 2836  namespace { Line 4688  namespace {
4688       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4689       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4690       *       *
4691         * @param pProgress - callback function for progress notification
4692       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4693       */       */
4694      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4695          // first update base classes' chunks          // first update base classes' chunks
4696          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4697    
4698          // update Regions' chunks          // update Regions' chunks
4699          {          {
4700              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4701              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4702              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4703                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4704          }          }
4705    
4706          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 2873  namespace { Line 4726  namespace {
4726                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4727          pData[10] = dimkeystart;          pData[10] = dimkeystart;
4728          pData[11] = DimensionKeyRange.high;          pData[11] = DimensionKeyRange.high;
4729    
4730            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4731                pData[32] = 0;
4732                pData[33] = 0;
4733            } else {
4734                for (int i = 0 ; pMidiRules[i] ; i++) {
4735                    pMidiRules[i]->UpdateChunks(pData);
4736                }
4737            }
4738    
4739            // own gig format extensions
4740           if (ScriptSlotCount()) {
4741               // make sure we have converted the original loaded script file
4742               // offsets into valid Script object pointers
4743               LoadScripts();
4744    
4745               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4746               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4747               const int slotCount = (int) pScriptRefs->size();
4748               const int headerSize = 3 * sizeof(uint32_t);
4749               const int slotSize  = 2 * sizeof(uint32_t);
4750               const int totalChunkSize = headerSize + slotCount * slotSize;
4751               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4752               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4753               else ckSCSL->Resize(totalChunkSize);
4754               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4755               int pos = 0;
4756               store32(&pData[pos], headerSize);
4757               pos += sizeof(uint32_t);
4758               store32(&pData[pos], slotCount);
4759               pos += sizeof(uint32_t);
4760               store32(&pData[pos], slotSize);
4761               pos += sizeof(uint32_t);
4762               for (int i = 0; i < slotCount; ++i) {
4763                   // arbitrary value, the actual file offset will be updated in
4764                   // UpdateScriptFileOffsets() after the file has been resized
4765                   int bogusFileOffset = 0;
4766                   store32(&pData[pos], bogusFileOffset);
4767                   pos += sizeof(uint32_t);
4768                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4769                   pos += sizeof(uint32_t);
4770               }
4771           } else {
4772               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4773               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4774               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4775           }
4776        }
4777    
4778        void Instrument::UpdateScriptFileOffsets() {
4779           // own gig format extensions
4780           if (pScriptRefs && pScriptRefs->size() > 0) {
4781               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4782               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4783               const int slotCount = (int) pScriptRefs->size();
4784               const int headerSize = 3 * sizeof(uint32_t);
4785               ckSCSL->SetPos(headerSize);
4786               for (int i = 0; i < slotCount; ++i) {
4787                   uint32_t fileOffset = uint32_t(
4788                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4789                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4790                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4791                   );
4792                   ckSCSL->WriteUint32(&fileOffset);
4793                   // jump over flags entry (containing the bypass flag)
4794                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4795               }
4796           }        
4797      }      }
4798    
4799      /**      /**
# Line 2927  namespace { Line 4848  namespace {
4848          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4849          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4850          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4851          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4852          // update Region key table for fast lookup          // update Region key table for fast lookup
4853          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4854          // done          // done
# Line 2941  namespace { Line 4862  namespace {
4862          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4863      }      }
4864    
4865        /**
4866         * Move this instrument at the position before @arg dst.
4867         *
4868         * This method can be used to reorder the sequence of instruments in a
4869         * .gig file. This might be helpful especially on large .gig files which
4870         * contain a large number of instruments within the same .gig file. So
4871         * grouping such instruments to similar ones, can help to keep track of them
4872         * when working with such complex .gig files.
4873         *
4874         * When calling this method, this instrument will be removed from in its
4875         * current position in the instruments list and moved to the requested
4876         * target position provided by @param dst. You may also pass NULL as
4877         * argument to this method, in that case this intrument will be moved to the
4878         * very end of the .gig file's instrument list.
4879         *
4880         * You have to call Save() to make the order change persistent to the .gig
4881         * file.
4882         *
4883         * Currently this method is limited to moving the instrument within the same
4884         * .gig file. Trying to move it to another .gig file by calling this method
4885         * will throw an exception.
4886         *
4887         * @param dst - destination instrument at which this instrument will be
4888         *              moved to, or pass NULL for moving to end of list
4889         * @throw gig::Exception if this instrument and target instrument are not
4890         *                       part of the same file
4891         */
4892        void Instrument::MoveTo(Instrument* dst) {
4893            if (dst && GetParent() != dst->GetParent())
4894                throw Exception(
4895                    "gig::Instrument::MoveTo() can only be used for moving within "
4896                    "the same gig file."
4897                );
4898    
4899            File* pFile = (File*) GetParent();
4900    
4901            // move this instrument within the instrument list
4902            {
4903                File::InstrumentList& list = *pFile->pInstruments;
4904    
4905                File::InstrumentList::iterator itFrom =
4906                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4907    
4908                File::InstrumentList::iterator itTo =
4909                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4910    
4911                list.splice(itTo, list, itFrom);
4912            }
4913    
4914            // move the instrument's actual list RIFF chunk appropriately
4915            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4916            lstCkInstruments->MoveSubChunk(
4917                this->pCkInstrument,
4918                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4919            );
4920        }
4921    
4922        /**
4923         * Returns a MIDI rule of the instrument.
4924         *
4925         * The list of MIDI rules, at least in gig v3, always contains at
4926         * most two rules. The second rule can only be the DEF filter
4927         * (which currently isn't supported by libgig).
4928         *
4929         * @param i - MIDI rule number
4930         * @returns   pointer address to MIDI rule number i or NULL if there is none
4931         */
4932        MidiRule* Instrument::GetMidiRule(int i) {
4933            return pMidiRules[i];
4934        }
4935    
4936        /**
4937         * Adds the "controller trigger" MIDI rule to the instrument.
4938         *
4939         * @returns the new MIDI rule
4940         */
4941        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4942            delete pMidiRules[0];
4943            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4944            pMidiRules[0] = r;
4945            pMidiRules[1] = 0;
4946            return r;
4947        }
4948    
4949        /**
4950         * Adds the legato MIDI rule to the instrument.
4951         *
4952         * @returns the new MIDI rule
4953         */
4954        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4955            delete pMidiRules[0];
4956            MidiRuleLegato* r = new MidiRuleLegato;
4957            pMidiRules[0] = r;
4958            pMidiRules[1] = 0;
4959            return r;
4960        }
4961    
4962        /**
4963         * Adds the alternator MIDI rule to the instrument.
4964         *
4965         * @returns the new MIDI rule
4966         */
4967        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4968            delete pMidiRules[0];
4969            MidiRuleAlternator* r = new MidiRuleAlternator;
4970            pMidiRules[0] = r;
4971            pMidiRules[1] = 0;
4972            return r;
4973        }
4974    
4975        /**
4976         * Deletes a MIDI rule from the instrument.
4977         *
4978         * @param i - MIDI rule number
4979         */
4980        void Instrument::DeleteMidiRule(int i) {
4981            delete pMidiRules[i];
4982            pMidiRules[i] = 0;
4983        }
4984    
4985        void Instrument::LoadScripts() {
4986            if (pScriptRefs) return;
4987            pScriptRefs = new std::vector<_ScriptPooolRef>;
4988            if (scriptPoolFileOffsets.empty()) return;
4989            File* pFile = (File*) GetParent();
4990            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4991                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4992                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4993                    ScriptGroup* group = pFile->GetScriptGroup(i);
4994                    for (uint s = 0; group->GetScript(s); ++s) {
4995                        Script* script = group->GetScript(s);
4996                        if (script->pChunk) {
4997                            uint32_t offset = uint32_t(
4998                                script->pChunk->GetFilePos() -
4999                                script->pChunk->GetPos() -
5000                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
5001                            );
5002                            if (offset == soughtOffset)
5003                            {
5004                                _ScriptPooolRef ref;
5005                                ref.script = script;
5006                                ref.bypass = scriptPoolFileOffsets[k].bypass;
5007                                pScriptRefs->push_back(ref);
5008                                break;
5009                            }
5010                        }
5011                    }
5012                }
5013            }
5014            // we don't need that anymore
5015            scriptPoolFileOffsets.clear();
5016        }
5017    
5018        /** @brief Get instrument script (gig format extension).
5019         *
5020         * Returns the real-time instrument script of instrument script slot
5021         * @a index.
5022         *
5023         * @note This is an own format extension which did not exist i.e. in the
5024         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5025         * gigedit.
5026         *
5027         * @param index - instrument script slot index
5028         * @returns script or NULL if index is out of bounds
5029         */
5030        Script* Instrument::GetScriptOfSlot(uint index) {
5031            LoadScripts();
5032            if (index >= pScriptRefs->size()) return NULL;
5033            return pScriptRefs->at(index).script;
5034        }
5035    
5036        /** @brief Add new instrument script slot (gig format extension).
5037         *
5038         * Add the given real-time instrument script reference to this instrument,
5039         * which shall be executed by the sampler for for this instrument. The
5040         * script will be added to the end of the script list of this instrument.
5041         * The positions of the scripts in the Instrument's Script list are
5042         * relevant, because they define in which order they shall be executed by
5043         * the sampler. For this reason it is also legal to add the same script
5044         * twice to an instrument, for example you might have a script called
5045         * "MyFilter" which performs an event filter task, and you might have
5046         * another script called "MyNoteTrigger" which triggers new notes, then you
5047         * might for example have the following list of scripts on the instrument:
5048         *
5049         * 1. Script "MyFilter"
5050         * 2. Script "MyNoteTrigger"
5051         * 3. Script "MyFilter"
5052         *
5053         * Which would make sense, because the 2nd script launched new events, which
5054         * you might need to filter as well.
5055         *
5056         * There are two ways to disable / "bypass" scripts. You can either disable
5057         * a script locally for the respective script slot on an instrument (i.e. by
5058         * passing @c false to the 2nd argument of this method, or by calling
5059         * SetScriptBypassed()). Or you can disable a script globally for all slots
5060         * and all instruments by setting Script::Bypass.
5061         *
5062         * @note This is an own format extension which did not exist i.e. in the
5063         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5064         * gigedit.
5065         *
5066         * @param pScript - script that shall be executed for this instrument
5067         * @param bypass  - if enabled, the sampler shall skip executing this
5068         *                  script (in the respective list position)
5069         * @see SetScriptBypassed()
5070         */
5071        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
5072            LoadScripts();
5073            _ScriptPooolRef ref = { pScript, bypass };
5074            pScriptRefs->push_back(ref);
5075        }
5076    
5077        /** @brief Flip two script slots with each other (gig format extension).
5078         *
5079         * Swaps the position of the two given scripts in the Instrument's Script
5080         * list. The positions of the scripts in the Instrument's Script list are
5081         * relevant, because they define in which order they shall be executed by
5082         * the sampler.
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 index1 - index of the first script slot to swap
5089         * @param index2 - index of the second script slot to swap
5090         */
5091        void Instrument::SwapScriptSlots(uint index1, uint index2) {
5092            LoadScripts();
5093            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
5094                return;
5095            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
5096            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
5097            (*pScriptRefs)[index2] = tmp;
5098        }
5099    
5100        /** @brief Remove script slot.
5101         *
5102         * Removes the script slot with the given slot index.
5103         *
5104         * @param index - index of script slot to remove
5105         */
5106        void Instrument::RemoveScriptSlot(uint index) {
5107            LoadScripts();
5108            if (index >= pScriptRefs->size()) return;
5109            pScriptRefs->erase( pScriptRefs->begin() + index );
5110        }
5111    
5112        /** @brief Remove reference to given Script (gig format extension).
5113         *
5114         * This will remove all script slots on the instrument which are referencing
5115         * the given script.
5116         *
5117         * @note This is an own format extension which did not exist i.e. in the
5118         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5119         * gigedit.
5120         *
5121         * @param pScript - script reference to remove from this instrument
5122         * @see RemoveScriptSlot()
5123         */
5124        void Instrument::RemoveScript(Script* pScript) {
5125            LoadScripts();
5126            for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5127                if ((*pScriptRefs)[i].script == pScript) {
5128                    pScriptRefs->erase( pScriptRefs->begin() + i );
5129                }
5130            }
5131        }
5132    
5133        /** @brief Instrument's amount of script slots.
5134         *
5135         * This method returns the amount of script slots this instrument currently
5136         * uses.
5137         *
5138         * A script slot is a reference of a real-time instrument script to be
5139         * executed by the sampler. The scripts will be executed by the sampler in
5140         * sequence of the slots. One (same) script may be referenced multiple
5141         * times in different slots.
5142         *
5143         * @note This is an own format extension which did not exist i.e. in the
5144         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5145         * gigedit.
5146         */
5147        uint Instrument::ScriptSlotCount() const {
5148            return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5149        }
5150    
5151        /** @brief Whether script execution shall be skipped.
5152         *
5153         * Defines locally for the Script reference slot in the Instrument's Script
5154         * list, whether the script shall be skipped by the sampler regarding
5155         * execution.
5156         *
5157         * It is also possible to ignore exeuction of the script globally, for all
5158         * slots and for all instruments by setting Script::Bypass.
5159         *
5160         * @note This is an own format extension which did not exist i.e. in the
5161         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5162         * gigedit.
5163         *
5164         * @param index - index of the script slot on this instrument
5165         * @see Script::Bypass
5166         */
5167        bool Instrument::IsScriptSlotBypassed(uint index) {
5168            if (index >= ScriptSlotCount()) return false;
5169            return pScriptRefs ? pScriptRefs->at(index).bypass
5170                               : scriptPoolFileOffsets.at(index).bypass;
5171            
5172        }
5173    
5174        /** @brief Defines whether execution shall be skipped.
5175         *
5176         * You can call this method to define locally whether or whether not the
5177         * given script slot shall be executed by the sampler.
5178         *
5179         * @note This is an own format extension which did not exist i.e. in the
5180         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5181         * gigedit.
5182         *
5183         * @param index - script slot index on this instrument
5184         * @param bBypass - if true, the script slot will be skipped by the sampler
5185         * @see Script::Bypass
5186         */
5187        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5188            if (index >= ScriptSlotCount()) return;
5189            if (pScriptRefs)
5190                pScriptRefs->at(index).bypass = bBypass;
5191            else
5192                scriptPoolFileOffsets.at(index).bypass = bBypass;
5193        }
5194    
5195        /**
5196         * Make a (semi) deep copy of the Instrument object given by @a orig
5197         * and assign it to this object.
5198         *
5199         * Note that all sample pointers referenced by @a orig are simply copied as
5200         * memory address. Thus the respective samples are shared, not duplicated!
5201         *
5202         * @param orig - original Instrument object to be copied from
5203         */
5204        void Instrument::CopyAssign(const Instrument* orig) {
5205            CopyAssign(orig, NULL);
5206        }
5207            
5208        /**
5209         * Make a (semi) deep copy of the Instrument object given by @a orig
5210         * and assign it to this object.
5211         *
5212         * @param orig - original Instrument object to be copied from
5213         * @param mSamples - crosslink map between the foreign file's samples and
5214         *                   this file's samples
5215         */
5216        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
5217            // handle base class
5218            // (without copying DLS region stuff)
5219            DLS::Instrument::CopyAssignCore(orig);
5220            
5221            // handle own member variables
5222            Attenuation = orig->Attenuation;
5223            EffectSend = orig->EffectSend;
5224            FineTune = orig->FineTune;
5225            PitchbendRange = orig->PitchbendRange;
5226            PianoReleaseMode = orig->PianoReleaseMode;
5227            DimensionKeyRange = orig->DimensionKeyRange;
5228            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5229            pScriptRefs = orig->pScriptRefs;
5230            
5231            // free old midi rules
5232            for (int i = 0 ; pMidiRules[i] ; i++) {
5233                delete pMidiRules[i];
5234            }
5235            //TODO: MIDI rule copying
5236            pMidiRules[0] = NULL;
5237            
5238            // delete all old regions
5239            while (Regions) DeleteRegion(GetFirstRegion());
5240            // create new regions and copy them from original
5241            {
5242                RegionList::const_iterator it = orig->pRegions->begin();
5243                for (int i = 0; i < orig->Regions; ++i, ++it) {
5244                    Region* dstRgn = AddRegion();
5245                    //NOTE: Region does semi-deep copy !
5246                    dstRgn->CopyAssign(
5247                        static_cast<gig::Region*>(*it),
5248                        mSamples
5249                    );
5250                }
5251            }
5252    
5253            UpdateRegionKeyTable();
5254        }
5255    
5256    
5257  // *************** Group ***************  // *************** Group ***************
# Line 2970  namespace { Line 5281  namespace {
5281       *       *
5282       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5283       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5284         *
5285         * @param pProgress - callback function for progress notification
5286       */       */
5287      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5288          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5289          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5290          if (!_3gri) {          if (!_3gri) {
# Line 3066  namespace { Line 5379  namespace {
5379  // *************** File ***************  // *************** File ***************
5380  // *  // *
5381    
5382      // File version 2.0, 1998-06-28      /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5383      const DLS::version_t File::VERSION_2 = {      const DLS::version_t File::VERSION_2 = {
5384          0, 2, 19980628 & 0xffff, 19980628 >> 16          0, 2, 19980628 & 0xffff, 19980628 >> 16
5385      };      };
5386    
5387      // File version 3.0, 2003-03-31      /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5388      const DLS::version_t File::VERSION_3 = {      const DLS::version_t File::VERSION_3 = {
5389          0, 3, 20030331 & 0xffff, 20030331 >> 16          0, 3, 20030331 & 0xffff, 20030331 >> 16
5390      };      };
5391    
5392      const DLS::Info::FixedStringLength File::FixedStringLengths[] = {      static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5393          { CHUNK_ID_IARL, 256 },          { CHUNK_ID_IARL, 256 },
5394          { CHUNK_ID_IART, 128 },          { CHUNK_ID_IART, 128 },
5395          { CHUNK_ID_ICMS, 128 },          { CHUNK_ID_ICMS, 128 },
# Line 3098  namespace { Line 5411  namespace {
5411      };      };
5412    
5413      File::File() : DLS::File() {      File::File() : DLS::File() {
5414            bAutoLoad = true;
5415          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5416          pGroups = NULL;          pGroups = NULL;
5417          pInfo->FixedStringLengths = FixedStringLengths;          pScriptGroups = NULL;
5418            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5419          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5420    
5421          // add some mandatory chunks to get the file chunks in right          // add some mandatory chunks to get the file chunks in right
# Line 3113  namespace { Line 5428  namespace {
5428      }      }
5429    
5430      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5431            bAutoLoad = true;
5432          pGroups = NULL;          pGroups = NULL;
5433          pInfo->FixedStringLengths = FixedStringLengths;          pScriptGroups = NULL;
5434            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5435      }      }
5436    
5437      File::~File() {      File::~File() {
# Line 3127  namespace { Line 5444  namespace {
5444              }              }
5445              delete pGroups;              delete pGroups;
5446          }          }
5447            if (pScriptGroups) {
5448                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5449                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5450                while (iter != end) {
5451                    delete *iter;
5452                    ++iter;
5453                }
5454                delete pScriptGroups;
5455            }
5456      }      }
5457    
5458      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 3141  namespace { Line 5467  namespace {
5467          SamplesIterator++;          SamplesIterator++;
5468          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5469      }      }
5470        
5471        /**
5472         * Returns Sample object of @a index.
5473         *
5474         * @returns sample object or NULL if index is out of bounds
5475         */
5476        Sample* File::GetSample(uint index) {
5477            if (!pSamples) LoadSamples();
5478            if (!pSamples) return NULL;
5479            DLS::File::SampleList::iterator it = pSamples->begin();
5480            for (int i = 0; i < index; ++i) {
5481                ++it;
5482                if (it == pSamples->end()) return NULL;
5483            }
5484            if (it == pSamples->end()) return NULL;
5485            return static_cast<gig::Sample*>( *it );
5486        }
5487    
5488      /** @brief Add a new sample.      /** @brief Add a new sample.
5489       *       *
# Line 3182  namespace { Line 5525  namespace {
5525          pSamples->erase(iter);          pSamples->erase(iter);
5526          delete pSample;          delete pSample;
5527    
5528            SampleList::iterator tmp = SamplesIterator;
5529          // remove all references to the sample          // remove all references to the sample
5530          for (Instrument* instrument = GetFirstInstrument() ; instrument ;          for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5531               instrument = GetNextInstrument()) {               instrument = GetNextInstrument()) {
# Line 3196  namespace { Line 5540  namespace {
5540                  }                  }
5541              }              }
5542          }          }
5543            SamplesIterator = tmp; // restore iterator
5544      }      }
5545    
5546      void File::LoadSamples() {      void File::LoadSamples() {
# Line 3216  namespace { Line 5561  namespace {
5561          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5562    
5563          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5564            // (only for old gig files < 2 GB)
5565          int lastFileNo = 0;          int lastFileNo = 0;
5566          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5567              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5568                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5569                }
5570          }          }
5571          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5572          int nameLen = name.length();          int nameLen = (int) name.length();
5573          char suffix[6];          char suffix[6];
5574          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5575    
5576          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5577              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5578              if (wvpl) {              if (wvpl) {
5579                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5580                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5581                  while (wave) {                  while (wave) {
5582                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 3236  namespace { Line 5584  namespace {
5584                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5585                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5586    
5587                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5588                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5589    
5590                          iSampleIndex++;                          iSampleIndex++;
5591                      }                      }
# Line 3286  namespace { Line 5634  namespace {
5634              progress_t subprogress;              progress_t subprogress;
5635              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask              __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
5636              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5637              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5638                    GetFirstSample(&subprogress); // now force all samples to be loaded
5639              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5640    
5641              // instrument loading subtask              // instrument loading subtask
# Line 3335  namespace { Line 5684  namespace {
5684         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5685         return pInstrument;         return pInstrument;
5686      }      }
5687        
5688        /** @brief Add a duplicate of an existing instrument.
5689         *
5690         * Duplicates the instrument definition given by @a orig and adds it
5691         * to this file. This allows in an instrument editor application to
5692         * easily create variations of an instrument, which will be stored in
5693         * the same .gig file, sharing i.e. the same samples.
5694         *
5695         * Note that all sample pointers referenced by @a orig are simply copied as
5696         * memory address. Thus the respective samples are shared, not duplicated!
5697         *
5698         * You have to call Save() to make this persistent to the file.
5699         *
5700         * @param orig - original instrument to be copied
5701         * @returns duplicated copy of the given instrument
5702         */
5703        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5704            Instrument* instr = AddInstrument();
5705            instr->CopyAssign(orig);
5706            return instr;
5707        }
5708        
5709        /** @brief Add content of another existing file.
5710         *
5711         * Duplicates the samples, groups and instruments of the original file
5712         * given by @a pFile and adds them to @c this File. In case @c this File is
5713         * a new one that you haven't saved before, then you have to call
5714         * SetFileName() before calling AddContentOf(), because this method will
5715         * automatically save this file during operation, which is required for
5716         * writing the sample waveform data by disk streaming.
5717         *
5718         * @param pFile - original file whose's content shall be copied from
5719         */
5720        void File::AddContentOf(File* pFile) {
5721            static int iCallCount = -1;
5722            iCallCount++;
5723            std::map<Group*,Group*> mGroups;
5724            std::map<Sample*,Sample*> mSamples;
5725            
5726            // clone sample groups
5727            for (int i = 0; pFile->GetGroup(i); ++i) {
5728                Group* g = AddGroup();
5729                g->Name =
5730                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5731                mGroups[pFile->GetGroup(i)] = g;
5732            }
5733            
5734            // clone samples (not waveform data here yet)
5735            for (int i = 0; pFile->GetSample(i); ++i) {
5736                Sample* s = AddSample();
5737                s->CopyAssignMeta(pFile->GetSample(i));
5738                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5739                mSamples[pFile->GetSample(i)] = s;
5740            }
5741    
5742            // clone script groups and their scripts
5743            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5744                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5745                ScriptGroup* dg = AddScriptGroup();
5746                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5747                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5748                    Script* ss = sg->GetScript(iScript);
5749                    Script* ds = dg->AddScript();
5750                    ds->CopyAssign(ss);
5751                }
5752            }
5753    
5754            //BUG: For some reason this method only works with this additional
5755            //     Save() call in between here.
5756            //
5757            // Important: The correct one of the 2 Save() methods has to be called
5758            // here, depending on whether the file is completely new or has been
5759            // saved to disk already, otherwise it will result in data corruption.
5760            if (pRIFF->IsNew())
5761                Save(GetFileName());
5762            else
5763                Save();
5764            
5765            // clone instruments
5766            // (passing the crosslink table here for the cloned samples)
5767            for (int i = 0; pFile->GetInstrument(i); ++i) {
5768                Instrument* instr = AddInstrument();
5769                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5770            }
5771            
5772            // Mandatory: file needs to be saved to disk at this point, so this
5773            // file has the correct size and data layout for writing the samples'
5774            // waveform data to disk.
5775            Save();
5776            
5777            // clone samples' waveform data
5778            // (using direct read & write disk streaming)
5779            for (int i = 0; pFile->GetSample(i); ++i) {
5780                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5781            }
5782        }
5783    
5784      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5785       *       *
# Line 3390  namespace { Line 5835  namespace {
5835          if (!_3crc) return;          if (!_3crc) return;
5836    
5837          // get the index of the sample          // get the index of the sample
5838          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;  
             }  
         }  
5839          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");
5840    
5841          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5842          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5843          uint32_t tmp = 1;          uint32_t one = 1;
5844          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5845          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5846      }      }
5847    
5848        uint32_t File::GetSampleChecksum(Sample* pSample) {
5849            // get the index of the sample
5850            int iWaveIndex = GetWaveTableIndexOf(pSample);
5851            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5852    
5853            return GetSampleChecksumByIndex(iWaveIndex);
5854        }
5855    
5856        uint32_t File::GetSampleChecksumByIndex(int index) {
5857            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5858    
5859            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5860            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5861            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5862            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5863    
5864            // read the CRC-32 checksum directly from disk
5865            size_t pos = index * 8;
5866            if (pos + 8 > _3crc->GetNewSize())
5867                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5868    
5869            uint32_t one = load32(&pData[pos]); // always 1
5870            if (one != 1)
5871                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5872    
5873            return load32(&pData[pos+4]);
5874        }
5875    
5876        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5877            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5878            File::SampleList::iterator iter = pSamples->begin();
5879            File::SampleList::iterator end  = pSamples->end();
5880            for (int index = 0; iter != end; ++iter, ++index)
5881                if (*iter == pSample)
5882                    return index;
5883            return -1;
5884        }
5885    
5886        /**
5887         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5888         * the CRC32 check sums of all samples' raw wave data.
5889         *
5890         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5891         */
5892        bool File::VerifySampleChecksumTable() {
5893            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5894            if (!_3crc) return false;
5895            if (_3crc->GetNewSize() <= 0) return false;
5896            if (_3crc->GetNewSize() % 8) return false;
5897            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5898            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5899    
5900            const file_offset_t n = _3crc->GetNewSize() / 8;
5901    
5902            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5903            if (!pData) return false;
5904    
5905            for (file_offset_t i = 0; i < n; ++i) {
5906                uint32_t one = pData[i*2];
5907                if (one != 1) return false;
5908            }
5909    
5910            return true;
5911        }
5912    
5913        /**
5914         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5915         * file's checksum table with those new checksums. This might usually
5916         * just be necessary if the checksum table was damaged.
5917         *
5918         * @e IMPORTANT: The current implementation of this method only works
5919         * with files that have not been modified since it was loaded, because
5920         * it expects that no externally caused file structure changes are
5921         * required!
5922         *
5923         * Due to the expectation above, this method is currently protected
5924         * and actually only used by the command line tool "gigdump" yet.
5925         *
5926         * @returns true if Save() is required to be called after this call,
5927         *          false if no further action is required
5928         */
5929        bool File::RebuildSampleChecksumTable() {
5930            // make sure sample chunks were scanned
5931            if (!pSamples) GetFirstSample();
5932    
5933            bool bRequiresSave = false;
5934    
5935            // make sure "3CRC" chunk exists with required size
5936            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5937            if (!_3crc) {
5938                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5939                // the order of einf and 3crc is not the same in v2 and v3
5940                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5941                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5942                bRequiresSave = true;
5943            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5944                _3crc->Resize(pSamples->size() * 8);
5945                bRequiresSave = true;
5946            }
5947    
5948            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5949                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5950                {
5951                    File::SampleList::iterator iter = pSamples->begin();
5952                    File::SampleList::iterator end  = pSamples->end();
5953                    for (; iter != end; ++iter) {
5954                        gig::Sample* pSample = (gig::Sample*) *iter;
5955                        int index = GetWaveTableIndexOf(pSample);
5956                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5957                        pData[index*2]   = 1; // always 1
5958                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5959                    }
5960                }
5961            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5962                // make sure file is in write mode
5963                pRIFF->SetMode(RIFF::stream_mode_read_write);
5964                {
5965                    File::SampleList::iterator iter = pSamples->begin();
5966                    File::SampleList::iterator end  = pSamples->end();
5967                    for (; iter != end; ++iter) {
5968                        gig::Sample* pSample = (gig::Sample*) *iter;
5969                        int index = GetWaveTableIndexOf(pSample);
5970                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5971                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5972                        SetSampleChecksum(pSample, pSample->crc);
5973                    }
5974                }
5975            }
5976    
5977            return bRequiresSave;
5978        }
5979    
5980      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5981          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5982          // there must always be at least one group          // there must always be at least one group
# Line 3437  namespace { Line 6006  namespace {
6006          return NULL;          return NULL;
6007      }      }
6008    
6009        /**
6010         * Returns the group with the given group name.
6011         *
6012         * Note: group names don't have to be unique in the gig format! So there
6013         * can be multiple groups with the same name. This method will simply
6014         * return the first group found with the given name.
6015         *
6016         * @param name - name of the sought group
6017         * @returns sought group or NULL if there's no group with that name
6018         */
6019        Group* File::GetGroup(String name) {
6020            if (!pGroups) LoadGroups();
6021            GroupsIterator = pGroups->begin();
6022            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
6023                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
6024            return NULL;
6025        }
6026    
6027      Group* File::AddGroup() {      Group* File::AddGroup() {
6028          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
6029          // there must always be at least one group          // there must always be at least one group
# Line 3517  namespace { Line 6104  namespace {
6104          }          }
6105      }      }
6106    
6107        /** @brief Get instrument script group (by index).
6108         *
6109         * Returns the real-time instrument script group with the given index.
6110         *
6111         * @param index - number of the sought group (0..n)
6112         * @returns sought script group or NULL if there's no such group
6113         */
6114        ScriptGroup* File::GetScriptGroup(uint index) {
6115            if (!pScriptGroups) LoadScriptGroups();
6116            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6117            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6118                if (i == index) return *it;
6119            return NULL;
6120        }
6121    
6122        /** @brief Get instrument script group (by name).
6123         *
6124         * Returns the first real-time instrument script group found with the given
6125         * group name. Note that group names may not necessarily be unique.
6126         *
6127         * @param name - name of the sought script group
6128         * @returns sought script group or NULL if there's no such group
6129         */
6130        ScriptGroup* File::GetScriptGroup(const String& name) {
6131            if (!pScriptGroups) LoadScriptGroups();
6132            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6133            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6134                if ((*it)->Name == name) return *it;
6135            return NULL;
6136        }
6137    
6138        /** @brief Add new instrument script group.
6139         *
6140         * Adds a new, empty real-time instrument script group to the file.
6141         *
6142         * You have to call Save() to make this persistent to the file.
6143         *
6144         * @return new empty script group
6145         */
6146        ScriptGroup* File::AddScriptGroup() {
6147            if (!pScriptGroups) LoadScriptGroups();
6148            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6149            pScriptGroups->push_back(pScriptGroup);
6150            return pScriptGroup;
6151        }
6152    
6153        /** @brief Delete an instrument script group.
6154         *
6155         * This will delete the given real-time instrument script group and all its
6156         * instrument scripts it contains. References inside instruments that are
6157         * using the deleted scripts will be removed from the respective instruments
6158         * accordingly.
6159         *
6160         * You have to call Save() to make this persistent to the file.
6161         *
6162         * @param pScriptGroup - script group to delete
6163         * @throws gig::Exception if given script group could not be found
6164         */
6165        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6166            if (!pScriptGroups) LoadScriptGroups();
6167            std::list<ScriptGroup*>::iterator iter =
6168                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6169            if (iter == pScriptGroups->end())
6170                throw gig::Exception("Could not delete script group, could not find given script group");
6171            pScriptGroups->erase(iter);
6172            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6173                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6174            if (pScriptGroup->pList)
6175                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6176            delete pScriptGroup;
6177        }
6178    
6179        void File::LoadScriptGroups() {
6180            if (pScriptGroups) return;
6181            pScriptGroups = new std::list<ScriptGroup*>;
6182            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6183            if (lstLS) {
6184                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6185                     lst = lstLS->GetNextSubList())
6186                {
6187                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6188                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6189                    }
6190                }
6191            }
6192        }
6193    
6194      /**      /**
6195       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6196       * 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 3525  namespace { Line 6199  namespace {
6199       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6200       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6201       *       *
6202         * @param pProgress - callback function for progress notification
6203       * @throws Exception - on errors       * @throws Exception - on errors
6204       */       */
6205      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6206          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6207    
6208          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6209            // (not part of the GigaStudio 4 format)
6210            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6211            if (!lst3LS) {
6212                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6213            }
6214            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6215            // location of <3LS > is irrelevant, however it should be located
6216            // before  the actual wave data
6217            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6218            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6219    
6220            // This must be performed before writing the chunks for instruments,
6221            // because the instruments' script slots will write the file offsets
6222            // of the respective instrument script chunk as reference.
6223            if (pScriptGroups) {
6224                // Update instrument script (group) chunks.
6225                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6226                     it != pScriptGroups->end(); ++it)
6227                {
6228                    (*it)->UpdateChunks(pProgress);
6229                }
6230            }
6231    
6232            // in case no libgig custom format data was added, then remove the
6233            // custom "3LS " chunk again
6234            if (!lst3LS->CountSubChunks()) {
6235                pRIFF->DeleteSubChunk(lst3LS);
6236                lst3LS = NULL;
6237            }
6238    
6239          // first update base class's chunks          // first update base class's chunks
6240          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6241    
6242          if (newFile) {          if (newFile) {
6243              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 3547  namespace { Line 6251  namespace {
6251    
6252          // update group's chunks          // update group's chunks
6253          if (pGroups) {          if (pGroups) {
6254              std::list<Group*>::iterator iter = pGroups->begin();              // make sure '3gri' and '3gnl' list chunks exist
6255              std::list<Group*>::iterator end  = pGroups->end();              // (before updating the Group chunks)
6256              for (; iter != end; ++iter) {              RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
6257                  (*iter)->UpdateChunks();              if (!_3gri) {
6258                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
6259                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
6260              }              }
6261                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
6262                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
6263    
6264              // v3: make sure the file has 128 3gnm chunks              // v3: make sure the file has 128 3gnm chunks
6265                // (before updating the Group chunks)
6266              if (pVersion && pVersion->major == 3) {              if (pVersion && pVersion->major == 3) {
                 RIFF::List* _3gnl = pRIFF->GetSubList(LIST_TYPE_3GRI)->GetSubList(LIST_TYPE_3GNL);  
6267                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();                  RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
6268                  for (int i = 0 ; i < 128 ; i++) {                  for (int i = 0 ; i < 128 ; i++) {
6269                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);                      if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
6270                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();                      if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
6271                  }                  }
6272              }              }
6273    
6274                std::list<Group*>::iterator iter = pGroups->begin();
6275                std::list<Group*>::iterator end  = pGroups->end();
6276                for (; iter != end; ++iter) {
6277                    (*iter)->UpdateChunks(pProgress);
6278                }
6279          }          }
6280    
6281          // update einf chunk          // update einf chunk
# Line 3580  namespace { Line 6294  namespace {
6294          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6295          // are set to zero.          // are set to zero.
6296    
6297          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6298          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6299    
6300          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 3653  namespace { Line 6367  namespace {
6367                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6368                  // next 8 bytes unknown                  // next 8 bytes unknown
6369                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6370                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6371                  // next 4 bytes unknown                  // next 4 bytes unknown
6372    
6373                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 3671  namespace { Line 6385  namespace {
6385              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6386              // next 8 bytes unknown              // next 8 bytes unknown
6387              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6388              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6389              // next 4 bytes unknown              // next 4 bytes unknown
6390          }          }
6391    
6392          // update 3crc chunk          // update 3crc chunk
6393    
6394          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6395          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6396          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6397            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6398            // member variable). This step is required, because samples might have
6399            // been deleted by the user since the file was opened, which in turn
6400            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6401            // If a sample was conciously modified by the user (that is if
6402            // Sample::Write() was called later on) then Sample::Write() will just
6403            // update the respective individual checksum(s) directly on disk and
6404            // leaves all other sample checksums untouched.
6405    
6406          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6407          if (_3crc) {          if (_3crc) {
6408              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6409          } else if (newFile) {          } else /*if (newFile)*/ {
6410              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6411              // 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
6412              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6413          }          }
6414            { // must be performed in RAM here ...
6415                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6416                if (pData) {
6417                    File::SampleList::iterator iter = pSamples->begin();
6418                    File::SampleList::iterator end  = pSamples->end();
6419                    for (int index = 0; iter != end; ++iter, ++index) {
6420                        gig::Sample* pSample = (gig::Sample*) *iter;
6421                        pData[index*2]   = 1; // always 1
6422                        pData[index*2+1] = pSample->crc;
6423                    }
6424                }
6425            }
6426        }
6427        
6428        void File::UpdateFileOffsets() {
6429            DLS::File::UpdateFileOffsets();
6430    
6431            for (Instrument* instrument = GetFirstInstrument(); instrument;
6432                 instrument = GetNextInstrument())
6433            {
6434                instrument->UpdateScriptFileOffsets();
6435            }
6436        }
6437    
6438        /**
6439         * Enable / disable automatic loading. By default this properyt is
6440         * enabled and all informations are loaded automatically. However
6441         * loading all Regions, DimensionRegions and especially samples might
6442         * take a long time for large .gig files, and sometimes one might only
6443         * be interested in retrieving very superficial informations like the
6444         * amount of instruments and their names. In this case one might disable
6445         * automatic loading to avoid very slow response times.
6446         *
6447         * @e CAUTION: by disabling this property many pointers (i.e. sample
6448         * references) and informations will have invalid or even undefined
6449         * data! This feature is currently only intended for retrieving very
6450         * superficial informations in a very fast way. Don't use it to retrieve
6451         * details like synthesis informations or even to modify .gig files!
6452         */
6453        void File::SetAutoLoad(bool b) {
6454            bAutoLoad = b;
6455        }
6456    
6457        /**
6458         * Returns whether automatic loading is enabled.
6459         * @see SetAutoLoad()
6460         */
6461        bool File::GetAutoLoad() {
6462            return bAutoLoad;
6463      }      }
6464    
6465    

Legend:
Removed from v.1335  
changed lines
  Added in v.3138

  ViewVC Help
Powered by ViewVC