/[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 858 by persson, Sat May 6 11:29:29 2006 UTC revision 2836 by persson, Sun Aug 23 05:57:18 2015 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2015 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  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
34  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 51  Line 53 
53    
54  namespace gig {  namespace gig {
55    
 // *************** 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;  
         }  
     }  
   
   
56  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
57  // *  // *
58    
# Line 111  namespace { Line 81  namespace {
81          return x & 0x800000 ? x - 0x1000000 : x;          return x & 0x800000 ? x - 0x1000000 : x;
82      }      }
83    
84        inline void store24(unsigned char* pDst, int x)
85        {
86            pDst[0] = x;
87            pDst[1] = x >> 8;
88            pDst[2] = x >> 16;
89        }
90    
91      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
92                        int srcStep, int dstStep,                        int srcStep, int dstStep,
93                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
# Line 150  namespace { Line 127  namespace {
127      }      }
128    
129      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
130                        int dstStep, const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
131                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
132                        unsigned long copysamples, int truncatedBits)                        unsigned long copysamples, int truncatedBits)
133      {      {
         // Note: The 24 bits are truncated to 16 bits for now.  
   
134          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
         const int shift = 8 - truncatedBits;  
135    
136  #define GET_PARAMS(params)                      \  #define GET_PARAMS(params)                      \
137          y    = get24(params);                   \          y    = get24(params);                   \
# Line 173  namespace { Line 147  namespace {
147    
148  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
149          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
150          *pDst = y >> shift;                     \          store24(pDst, y << truncatedBits);      \
151          pDst += dstStep          pDst += dstStep
152    
153          switch (compressionmode) {          switch (compressionmode) {
154              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
155                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
156                  while (copysamples) {                  while (copysamples) {
157                      *pDst = get24(pSrc) >> shift;                      store24(pDst, get24(pSrc) << truncatedBits);
158                      pDst += dstStep;                      pDst += dstStep;
159                      pSrc += 3;                      pSrc += 3;
160                      copysamples--;                      copysamples--;
# Line 250  namespace { Line 224  namespace {
224  }  }
225    
226    
227    
228    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
229    // *
230    
231        static uint32_t* __initCRCTable() {
232            static uint32_t res[256];
233    
234            for (int i = 0 ; i < 256 ; i++) {
235                uint32_t c = i;
236                for (int j = 0 ; j < 8 ; j++) {
237                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
238                }
239                res[i] = c;
240            }
241            return res;
242        }
243    
244        static const uint32_t* __CRCTable = __initCRCTable();
245    
246        /**
247         * Initialize a CRC variable.
248         *
249         * @param crc - variable to be initialized
250         */
251        inline static void __resetCRC(uint32_t& crc) {
252            crc = 0xffffffff;
253        }
254    
255        /**
256         * Used to calculate checksums of the sample data in a gig file. The
257         * checksums are stored in the 3crc chunk of the gig file and
258         * automatically updated when a sample is written with Sample::Write().
259         *
260         * One should call __resetCRC() to initialize the CRC variable to be
261         * used before calling this function the first time.
262         *
263         * After initializing the CRC variable one can call this function
264         * arbitrary times, i.e. to split the overall CRC calculation into
265         * steps.
266         *
267         * Once the whole data was processed by __calculateCRC(), one should
268         * call __encodeCRC() to get the final CRC result.
269         *
270         * @param buf     - pointer to data the CRC shall be calculated of
271         * @param bufSize - size of the data to be processed
272         * @param crc     - variable the CRC sum shall be stored to
273         */
274        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
275            for (int i = 0 ; i < bufSize ; i++) {
276                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
277            }
278        }
279    
280        /**
281         * Returns the final CRC result.
282         *
283         * @param crc - variable previously passed to __calculateCRC()
284         */
285        inline static uint32_t __encodeCRC(const uint32_t& crc) {
286            return crc ^ 0xffffffff;
287        }
288    
289    
290    
291    // *************** Other Internal functions  ***************
292    // *
293    
294        static split_type_t __resolveSplitType(dimension_t dimension) {
295            return (
296                dimension == dimension_layer ||
297                dimension == dimension_samplechannel ||
298                dimension == dimension_releasetrigger ||
299                dimension == dimension_keyboard ||
300                dimension == dimension_roundrobin ||
301                dimension == dimension_random ||
302                dimension == dimension_smartmidi ||
303                dimension == dimension_roundrobinkeyboard
304            ) ? split_type_bit : split_type_normal;
305        }
306    
307        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
308            return (dimension_definition.split_type == split_type_normal)
309            ? int(128.0 / dimension_definition.zones) : 0;
310        }
311    
312    
313    
314  // *************** Sample ***************  // *************** Sample ***************
315  // *  // *
316    
# Line 275  namespace { Line 336  namespace {
336       *                         is located, 0 otherwise       *                         is located, 0 otherwise
337       */       */
338      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, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
339            static const DLS::Info::string_length_t fixedStringLengths[] = {
340                { CHUNK_ID_INAM, 64 },
341                { 0, 0 }
342            };
343            pInfo->SetFixedStringLengths(fixedStringLengths);
344          Instances++;          Instances++;
345          FileNo = fileNo;          FileNo = fileNo;
346    
347            __resetCRC(crc);
348    
349          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
350          if (pCk3gix) {          if (pCk3gix) {
351              SampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
352                pGroup = pFile->GetGroup(iSampleGroup);
353          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
354              // use default value(s)              // by default assigned to that mandatory "Default Group"
355              SampleGroup = 0;              pGroup = pFile->GetGroup(0);
356          }          }
357    
358          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 307  namespace { Line 376  namespace {
376              // use default values              // use default values
377              Manufacturer  = 0;              Manufacturer  = 0;
378              Product       = 0;              Product       = 0;
379              SamplePeriod  = 1 / SamplesPerSecond;              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
380              MIDIUnityNote = 64;              MIDIUnityNote = 60;
381              FineTune      = 0;              FineTune      = 0;
382                SMPTEFormat   = smpte_format_no_offset;
383              SMPTEOffset   = 0;              SMPTEOffset   = 0;
384              Loops         = 0;              Loops         = 0;
385              LoopID        = 0;              LoopID        = 0;
386                LoopType      = loop_type_normal;
387              LoopStart     = 0;              LoopStart     = 0;
388              LoopEnd       = 0;              LoopEnd       = 0;
389              LoopFraction  = 0;              LoopFraction  = 0;
# Line 348  namespace { Line 419  namespace {
419          }          }
420          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
421    
422          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
423        }
424    
425        /**
426         * Make a (semi) deep copy of the Sample object given by @a orig (without
427         * the actual waveform data) and assign it to this object.
428         *
429         * Discussion: copying .gig samples is a bit tricky. It requires three
430         * steps:
431         * 1. Copy sample's meta informations (done by CopyAssignMeta()) including
432         *    its new sample waveform data size.
433         * 2. Saving the file (done by File::Save()) so that it gains correct size
434         *    and layout for writing the actual wave form data directly to disc
435         *    in next step.
436         * 3. Copy the waveform data with disk streaming (done by CopyAssignWave()).
437         *
438         * @param orig - original Sample object to be copied from
439         */
440        void Sample::CopyAssignMeta(const Sample* orig) {
441            // handle base classes
442            DLS::Sample::CopyAssignCore(orig);
443            
444            // handle actual own attributes of this class
445            Manufacturer = orig->Manufacturer;
446            Product = orig->Product;
447            SamplePeriod = orig->SamplePeriod;
448            MIDIUnityNote = orig->MIDIUnityNote;
449            FineTune = orig->FineTune;
450            SMPTEFormat = orig->SMPTEFormat;
451            SMPTEOffset = orig->SMPTEOffset;
452            Loops = orig->Loops;
453            LoopID = orig->LoopID;
454            LoopType = orig->LoopType;
455            LoopStart = orig->LoopStart;
456            LoopEnd = orig->LoopEnd;
457            LoopSize = orig->LoopSize;
458            LoopFraction = orig->LoopFraction;
459            LoopPlayCount = orig->LoopPlayCount;
460            
461            // schedule resizing this sample to the given sample's size
462            Resize(orig->GetSize());
463        }
464    
465        /**
466         * Should be called after CopyAssignMeta() and File::Save() sequence.
467         * Read more about it in the discussion of CopyAssignMeta(). This method
468         * copies the actual waveform data by disk streaming.
469         *
470         * @e CAUTION: this method is currently not thread safe! During this
471         * operation the sample must not be used for other purposes by other
472         * threads!
473         *
474         * @param orig - original Sample object to be copied from
475         */
476        void Sample::CopyAssignWave(const Sample* orig) {
477            const int iReadAtOnce = 32*1024;
478            char* buf = new char[iReadAtOnce * orig->FrameSize];
479            Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
480            unsigned long restorePos = pOrig->GetPos();
481            pOrig->SetPos(0);
482            SetPos(0);
483            for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;
484                               n = pOrig->Read(buf, iReadAtOnce))
485            {
486                Write(buf, n);
487            }
488            pOrig->SetPos(restorePos);
489            delete [] buf;
490      }      }
491    
492      /**      /**
# Line 358  namespace { Line 496  namespace {
496       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
497       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
498       *       *
499       * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @param pProgress - callback function for progress notification
500         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
501       *                        was provided yet       *                        was provided yet
502       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
503       */       */
504      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
505          // first update base class's chunks          // first update base class's chunks
506          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
507    
508          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
509          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
510          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) {
511                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
512                memset(pCkSmpl->LoadChunkData(), 0, 60);
513            }
514          // update 'smpl' chunk          // update 'smpl' chunk
515          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
516          SamplePeriod = 1 / SamplesPerSecond;          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
517          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
518          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
519          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
520          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
521          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
522          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
523          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
524          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
525    
526          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
527    
528          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
529          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
530          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
531          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
532          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
533          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
534    
535          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
536          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
537          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
538            // determine appropriate sample group index (to be stored in chunk)
539            uint16_t iSampleGroup = 0; // 0 refers to default sample group
540            File* pFile = static_cast<File*>(pParent);
541            if (pFile->pGroups) {
542                std::list<Group*>::iterator iter = pFile->pGroups->begin();
543                std::list<Group*>::iterator end  = pFile->pGroups->end();
544                for (int i = 0; iter != end; i++, iter++) {
545                    if (*iter == pGroup) {
546                        iSampleGroup = i;
547                        break; // found
548                    }
549                }
550            }
551          // update '3gix' chunk          // update '3gix' chunk
552          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
553          memcpy(&pData[0], &SampleGroup, 2);          store16(&pData[0], iSampleGroup);
554    
555            // if the library user toggled the "Compressed" attribute from true to
556            // false, then the EWAV chunk associated with compressed samples needs
557            // to be deleted
558            RIFF::Chunk* ewav = pWaveList->GetSubChunk(CHUNK_ID_EWAV);
559            if (ewav && !Compressed) {
560                pWaveList->DeleteSubChunk(ewav);
561            }
562      }      }
563    
564      /// 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).
# Line 559  namespace { Line 722  namespace {
722          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
723          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
724          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
725            SetPos(0); // reset read position to begin of sample
726          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
727          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
728          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;          RAMCache.NullExtensionSize = allocationsize - RAMCache.Size;
# Line 596  namespace { Line 760  namespace {
760          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
761          RAMCache.pStart = NULL;          RAMCache.pStart = NULL;
762          RAMCache.Size   = 0;          RAMCache.Size   = 0;
763            RAMCache.NullExtensionSize = 0;
764      }      }
765    
766      /** @brief Resize sample.      /** @brief Resize sample.
# Line 616  namespace { Line 781  namespace {
781       * enlarged samples before calling File::Save() as this might exceed the       * enlarged samples before calling File::Save() as this might exceed the
782       * current sample's boundary!       * current sample's boundary!
783       *       *
784       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
785       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
786       * other formats will fail!       * other formats will fail!
787       *       *
788       * @param iNewSize - new sample wave data size in sample points (must be       * @param iNewSize - new sample wave data size in sample points (must be
789       *                   greater than zero)       *                   greater than zero)
790       * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
791       *                         or if \a iNewSize is less than 1       *                         or if \a iNewSize is less than 1
792       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
793       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
# Line 688  namespace { Line 853  namespace {
853      /**      /**
854       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
855       */       */
856      unsigned long Sample::GetPos() {      unsigned long Sample::GetPos() const {
857          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
858          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
859      }      }
# Line 722  namespace { Line 887  namespace {
887       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
888       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
889       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
890         * @param pDimRgn          dimension region with looping information
891       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
892       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
893       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
894       */       */
895      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
896                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
897          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
898          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
899    
900          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
901    
902          if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined          if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
903    
904              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
905                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
906    
907                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
908                      do {                  switch (loop.LoopType) {
                         // if not endless loop check if max. number of loop cycles have been passed  
                         if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;  
   
                         if (!pPlaybackState->reverse) { // forward playback  
                             do {  
                                 samplestoloopend  = this->LoopEnd - GetPos();  
                                 readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);  
                                 samplestoread    -= readsamples;  
                                 totalreadsamples += readsamples;  
                                 if (readsamples == samplestoloopend) {  
                                     pPlaybackState->reverse = true;  
                                     break;  
                                 }  
                             } while (samplestoread && readsamples);  
                         }  
                         else { // backward playback  
909    
910                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
911                              // determine the end position within the loop first,                          do {
912                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
913                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
914                              // backward playback  
915                                if (!pPlaybackState->reverse) { // forward playback
916                              unsigned long swapareastart       = totalreadsamples;                                  do {
917                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
918                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
919                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
920                                        totalreadsamples += readsamples;
921                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
922                                            pPlaybackState->reverse = true;
923                              // read samples for backward playback                                          break;
924                              do {                                      }
925                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
926                                  samplestoreadinloop -= readsamples;                              }
927                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
928    
929                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
930                                    // determine the end position within the loop first,
931                                    // read forward from that 'end' and finally after
932                                    // reading, swap all sample frames so it reflects
933                                    // backward playback
934    
935                                    unsigned long swapareastart       = totalreadsamples;
936                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
937                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
938                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
939    
940                                    SetPos(reverseplaybackend);
941    
942                                    // read samples for backward playback
943                                    do {
944                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
945                                        samplestoreadinloop -= readsamples;
946                                        samplestoread       -= readsamples;
947                                        totalreadsamples    += readsamples;
948                                    } while (samplestoreadinloop && readsamples);
949    
950                                    SetPos(reverseplaybackend); // pretend we really read backwards
951    
952                                    if (reverseplaybackend == loop.LoopStart) {
953                                        pPlaybackState->loop_cycles_left--;
954                                        pPlaybackState->reverse = false;
955                                    }
956    
957                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
958                                  pPlaybackState->loop_cycles_left--;                                  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!
959                                  pPlaybackState->reverse = false;                                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
960                              }                              }
961                            } while (samplestoread && readsamples);
962                            break;
963                        }
964    
965                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
966                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
967                          }                          if (!pPlaybackState->reverse) do {
968                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
969                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
970                  }                              samplestoread    -= readsamples;
971                                totalreadsamples += readsamples;
972                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
973                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
974                      if (!pPlaybackState->reverse) do {                                  break;
975                          samplestoloopend  = this->LoopEnd - GetPos();                              }
976                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                          } while (samplestoread && readsamples);
                         samplestoread    -= readsamples;  
                         totalreadsamples += readsamples;  
                         if (readsamples == samplestoloopend) {  
                             pPlaybackState->reverse = true;  
                             break;  
                         }  
                     } while (samplestoread && readsamples);  
977    
978                      if (!samplestoread) break;                          if (!samplestoread) break;
979    
980                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
981                      // determine the end position within the loop first,                          // determine the end position within the loop first,
982                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
983                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
984                      // backward playback                          // backward playback
985    
986                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
987                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
988                      unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
989                                                                                : samplestoread;                                                                                    : samplestoread;
990                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
991    
992                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
993    
994                      // read samples for backward playback                          // read samples for backward playback
995                      do {                          do {
996                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
997                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
998                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
999                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
1000                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
1001                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
1002                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
1003                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1004                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1005                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1006                          }                              }
1007                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
1008    
1009                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
1010    
1011                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
1012                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
1013                      break;                          break;
1014                  }                      }
1015    
1016                  default: case loop_type_normal: {                      default: case loop_type_normal: {
1017                      do {                          do {
1018                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
1019                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
1020                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
1021                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
1022                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
1023                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
1024                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
1025                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
1026                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
1027                          }                              }
1028                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
1029                      break;                          break;
1030                        }
1031                  }                  }
1032              }              }
1033          }          }
# Line 884  namespace { Line 1057  namespace {
1057       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
1058       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
1059       *       *
1060         * For 16 bit samples, the data in the buffer will be int16_t
1061         * (using native endianness). For 24 bit, the buffer will
1062         * contain three bytes per sample, little-endian.
1063         *
1064       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1065       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1066       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 894  namespace { Line 1071  namespace {
1071          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1072          if (!Compressed) {          if (!Compressed) {
1073              if (BitDepth == 24) {              if (BitDepth == 24) {
1074                  // 24 bit sample. For now just truncate to 16 bit.                  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
                 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);  
                 int16_t* pDst = static_cast<int16_t*>(pBuffer);  
                 if (Channels == 2) { // Stereo  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;  
                 }  
                 else { // Mono  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return pDst - static_cast<int16_t*>(pBuffer);  
                 }  
1075              }              }
1076              else { // 16 bit              else { // 16 bit
1077                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 944  namespace { Line 1101  namespace {
1101    
1102              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1103              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1104                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1105              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1106    
1107              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 1025  namespace { Line 1183  namespace {
1183                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1184                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1185    
1186                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1187                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1188                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1189                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1190                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1191                          }                          }
1192                          else { // Mono                          else { // Mono
1193                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1194                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1195                              pDst += copysamples;                              pDst24 += copysamples * 3;
1196                          }                          }
1197                      }                      }
1198                      else { // 16 bit                      else { // 16 bit
# Line 1088  namespace { Line 1246  namespace {
1246       *       *
1247       * Note: there is currently no support for writing compressed samples.       * Note: there is currently no support for writing compressed samples.
1248       *       *
1249         * For 16 bit samples, the data in the source buffer should be
1250         * int16_t (using native endianness). For 24 bit, the buffer
1251         * should contain three bytes per sample, little-endian.
1252         *
1253       * @param pBuffer     - source buffer       * @param pBuffer     - source buffer
1254       * @param SampleCount - number of sample points to write       * @param SampleCount - number of sample points to write
1255       * @throws DLS::Exception if current sample size is too small       * @throws DLS::Exception if current sample size is too small
# Line 1096  namespace { Line 1258  namespace {
1258       */       */
1259      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1260          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)");
1261          return DLS::Sample::Write(pBuffer, SampleCount);  
1262            // if this is the first write in this sample, reset the
1263            // checksum calculator
1264            if (pCkData->GetPos() == 0) {
1265                __resetCRC(crc);
1266            }
1267            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1268            unsigned long res;
1269            if (BitDepth == 24) {
1270                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1271            } else { // 16 bit
1272                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1273                                    : pCkData->Write(pBuffer, SampleCount, 2);
1274            }
1275            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1276    
1277            // if this is the last write, update the checksum chunk in the
1278            // file
1279            if (pCkData->GetPos() == pCkData->GetSize()) {
1280                File* pFile = static_cast<File*>(GetParent());
1281                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1282            }
1283            return res;
1284      }      }
1285    
1286      /**      /**
# Line 1141  namespace { Line 1325  namespace {
1325          }          }
1326      }      }
1327    
1328        /**
1329         * Returns pointer to the Group this Sample belongs to. In the .gig
1330         * format a sample always belongs to one group. If it wasn't explicitly
1331         * assigned to a certain group, it will be automatically assigned to a
1332         * default group.
1333         *
1334         * @returns Sample's Group (never NULL)
1335         */
1336        Group* Sample::GetGroup() const {
1337            return pGroup;
1338        }
1339    
1340      Sample::~Sample() {      Sample::~Sample() {
1341          Instances--;          Instances--;
1342          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1160  namespace { Line 1356  namespace {
1356      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1357      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1358    
1359      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1360          Instances++;          Instances++;
1361    
1362          pSample = NULL;          pSample = NULL;
1363            pRegion = pParent;
1364    
1365            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1366            else memset(&Crossfade, 0, 4);
1367    
         memcpy(&Crossfade, &SamplerOptions, 4);  
1368          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1369    
1370          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1371          if (_3ewa) { // if '3ewa' chunk exists          if (_3ewa) { // if '3ewa' chunk exists
1372              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1373              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1374              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1375              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
# Line 1279  namespace { Line 1478  namespace {
1478                                                          : vcf_res_ctrl_none;                                                          : vcf_res_ctrl_none;
1479              uint16_t eg3depth = _3ewa->ReadUint16();              uint16_t eg3depth = _3ewa->ReadUint16();
1480              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1481                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */                                          : (-1) * (int16_t) ((eg3depth ^ 0xfff) + 1); /* binary complementary for negatives */
1482              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1483              ChannelOffset = _3ewa->ReadUint8() / 4;              ChannelOffset = _3ewa->ReadUint8() / 4;
1484              uint8_t regoptions = _3ewa->ReadUint8();              uint8_t regoptions = _3ewa->ReadUint8();
# Line 1315  namespace { Line 1514  namespace {
1514                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1515                      VCFType = vcf_type_lowpassturbo;                      VCFType = vcf_type_lowpassturbo;
1516              }              }
1517                if (_3ewa->RemainingBytes() >= 8) {
1518                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1519                } else {
1520                    memset(DimensionUpperLimits, 0, 8);
1521                }
1522          } else { // '3ewa' chunk does not exist yet          } else { // '3ewa' chunk does not exist yet
1523              // use default values              // use default values
1524              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1324  namespace { Line 1528  namespace {
1528              LFO1ControlDepth                = 0;              LFO1ControlDepth                = 0;
1529              LFO3ControlDepth                = 0;              LFO3ControlDepth                = 0;
1530              EG1Attack                       = 0.0;              EG1Attack                       = 0.0;
1531              EG1Decay1                       = 0.0;              EG1Decay1                       = 0.005;
1532              EG1Sustain                      = 0;              EG1Sustain                      = 1000;
1533              EG1Release                      = 0.0;              EG1Release                      = 0.3;
1534              EG1Controller.type              = eg1_ctrl_t::type_none;              EG1Controller.type              = eg1_ctrl_t::type_none;
1535              EG1Controller.controller_number = 0;              EG1Controller.controller_number = 0;
1536              EG1ControllerInvert             = false;              EG1ControllerInvert             = false;
# Line 1341  namespace { Line 1545  namespace {
1545              EG2ControllerReleaseInfluence   = 0;              EG2ControllerReleaseInfluence   = 0;
1546              LFO1Frequency                   = 1.0;              LFO1Frequency                   = 1.0;
1547              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1548              EG2Decay1                       = 0.0;              EG2Decay1                       = 0.005;
1549              EG2Sustain                      = 0;              EG2Sustain                      = 1000;
1550              EG2Release                      = 0.0;              EG2Release                      = 0.3;
1551              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1552              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1553              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
1554              EG1Decay2                       = 0.0;              EG1Decay2                       = 0.0;
1555              EG1InfiniteSustain              = false;              EG1InfiniteSustain              = true;
1556              EG1PreAttack                    = 1000;              EG1PreAttack                    = 0;
1557              EG2Decay2                       = 0.0;              EG2Decay2                       = 0.0;
1558              EG2InfiniteSustain              = false;              EG2InfiniteSustain              = true;
1559              EG2PreAttack                    = 1000;              EG2PreAttack                    = 0;
1560              VelocityResponseCurve           = curve_type_nonlinear;              VelocityResponseCurve           = curve_type_nonlinear;
1561              VelocityResponseDepth           = 3;              VelocityResponseDepth           = 3;
1562              ReleaseVelocityResponseCurve    = curve_type_nonlinear;              ReleaseVelocityResponseCurve    = curve_type_nonlinear;
# Line 1395  namespace { Line 1599  namespace {
1599              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1600              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1601              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1602                memset(DimensionUpperLimits, 127, 8);
1603          }          }
1604    
1605          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1606                                                       VelocityResponseDepth,                                                       VelocityResponseDepth,
1607                                                       VelocityResponseCurveScaling);                                                       VelocityResponseCurveScaling);
1608    
1609          curve_type_t curveType = ReleaseVelocityResponseCurve;          pVelocityReleaseTable = GetReleaseVelocityTable(
1610          uint8_t depth = ReleaseVelocityResponseDepth;                                      ReleaseVelocityResponseCurve,
1611                                        ReleaseVelocityResponseDepth
1612                                    );
1613    
1614            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1615                                                          VCFVelocityDynamicRange,
1616                                                          VCFVelocityScale,
1617                                                          VCFCutoffController);
1618    
1619          // this models a strange behaviour or bug in GSt: two of the          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1620          // velocity response curves for release time are not used even          VelocityTable = 0;
1621          // if specified, instead another curve is chosen.      }
         if ((curveType == curve_type_nonlinear && depth == 0) ||  
             (curveType == curve_type_special   && depth == 4)) {  
             curveType = curve_type_nonlinear;  
             depth = 3;  
         }  
         pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);  
1622    
1623          curveType = VCFVelocityCurve;      /*
1624          depth = VCFVelocityDynamicRange;       * Constructs a DimensionRegion by copying all parameters from
1625         * another DimensionRegion
1626         */
1627        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1628            Instances++;
1629            //NOTE: I think we cannot call CopyAssign() here (in a constructor) as long as its a virtual method
1630            *this = src; // default memberwise shallow copy of all parameters
1631            pParentList = _3ewl; // restore the chunk pointer
1632    
1633            // deep copy of owned structures
1634            if (src.VelocityTable) {
1635                VelocityTable = new uint8_t[128];
1636                for (int k = 0 ; k < 128 ; k++)
1637                    VelocityTable[k] = src.VelocityTable[k];
1638            }
1639            if (src.pSampleLoops) {
1640                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1641                for (int k = 0 ; k < src.SampleLoops ; k++)
1642                    pSampleLoops[k] = src.pSampleLoops[k];
1643            }
1644        }
1645        
1646        /**
1647         * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1648         * and assign it to this object.
1649         *
1650         * Note that all sample pointers referenced by @a orig are simply copied as
1651         * memory address. Thus the respective samples are shared, not duplicated!
1652         *
1653         * @param orig - original DimensionRegion object to be copied from
1654         */
1655        void DimensionRegion::CopyAssign(const DimensionRegion* orig) {
1656            CopyAssign(orig, NULL);
1657        }
1658    
1659          // even stranger GSt: two of the velocity response curves for      /**
1660          // filter cutoff are not used, instead another special curve       * Make a (semi) deep copy of the DimensionRegion object given by @a orig
1661          // is chosen. This curve is not used anywhere else.       * and assign it to this object.
1662          if ((curveType == curve_type_nonlinear && depth == 0) ||       *
1663              (curveType == curve_type_special   && depth == 4)) {       * @param orig - original DimensionRegion object to be copied from
1664              curveType = curve_type_special;       * @param mSamples - crosslink map between the foreign file's samples and
1665              depth = 5;       *                   this file's samples
1666         */
1667        void DimensionRegion::CopyAssign(const DimensionRegion* orig, const std::map<Sample*,Sample*>* mSamples) {
1668            // delete all allocated data first
1669            if (VelocityTable) delete [] VelocityTable;
1670            if (pSampleLoops) delete [] pSampleLoops;
1671            
1672            // backup parent list pointer
1673            RIFF::List* p = pParentList;
1674            
1675            gig::Sample* pOriginalSample = pSample;
1676            gig::Region* pOriginalRegion = pRegion;
1677            
1678            //NOTE: copy code copied from assignment constructor above, see comment there as well
1679            
1680            *this = *orig; // default memberwise shallow copy of all parameters
1681            
1682            // restore members that shall not be altered
1683            pParentList = p; // restore the chunk pointer
1684            pRegion = pOriginalRegion;
1685            
1686            // only take the raw sample reference reference if the
1687            // two DimensionRegion objects are part of the same file
1688            if (pOriginalRegion->GetParent()->GetParent() != orig->pRegion->GetParent()->GetParent()) {
1689                pSample = pOriginalSample;
1690            }
1691            
1692            if (mSamples && mSamples->count(orig->pSample)) {
1693                pSample = mSamples->find(orig->pSample)->second;
1694            }
1695    
1696            // deep copy of owned structures
1697            if (orig->VelocityTable) {
1698                VelocityTable = new uint8_t[128];
1699                for (int k = 0 ; k < 128 ; k++)
1700                    VelocityTable[k] = orig->VelocityTable[k];
1701            }
1702            if (orig->pSampleLoops) {
1703                pSampleLoops = new DLS::sample_loop_t[orig->SampleLoops];
1704                for (int k = 0 ; k < orig->SampleLoops ; k++)
1705                    pSampleLoops[k] = orig->pSampleLoops[k];
1706          }          }
1707          pVelocityCutoffTable = GetVelocityTable(curveType, depth,      }
                                                 VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);  
1708    
1709        /**
1710         * Updates the respective member variable and updates @c SampleAttenuation
1711         * which depends on this value.
1712         */
1713        void DimensionRegion::SetGain(int32_t gain) {
1714            DLS::Sampler::SetGain(gain);
1715          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
         VelocityTable = 0;  
1716      }      }
1717    
1718      /**      /**
# Line 1438  namespace { Line 1721  namespace {
1721       *       *
1722       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1723       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1724         *
1725         * @param pProgress - callback function for progress notification
1726       */       */
1727      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1728          // first update base class's chunk          // first update base class's chunk
1729          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1730    
1731            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1732            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1733            pData[12] = Crossfade.in_start;
1734            pData[13] = Crossfade.in_end;
1735            pData[14] = Crossfade.out_start;
1736            pData[15] = Crossfade.out_end;
1737    
1738          // make sure '3ewa' chunk exists          // make sure '3ewa' chunk exists
1739          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1740          if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);          if (!_3ewa) {
1741          uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();              File* pFile = (File*) GetParent()->GetParent()->GetParent();
1742                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1743                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1744            }
1745            pData = (uint8_t*) _3ewa->LoadChunkData();
1746    
1747          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1748    
1749          const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?          const uint32_t chunksize = _3ewa->GetNewSize();
1750          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1751    
1752          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1753          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1754    
1755          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1756          memcpy(&pData[4], &eg3attack, 4);          store32(&pData[8], eg3attack);
1757    
1758          // next 2 bytes unknown          // next 2 bytes unknown
1759    
1760          memcpy(&pData[10], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1761    
1762          // next 2 bytes unknown          // next 2 bytes unknown
1763    
1764          memcpy(&pData[14], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1765    
1766          // next 2 bytes unknown          // next 2 bytes unknown
1767    
1768          memcpy(&pData[18], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1769    
1770          // next 2 bytes unknown          // next 2 bytes unknown
1771    
1772          memcpy(&pData[22], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1773    
1774          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1775          memcpy(&pData[24], &eg1attack, 4);          store32(&pData[28], eg1attack);
1776    
1777          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1778          memcpy(&pData[28], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1779    
1780          // next 2 bytes unknown          // next 2 bytes unknown
1781    
1782          memcpy(&pData[34], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1783    
1784          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1785          memcpy(&pData[36], &eg1release, 4);          store32(&pData[40], eg1release);
1786    
1787          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1788          memcpy(&pData[40], &eg1ctl, 1);          pData[44] = eg1ctl;
1789    
1790          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1791              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert ? 0x01 : 0x00) |
1792              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1793              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1794              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1795          memcpy(&pData[41], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1796    
1797          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1798          memcpy(&pData[42], &eg2ctl, 1);          pData[46] = eg2ctl;
1799    
1800          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1801              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert ? 0x01 : 0x00) |
1802              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1803              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1804              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1805          memcpy(&pData[43], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1806    
1807          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1808          memcpy(&pData[44], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1809    
1810          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1811          memcpy(&pData[48], &eg2attack, 4);          store32(&pData[52], eg2attack);
1812    
1813          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1814          memcpy(&pData[52], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1815    
1816          // next 2 bytes unknown          // next 2 bytes unknown
1817    
1818          memcpy(&pData[58], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1819    
1820          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1821          memcpy(&pData[60], &eg2release, 4);          store32(&pData[64], eg2release);
1822    
1823          // next 2 bytes unknown          // next 2 bytes unknown
1824    
1825          memcpy(&pData[66], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1826    
1827          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1828          memcpy(&pData[68], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1829    
1830          // next 2 bytes unknown          // next 2 bytes unknown
1831    
1832          memcpy(&pData[72], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1833    
1834          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1835          memcpy(&pData[74], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1836    
1837          // next 2 bytes unknown          // next 2 bytes unknown
1838    
1839          memcpy(&pData[80], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1840    
1841          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1842          memcpy(&pData[82], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1843    
1844          // next 2 bytes unknown          // next 2 bytes unknown
1845    
1846          memcpy(&pData[88], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1847    
1848          {          {
1849              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
# Line 1565  namespace { Line 1861  namespace {
1861                  default:                  default:
1862                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1863              }              }
1864              memcpy(&pData[90], &velocityresponse, 1);              pData[96] = velocityresponse;
1865          }          }
1866    
1867          {          {
# Line 1584  namespace { Line 1880  namespace {
1880                  default:                  default:
1881                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1882              }              }
1883              memcpy(&pData[91], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1884          }          }
1885    
1886          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1887    
1888          memcpy(&pData[93], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1889    
1890          // next 4 bytes unknown          // next 4 bytes unknown
1891    
1892          memcpy(&pData[98], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1893    
1894          // next 2 bytes unknown          // next 2 bytes unknown
1895    
# Line 1612  namespace { Line 1908  namespace {
1908                  default:                  default:
1909                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1910              }              }
1911              memcpy(&pData[102], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1912          }          }
1913    
1914          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1915          memcpy(&pData[103], &pan, 1);          pData[109] = pan;
1916    
1917          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1918          memcpy(&pData[104], &selfmask, 1);          pData[110] = selfmask;
1919    
1920          // next byte unknown          // next byte unknown
1921    
# Line 1628  namespace { Line 1924  namespace {
1924              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1925              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1926              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1927              memcpy(&pData[106], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1928          }          }
1929    
1930          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1931          memcpy(&pData[107], &attenctl, 1);          pData[113] = attenctl;
1932    
1933          {          {
1934              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1935              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1936              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1937              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1938              memcpy(&pData[108], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1939          }          }
1940    
1941          {          {
# Line 1648  namespace { Line 1944  namespace {
1944              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1945              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1946                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1947              memcpy(&pData[109], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1948          }          }
1949    
1950          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1951                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xfff); /* binary complementary for negatives */
1952          memcpy(&pData[110], &eg3depth, 1);          store16(&pData[116], eg3depth);
1953    
1954          // next 2 bytes unknown          // next 2 bytes unknown
1955    
1956          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1957          memcpy(&pData[113], &channeloffset, 1);          pData[120] = channeloffset;
1958    
1959          {          {
1960              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1961              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1962              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1963              memcpy(&pData[114], &regoptions, 1);              pData[121] = regoptions;
1964          }          }
1965    
1966          // next 2 bytes unknown          // next 2 bytes unknown
1967    
1968          memcpy(&pData[117], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
1969    
1970          // next 3 bytes unknown          // next 3 bytes unknown
1971    
1972          memcpy(&pData[121], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
1973    
1974          // next 2 bytes unknown          // next 2 bytes unknown
1975    
1976          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1977          memcpy(&pData[124], &eg1hold, 1);          pData[131] = eg1hold;
1978    
1979          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1980                                    (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1981          memcpy(&pData[125], &vcfcutoff, 1);          pData[132] = vcfcutoff;
1982    
1983          memcpy(&pData[126], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
1984    
1985          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
1986                                      (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1987          memcpy(&pData[127], &vcfvelscale, 1);          pData[134] = vcfvelscale;
1988    
1989          // next byte unknown          // next byte unknown
1990    
1991          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
1992                                       (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
1993          memcpy(&pData[129], &vcfresonance, 1);          pData[136] = vcfresonance;
1994    
1995          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
1996                                        (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1997          memcpy(&pData[130], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
1998    
1999          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 +
2000                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
2001          memcpy(&pData[131], &vcfvelocity, 1);          pData[138] = vcfvelocity;
2002    
2003          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
2004          memcpy(&pData[132], &vcftype, 1);          pData[139] = vcftype;
2005    
2006            if (chunksize >= 148) {
2007                memcpy(&pData[140], DimensionUpperLimits, 8);
2008            }
2009        }
2010    
2011        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
2012            curve_type_t curveType = releaseVelocityResponseCurve;
2013            uint8_t depth = releaseVelocityResponseDepth;
2014            // this models a strange behaviour or bug in GSt: two of the
2015            // velocity response curves for release time are not used even
2016            // if specified, instead another curve is chosen.
2017            if ((curveType == curve_type_nonlinear && depth == 0) ||
2018                (curveType == curve_type_special   && depth == 4)) {
2019                curveType = curve_type_nonlinear;
2020                depth = 3;
2021            }
2022            return GetVelocityTable(curveType, depth, 0);
2023        }
2024    
2025        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
2026                                                        uint8_t vcfVelocityDynamicRange,
2027                                                        uint8_t vcfVelocityScale,
2028                                                        vcf_cutoff_ctrl_t vcfCutoffController)
2029        {
2030            curve_type_t curveType = vcfVelocityCurve;
2031            uint8_t depth = vcfVelocityDynamicRange;
2032            // even stranger GSt: two of the velocity response curves for
2033            // filter cutoff are not used, instead another special curve
2034            // is chosen. This curve is not used anywhere else.
2035            if ((curveType == curve_type_nonlinear && depth == 0) ||
2036                (curveType == curve_type_special   && depth == 4)) {
2037                curveType = curve_type_special;
2038                depth = 5;
2039            }
2040            return GetVelocityTable(curveType, depth,
2041                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
2042                                        ? vcfVelocityScale : 0);
2043      }      }
2044    
2045      // 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
# Line 1723  namespace { Line 2057  namespace {
2057          return table;          return table;
2058      }      }
2059    
2060        Region* DimensionRegion::GetParent() const {
2061            return pRegion;
2062        }
2063    
2064    // show error if some _lev_ctrl_* enum entry is not listed in the following function
2065    // (commented out for now, because "diagnostic push" not supported prior GCC 4.6)
2066    // TODO: uncomment and add a GCC version check (see also commented "#pragma GCC diagnostic pop" below)
2067    //#pragma GCC diagnostic push
2068    //#pragma GCC diagnostic error "-Wswitch"
2069    
2070      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
2071          leverage_ctrl_t decodedcontroller;          leverage_ctrl_t decodedcontroller;
2072          switch (EncodedController) {          switch (EncodedController) {
# Line 1834  namespace { Line 2178  namespace {
2178                  decodedcontroller.controller_number = 95;                  decodedcontroller.controller_number = 95;
2179                  break;                  break;
2180    
2181                // format extension (these controllers are so far only supported by
2182                // LinuxSampler & gigedit) they will *NOT* work with
2183                // Gigasampler/GigaStudio !
2184                case _lev_ctrl_CC3_EXT:
2185                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2186                    decodedcontroller.controller_number = 3;
2187                    break;
2188                case _lev_ctrl_CC6_EXT:
2189                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2190                    decodedcontroller.controller_number = 6;
2191                    break;
2192                case _lev_ctrl_CC7_EXT:
2193                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2194                    decodedcontroller.controller_number = 7;
2195                    break;
2196                case _lev_ctrl_CC8_EXT:
2197                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2198                    decodedcontroller.controller_number = 8;
2199                    break;
2200                case _lev_ctrl_CC9_EXT:
2201                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2202                    decodedcontroller.controller_number = 9;
2203                    break;
2204                case _lev_ctrl_CC10_EXT:
2205                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2206                    decodedcontroller.controller_number = 10;
2207                    break;
2208                case _lev_ctrl_CC11_EXT:
2209                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2210                    decodedcontroller.controller_number = 11;
2211                    break;
2212                case _lev_ctrl_CC14_EXT:
2213                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2214                    decodedcontroller.controller_number = 14;
2215                    break;
2216                case _lev_ctrl_CC15_EXT:
2217                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2218                    decodedcontroller.controller_number = 15;
2219                    break;
2220                case _lev_ctrl_CC20_EXT:
2221                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2222                    decodedcontroller.controller_number = 20;
2223                    break;
2224                case _lev_ctrl_CC21_EXT:
2225                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2226                    decodedcontroller.controller_number = 21;
2227                    break;
2228                case _lev_ctrl_CC22_EXT:
2229                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2230                    decodedcontroller.controller_number = 22;
2231                    break;
2232                case _lev_ctrl_CC23_EXT:
2233                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2234                    decodedcontroller.controller_number = 23;
2235                    break;
2236                case _lev_ctrl_CC24_EXT:
2237                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2238                    decodedcontroller.controller_number = 24;
2239                    break;
2240                case _lev_ctrl_CC25_EXT:
2241                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2242                    decodedcontroller.controller_number = 25;
2243                    break;
2244                case _lev_ctrl_CC26_EXT:
2245                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2246                    decodedcontroller.controller_number = 26;
2247                    break;
2248                case _lev_ctrl_CC27_EXT:
2249                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2250                    decodedcontroller.controller_number = 27;
2251                    break;
2252                case _lev_ctrl_CC28_EXT:
2253                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2254                    decodedcontroller.controller_number = 28;
2255                    break;
2256                case _lev_ctrl_CC29_EXT:
2257                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2258                    decodedcontroller.controller_number = 29;
2259                    break;
2260                case _lev_ctrl_CC30_EXT:
2261                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2262                    decodedcontroller.controller_number = 30;
2263                    break;
2264                case _lev_ctrl_CC31_EXT:
2265                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2266                    decodedcontroller.controller_number = 31;
2267                    break;
2268                case _lev_ctrl_CC68_EXT:
2269                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2270                    decodedcontroller.controller_number = 68;
2271                    break;
2272                case _lev_ctrl_CC69_EXT:
2273                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2274                    decodedcontroller.controller_number = 69;
2275                    break;
2276                case _lev_ctrl_CC70_EXT:
2277                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2278                    decodedcontroller.controller_number = 70;
2279                    break;
2280                case _lev_ctrl_CC71_EXT:
2281                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2282                    decodedcontroller.controller_number = 71;
2283                    break;
2284                case _lev_ctrl_CC72_EXT:
2285                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2286                    decodedcontroller.controller_number = 72;
2287                    break;
2288                case _lev_ctrl_CC73_EXT:
2289                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2290                    decodedcontroller.controller_number = 73;
2291                    break;
2292                case _lev_ctrl_CC74_EXT:
2293                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2294                    decodedcontroller.controller_number = 74;
2295                    break;
2296                case _lev_ctrl_CC75_EXT:
2297                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2298                    decodedcontroller.controller_number = 75;
2299                    break;
2300                case _lev_ctrl_CC76_EXT:
2301                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2302                    decodedcontroller.controller_number = 76;
2303                    break;
2304                case _lev_ctrl_CC77_EXT:
2305                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2306                    decodedcontroller.controller_number = 77;
2307                    break;
2308                case _lev_ctrl_CC78_EXT:
2309                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2310                    decodedcontroller.controller_number = 78;
2311                    break;
2312                case _lev_ctrl_CC79_EXT:
2313                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2314                    decodedcontroller.controller_number = 79;
2315                    break;
2316                case _lev_ctrl_CC84_EXT:
2317                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2318                    decodedcontroller.controller_number = 84;
2319                    break;
2320                case _lev_ctrl_CC85_EXT:
2321                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2322                    decodedcontroller.controller_number = 85;
2323                    break;
2324                case _lev_ctrl_CC86_EXT:
2325                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2326                    decodedcontroller.controller_number = 86;
2327                    break;
2328                case _lev_ctrl_CC87_EXT:
2329                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2330                    decodedcontroller.controller_number = 87;
2331                    break;
2332                case _lev_ctrl_CC89_EXT:
2333                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2334                    decodedcontroller.controller_number = 89;
2335                    break;
2336                case _lev_ctrl_CC90_EXT:
2337                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2338                    decodedcontroller.controller_number = 90;
2339                    break;
2340                case _lev_ctrl_CC96_EXT:
2341                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2342                    decodedcontroller.controller_number = 96;
2343                    break;
2344                case _lev_ctrl_CC97_EXT:
2345                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2346                    decodedcontroller.controller_number = 97;
2347                    break;
2348                case _lev_ctrl_CC102_EXT:
2349                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2350                    decodedcontroller.controller_number = 102;
2351                    break;
2352                case _lev_ctrl_CC103_EXT:
2353                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2354                    decodedcontroller.controller_number = 103;
2355                    break;
2356                case _lev_ctrl_CC104_EXT:
2357                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2358                    decodedcontroller.controller_number = 104;
2359                    break;
2360                case _lev_ctrl_CC105_EXT:
2361                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2362                    decodedcontroller.controller_number = 105;
2363                    break;
2364                case _lev_ctrl_CC106_EXT:
2365                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2366                    decodedcontroller.controller_number = 106;
2367                    break;
2368                case _lev_ctrl_CC107_EXT:
2369                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2370                    decodedcontroller.controller_number = 107;
2371                    break;
2372                case _lev_ctrl_CC108_EXT:
2373                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2374                    decodedcontroller.controller_number = 108;
2375                    break;
2376                case _lev_ctrl_CC109_EXT:
2377                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2378                    decodedcontroller.controller_number = 109;
2379                    break;
2380                case _lev_ctrl_CC110_EXT:
2381                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2382                    decodedcontroller.controller_number = 110;
2383                    break;
2384                case _lev_ctrl_CC111_EXT:
2385                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2386                    decodedcontroller.controller_number = 111;
2387                    break;
2388                case _lev_ctrl_CC112_EXT:
2389                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2390                    decodedcontroller.controller_number = 112;
2391                    break;
2392                case _lev_ctrl_CC113_EXT:
2393                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2394                    decodedcontroller.controller_number = 113;
2395                    break;
2396                case _lev_ctrl_CC114_EXT:
2397                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2398                    decodedcontroller.controller_number = 114;
2399                    break;
2400                case _lev_ctrl_CC115_EXT:
2401                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2402                    decodedcontroller.controller_number = 115;
2403                    break;
2404                case _lev_ctrl_CC116_EXT:
2405                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2406                    decodedcontroller.controller_number = 116;
2407                    break;
2408                case _lev_ctrl_CC117_EXT:
2409                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2410                    decodedcontroller.controller_number = 117;
2411                    break;
2412                case _lev_ctrl_CC118_EXT:
2413                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2414                    decodedcontroller.controller_number = 118;
2415                    break;
2416                case _lev_ctrl_CC119_EXT:
2417                    decodedcontroller.type = leverage_ctrl_t::type_controlchange;
2418                    decodedcontroller.controller_number = 119;
2419                    break;
2420    
2421              // unknown controller type              // unknown controller type
2422              default:              default:
2423                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2424          }          }
2425          return decodedcontroller;          return decodedcontroller;
2426      }      }
2427        
2428    // see above (diagnostic push not supported prior GCC 4.6)
2429    //#pragma GCC diagnostic pop
2430    
2431      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {      DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2432          _lev_ctrl_t encodedcontroller;          _lev_ctrl_t encodedcontroller;
# Line 1927  namespace { Line 2514  namespace {
2514                      case 95:                      case 95:
2515                          encodedcontroller = _lev_ctrl_effect5depth;                          encodedcontroller = _lev_ctrl_effect5depth;
2516                          break;                          break;
2517    
2518                        // format extension (these controllers are so far only
2519                        // supported by LinuxSampler & gigedit) they will *NOT*
2520                        // work with Gigasampler/GigaStudio !
2521                        case 3:
2522                            encodedcontroller = _lev_ctrl_CC3_EXT;
2523                            break;
2524                        case 6:
2525                            encodedcontroller = _lev_ctrl_CC6_EXT;
2526                            break;
2527                        case 7:
2528                            encodedcontroller = _lev_ctrl_CC7_EXT;
2529                            break;
2530                        case 8:
2531                            encodedcontroller = _lev_ctrl_CC8_EXT;
2532                            break;
2533                        case 9:
2534                            encodedcontroller = _lev_ctrl_CC9_EXT;
2535                            break;
2536                        case 10:
2537                            encodedcontroller = _lev_ctrl_CC10_EXT;
2538                            break;
2539                        case 11:
2540                            encodedcontroller = _lev_ctrl_CC11_EXT;
2541                            break;
2542                        case 14:
2543                            encodedcontroller = _lev_ctrl_CC14_EXT;
2544                            break;
2545                        case 15:
2546                            encodedcontroller = _lev_ctrl_CC15_EXT;
2547                            break;
2548                        case 20:
2549                            encodedcontroller = _lev_ctrl_CC20_EXT;
2550                            break;
2551                        case 21:
2552                            encodedcontroller = _lev_ctrl_CC21_EXT;
2553                            break;
2554                        case 22:
2555                            encodedcontroller = _lev_ctrl_CC22_EXT;
2556                            break;
2557                        case 23:
2558                            encodedcontroller = _lev_ctrl_CC23_EXT;
2559                            break;
2560                        case 24:
2561                            encodedcontroller = _lev_ctrl_CC24_EXT;
2562                            break;
2563                        case 25:
2564                            encodedcontroller = _lev_ctrl_CC25_EXT;
2565                            break;
2566                        case 26:
2567                            encodedcontroller = _lev_ctrl_CC26_EXT;
2568                            break;
2569                        case 27:
2570                            encodedcontroller = _lev_ctrl_CC27_EXT;
2571                            break;
2572                        case 28:
2573                            encodedcontroller = _lev_ctrl_CC28_EXT;
2574                            break;
2575                        case 29:
2576                            encodedcontroller = _lev_ctrl_CC29_EXT;
2577                            break;
2578                        case 30:
2579                            encodedcontroller = _lev_ctrl_CC30_EXT;
2580                            break;
2581                        case 31:
2582                            encodedcontroller = _lev_ctrl_CC31_EXT;
2583                            break;
2584                        case 68:
2585                            encodedcontroller = _lev_ctrl_CC68_EXT;
2586                            break;
2587                        case 69:
2588                            encodedcontroller = _lev_ctrl_CC69_EXT;
2589                            break;
2590                        case 70:
2591                            encodedcontroller = _lev_ctrl_CC70_EXT;
2592                            break;
2593                        case 71:
2594                            encodedcontroller = _lev_ctrl_CC71_EXT;
2595                            break;
2596                        case 72:
2597                            encodedcontroller = _lev_ctrl_CC72_EXT;
2598                            break;
2599                        case 73:
2600                            encodedcontroller = _lev_ctrl_CC73_EXT;
2601                            break;
2602                        case 74:
2603                            encodedcontroller = _lev_ctrl_CC74_EXT;
2604                            break;
2605                        case 75:
2606                            encodedcontroller = _lev_ctrl_CC75_EXT;
2607                            break;
2608                        case 76:
2609                            encodedcontroller = _lev_ctrl_CC76_EXT;
2610                            break;
2611                        case 77:
2612                            encodedcontroller = _lev_ctrl_CC77_EXT;
2613                            break;
2614                        case 78:
2615                            encodedcontroller = _lev_ctrl_CC78_EXT;
2616                            break;
2617                        case 79:
2618                            encodedcontroller = _lev_ctrl_CC79_EXT;
2619                            break;
2620                        case 84:
2621                            encodedcontroller = _lev_ctrl_CC84_EXT;
2622                            break;
2623                        case 85:
2624                            encodedcontroller = _lev_ctrl_CC85_EXT;
2625                            break;
2626                        case 86:
2627                            encodedcontroller = _lev_ctrl_CC86_EXT;
2628                            break;
2629                        case 87:
2630                            encodedcontroller = _lev_ctrl_CC87_EXT;
2631                            break;
2632                        case 89:
2633                            encodedcontroller = _lev_ctrl_CC89_EXT;
2634                            break;
2635                        case 90:
2636                            encodedcontroller = _lev_ctrl_CC90_EXT;
2637                            break;
2638                        case 96:
2639                            encodedcontroller = _lev_ctrl_CC96_EXT;
2640                            break;
2641                        case 97:
2642                            encodedcontroller = _lev_ctrl_CC97_EXT;
2643                            break;
2644                        case 102:
2645                            encodedcontroller = _lev_ctrl_CC102_EXT;
2646                            break;
2647                        case 103:
2648                            encodedcontroller = _lev_ctrl_CC103_EXT;
2649                            break;
2650                        case 104:
2651                            encodedcontroller = _lev_ctrl_CC104_EXT;
2652                            break;
2653                        case 105:
2654                            encodedcontroller = _lev_ctrl_CC105_EXT;
2655                            break;
2656                        case 106:
2657                            encodedcontroller = _lev_ctrl_CC106_EXT;
2658                            break;
2659                        case 107:
2660                            encodedcontroller = _lev_ctrl_CC107_EXT;
2661                            break;
2662                        case 108:
2663                            encodedcontroller = _lev_ctrl_CC108_EXT;
2664                            break;
2665                        case 109:
2666                            encodedcontroller = _lev_ctrl_CC109_EXT;
2667                            break;
2668                        case 110:
2669                            encodedcontroller = _lev_ctrl_CC110_EXT;
2670                            break;
2671                        case 111:
2672                            encodedcontroller = _lev_ctrl_CC111_EXT;
2673                            break;
2674                        case 112:
2675                            encodedcontroller = _lev_ctrl_CC112_EXT;
2676                            break;
2677                        case 113:
2678                            encodedcontroller = _lev_ctrl_CC113_EXT;
2679                            break;
2680                        case 114:
2681                            encodedcontroller = _lev_ctrl_CC114_EXT;
2682                            break;
2683                        case 115:
2684                            encodedcontroller = _lev_ctrl_CC115_EXT;
2685                            break;
2686                        case 116:
2687                            encodedcontroller = _lev_ctrl_CC116_EXT;
2688                            break;
2689                        case 117:
2690                            encodedcontroller = _lev_ctrl_CC117_EXT;
2691                            break;
2692                        case 118:
2693                            encodedcontroller = _lev_ctrl_CC118_EXT;
2694                            break;
2695                        case 119:
2696                            encodedcontroller = _lev_ctrl_CC119_EXT;
2697                            break;
2698    
2699                      default:                      default:
2700                          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");
2701                  }                  }
2702                    break;
2703              default:              default:
2704                  throw gig::Exception("Unknown leverage controller type.");                  throw gig::Exception("Unknown leverage controller type.");
2705          }          }
# Line 1975  namespace { Line 2745  namespace {
2745          return pVelocityCutoffTable[MIDIKeyVelocity];          return pVelocityCutoffTable[MIDIKeyVelocity];
2746      }      }
2747    
2748        /**
2749         * Updates the respective member variable and the lookup table / cache
2750         * that depends on this value.
2751         */
2752        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2753            pVelocityAttenuationTable =
2754                GetVelocityTable(
2755                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2756                );
2757            VelocityResponseCurve = curve;
2758        }
2759    
2760        /**
2761         * Updates the respective member variable and the lookup table / cache
2762         * that depends on this value.
2763         */
2764        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2765            pVelocityAttenuationTable =
2766                GetVelocityTable(
2767                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2768                );
2769            VelocityResponseDepth = depth;
2770        }
2771    
2772        /**
2773         * Updates the respective member variable and the lookup table / cache
2774         * that depends on this value.
2775         */
2776        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2777            pVelocityAttenuationTable =
2778                GetVelocityTable(
2779                    VelocityResponseCurve, VelocityResponseDepth, scaling
2780                );
2781            VelocityResponseCurveScaling = scaling;
2782        }
2783    
2784        /**
2785         * Updates the respective member variable and the lookup table / cache
2786         * that depends on this value.
2787         */
2788        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2789            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2790            ReleaseVelocityResponseCurve = curve;
2791        }
2792    
2793        /**
2794         * Updates the respective member variable and the lookup table / cache
2795         * that depends on this value.
2796         */
2797        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2798            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2799            ReleaseVelocityResponseDepth = depth;
2800        }
2801    
2802        /**
2803         * Updates the respective member variable and the lookup table / cache
2804         * that depends on this value.
2805         */
2806        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2807            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2808            VCFCutoffController = controller;
2809        }
2810    
2811        /**
2812         * Updates the respective member variable and the lookup table / cache
2813         * that depends on this value.
2814         */
2815        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2816            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2817            VCFVelocityCurve = curve;
2818        }
2819    
2820        /**
2821         * Updates the respective member variable and the lookup table / cache
2822         * that depends on this value.
2823         */
2824        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2825            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2826            VCFVelocityDynamicRange = range;
2827        }
2828    
2829        /**
2830         * Updates the respective member variable and the lookup table / cache
2831         * that depends on this value.
2832         */
2833        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2834            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2835            VCFVelocityScale = scaling;
2836        }
2837    
2838      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) {
2839    
2840          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 2058  namespace { Line 2918  namespace {
2918    
2919          // Actual Loading          // Actual Loading
2920    
2921            if (!file->GetAutoLoad()) return;
2922    
2923          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2924    
2925          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 2066  namespace { Line 2928  namespace {
2928              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2929                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2930                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2931                  _3lnk->ReadUint8(); // probably the position of the dimension                  _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2932                  _3lnk->ReadUint8(); // unknown                  _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2933                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)                  uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2934                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2935                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
# Line 2080  namespace { Line 2942  namespace {
2942                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2943                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2944                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2945                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2946                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random) ? split_type_bit  
                                                                                           : split_type_normal;  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2947                      Dimensions++;                      Dimensions++;
2948    
2949                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2108  namespace { Line 2963  namespace {
2963              else              else
2964                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2965    
2966              // load sample references              // load sample references (if auto loading is enabled)
2967              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2968                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2969                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2970                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2971                    }
2972                    GetSample(); // load global region sample reference
2973                }
2974            } else {
2975                DimensionRegions = 0;
2976                for (int i = 0 ; i < 8 ; i++) {
2977                    pDimensionDefinitions[i].dimension  = dimension_none;
2978                    pDimensionDefinitions[i].bits       = 0;
2979                    pDimensionDefinitions[i].zones      = 0;
2980              }              }
2981          }          }
2982    
# Line 2120  namespace { Line 2985  namespace {
2985              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);              RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2986              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);              if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2987              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);              RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2988              pDimensionRegions[0] = new DimensionRegion(_3ewl);              pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2989              DimensionRegions = 1;              DimensionRegions = 1;
2990          }          }
2991      }      }
# Line 2132  namespace { Line 2997  namespace {
2997       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
2998       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
2999       *       *
3000         * @param pProgress - callback function for progress notification
3001       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3002       */       */
3003      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3004            // in the gig format we don't care about the Region's sample reference
3005            // but we still have to provide some existing one to not corrupt the
3006            // file, so to avoid the latter we simply always assign the sample of
3007            // the first dimension region of this region
3008            pSample = pDimensionRegions[0]->pSample;
3009    
3010          // first update base class's chunks          // first update base class's chunks
3011          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3012    
3013          // update dimension region's chunks          // update dimension region's chunks
3014          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3015              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3016          }          }
3017    
3018          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
3019          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
3020          const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;          const int iMaxDimensions =  version3 ? 8 : 5;
3021            const int iMaxDimensionRegions = version3 ? 256 : 32;
3022    
3023          // make sure '3lnk' chunk exists          // make sure '3lnk' chunk exists
3024          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
3025          if (!_3lnk) {          if (!_3lnk) {
3026              const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;              const int _3lnkChunkSize = version3 ? 1092 : 172;
3027              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);              _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
3028                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3029    
3030                // move 3prg to last position
3031                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3032          }          }
3033    
3034          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
3035          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
3036            store32(&pData[0], DimensionRegions);
3037            int shift = 0;
3038          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
3039              pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
3040              pData[i * 8 + 1] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
3041              // next 2 bytes unknown              pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
3042              pData[i * 8 + 4] = pDimensionDefinitions[i].zones;              pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
3043              // next 3 bytes unknown              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
3044                // next 3 bytes unknown, always zero?
3045    
3046                shift += pDimensionDefinitions[i].bits;
3047          }          }
3048    
3049          // update wave pool table in '3lnk' chunk          // update wave pool table in '3lnk' chunk
3050          const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;          const int iWavePoolOffset = version3 ? 68 : 44;
3051          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
3052              int iWaveIndex = -1;              int iWaveIndex = -1;
3053              if (i < DimensionRegions) {              if (i < DimensionRegions) {
# Line 2178  namespace { Line 3060  namespace {
3060                          break;                          break;
3061                      }                      }
3062                  }                  }
                 if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");  
3063              }              }
3064              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
3065          }          }
3066      }      }
3067    
# Line 2191  namespace { Line 3072  namespace {
3072              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
3073              while (_3ewl) {              while (_3ewl) {
3074                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
3075                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
3076                      dimensionRegionNr++;                      dimensionRegionNr++;
3077                  }                  }
3078                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 2200  namespace { Line 3081  namespace {
3081          }          }
3082      }      }
3083    
3084        void Region::SetKeyRange(uint16_t Low, uint16_t High) {
3085            // update KeyRange struct and make sure regions are in correct order
3086            DLS::Region::SetKeyRange(Low, High);
3087            // update Region key table for fast lookup
3088            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
3089        }
3090    
3091      void Region::UpdateVelocityTable() {      void Region::UpdateVelocityTable() {
3092          // get velocity dimension's index          // get velocity dimension's index
3093          int veldim = -1;          int veldim = -1;
# Line 2220  namespace { Line 3108  namespace {
3108          int dim[8] = { 0 };          int dim[8] = { 0 };
3109          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3110    
3111              if (pDimensionRegions[i]->VelocityUpperLimit) {              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3112                    pDimensionRegions[i]->VelocityUpperLimit) {
3113                  // create the velocity table                  // create the velocity table
3114                  uint8_t* table = pDimensionRegions[i]->VelocityTable;                  uint8_t* table = pDimensionRegions[i]->VelocityTable;
3115                  if (!table) {                  if (!table) {
# Line 2229  namespace { Line 3118  namespace {
3118                  }                  }
3119                  int tableidx = 0;                  int tableidx = 0;
3120                  int velocityZone = 0;                  int velocityZone = 0;
3121                  for (int k = i ; k < end ; k += step) {                  if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
3122                      DimensionRegion *d = pDimensionRegions[k];                      for (int k = i ; k < end ; k += step) {
3123                      for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;                          DimensionRegion *d = pDimensionRegions[k];
3124                      velocityZone++;                          for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
3125                            velocityZone++;
3126                        }
3127                    } else { // gig2
3128                        for (int k = i ; k < end ; k += step) {
3129                            DimensionRegion *d = pDimensionRegions[k];
3130                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
3131                            velocityZone++;
3132                        }
3133                  }                  }
3134              } else {              } else {
3135                  if (pDimensionRegions[i]->VelocityTable) {                  if (pDimensionRegions[i]->VelocityTable) {
# Line 2277  namespace { Line 3174  namespace {
3174       *                        dimension bits limit is violated       *                        dimension bits limit is violated
3175       */       */
3176      void Region::AddDimension(dimension_def_t* pDimDef) {      void Region::AddDimension(dimension_def_t* pDimDef) {
3177            // some initial sanity checks of the given dimension definition
3178            if (pDimDef->zones < 2)
3179                throw gig::Exception("Could not add new dimension, amount of requested zones must always be at least two");
3180            if (pDimDef->bits < 1)
3181                throw gig::Exception("Could not add new dimension, amount of requested requested zone bits must always be at least one");
3182            if (pDimDef->dimension == dimension_samplechannel) {
3183                if (pDimDef->zones != 2)
3184                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zones must always be 2 for this dimension type");
3185                if (pDimDef->bits != 1)
3186                    throw gig::Exception("Could not add new 'sample channel' dimensions, the requested amount of zone bits must always be 1 for this dimension type");
3187            }
3188    
3189          // check if max. amount of dimensions reached          // check if max. amount of dimensions reached
3190          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3191          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
# Line 2296  namespace { Line 3205  namespace {
3205              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)              if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
3206                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");                  throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
3207    
3208            // pos is where the new dimension should be placed, normally
3209            // last in list, except for the samplechannel dimension which
3210            // has to be first in list
3211            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
3212            int bitpos = 0;
3213            for (int i = 0 ; i < pos ; i++)
3214                bitpos += pDimensionDefinitions[i].bits;
3215    
3216            // make room for the new dimension
3217            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
3218            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
3219                for (int j = Dimensions ; j > pos ; j--) {
3220                    pDimensionRegions[i]->DimensionUpperLimits[j] =
3221                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
3222                }
3223            }
3224    
3225          // assign definition of new dimension          // assign definition of new dimension
3226          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[pos] = *pDimDef;
3227    
3228          // create new dimension region(s) for this new dimension          // auto correct certain dimension definition fields (where possible)
3229          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          pDimensionDefinitions[pos].split_type  =
3230              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values              __resolveSplitType(pDimensionDefinitions[pos].dimension);
3231              RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);          pDimensionDefinitions[pos].zone_size =
3232              pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);              __resolveZoneSize(pDimensionDefinitions[pos]);
3233              DimensionRegions++;  
3234            // create new dimension region(s) for this new dimension, and make
3235            // sure that the dimension regions are placed correctly in both the
3236            // RIFF list and the pDimensionRegions array
3237            RIFF::Chunk* moveTo = NULL;
3238            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3239            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
3240                for (int k = 0 ; k < (1 << bitpos) ; k++) {
3241                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
3242                }
3243                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
3244                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
3245                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
3246                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
3247                        // create a new dimension region and copy all parameter values from
3248                        // an existing dimension region
3249                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
3250                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
3251    
3252                        DimensionRegions++;
3253                    }
3254                }
3255                moveTo = pDimensionRegions[i]->pParentList;
3256            }
3257    
3258            // initialize the upper limits for this dimension
3259            int mask = (1 << bitpos) - 1;
3260            for (int z = 0 ; z < pDimDef->zones ; z++) {
3261                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
3262                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
3263                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
3264                                      (z << bitpos) |
3265                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
3266                }
3267          }          }
3268    
3269          Dimensions++;          Dimensions++;
# Line 2347  namespace { Line 3306  namespace {
3306          for (int i = iDimensionNr + 1; i < Dimensions; i++)          for (int i = iDimensionNr + 1; i < Dimensions; i++)
3307              iUpperBits += pDimensionDefinitions[i].bits;              iUpperBits += pDimensionDefinitions[i].bits;
3308    
3309            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
3310    
3311          // delete dimension regions which belong to the given dimension          // delete dimension regions which belong to the given dimension
3312          // (that is where the dimension's bit > 0)          // (that is where the dimension's bit > 0)
3313          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {          for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
# Line 2355  namespace { Line 3316  namespace {
3316                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |                      int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
3317                                      iObsoleteBit << iLowerBits |                                      iObsoleteBit << iLowerBits |
3318                                      iLowerBit;                                      iLowerBit;
3319    
3320                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
3321                      delete pDimensionRegions[iToDelete];                      delete pDimensionRegions[iToDelete];
3322                      pDimensionRegions[iToDelete] = NULL;                      pDimensionRegions[iToDelete] = NULL;
3323                      DimensionRegions--;                      DimensionRegions--;
# Line 2375  namespace { Line 3338  namespace {
3338              }              }
3339          }          }
3340    
3341            // remove the this dimension from the upper limits arrays
3342            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
3343                DimensionRegion* d = pDimensionRegions[j];
3344                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3345                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
3346                }
3347                d->DimensionUpperLimits[Dimensions - 1] = 127;
3348            }
3349    
3350          // 'remove' dimension definition          // 'remove' dimension definition
3351          for (int i = iDimensionNr + 1; i < Dimensions; i++) {          for (int i = iDimensionNr + 1; i < Dimensions; i++) {
3352              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];              pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
# Line 2389  namespace { Line 3361  namespace {
3361          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3362      }      }
3363    
3364        /** @brief Delete one split zone of a dimension (decrement zone amount).
3365         *
3366         * Instead of deleting an entire dimensions, this method will only delete
3367         * one particular split zone given by @a zone of the Region's dimension
3368         * given by @a type. So this method will simply decrement the amount of
3369         * zones by one of the dimension in question. To be able to do that, the
3370         * respective dimension must exist on this Region and it must have at least
3371         * 3 zones. All DimensionRegion objects associated with the zone will be
3372         * deleted.
3373         *
3374         * @param type - identifies the dimension where a zone shall be deleted
3375         * @param zone - index of the dimension split zone that shall be deleted
3376         * @throws gig::Exception if requested zone could not be deleted
3377         */
3378        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3379            dimension_def_t* oldDef = GetDimensionDefinition(type);
3380            if (!oldDef)
3381                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3382            if (oldDef->zones <= 2)
3383                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3384            if (zone < 0 || zone >= oldDef->zones)
3385                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3386    
3387            const int newZoneSize = oldDef->zones - 1;
3388    
3389            // create a temporary Region which just acts as a temporary copy
3390            // container and will be deleted at the end of this function and will
3391            // also not be visible through the API during this process
3392            gig::Region* tempRgn = NULL;
3393            {
3394                // adding these temporary chunks is probably not even necessary
3395                Instrument* instr = static_cast<Instrument*>(GetParent());
3396                RIFF::List* pCkInstrument = instr->pCkInstrument;
3397                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3398                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3399                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3400                tempRgn = new Region(instr, rgn);
3401            }
3402    
3403            // copy this region's dimensions (with already the dimension split size
3404            // requested by the arguments of this method call) to the temporary
3405            // region, and don't use Region::CopyAssign() here for this task, since
3406            // it would also alter fast lookup helper variables here and there
3407            dimension_def_t newDef;
3408            for (int i = 0; i < Dimensions; ++i) {
3409                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3410                // is this the dimension requested by the method arguments? ...
3411                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3412                    def.zones = newZoneSize;
3413                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3414                    newDef = def;
3415                }
3416                tempRgn->AddDimension(&def);
3417            }
3418    
3419            // find the dimension index in the tempRegion which is the dimension
3420            // type passed to this method (paranoidly expecting different order)
3421            int tempReducedDimensionIndex = -1;
3422            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3423                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3424                    tempReducedDimensionIndex = d;
3425                    break;
3426                }
3427            }
3428    
3429            // copy dimension regions from this region to the temporary region
3430            for (int iDst = 0; iDst < 256; ++iDst) {
3431                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3432                if (!dstDimRgn) continue;
3433                std::map<dimension_t,int> dimCase;
3434                bool isValidZone = true;
3435                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3436                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3437                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3438                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3439                    baseBits += dstBits;
3440                    // there are also DimensionRegion objects of unused zones, skip them
3441                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3442                        isValidZone = false;
3443                        break;
3444                    }
3445                }
3446                if (!isValidZone) continue;
3447                // a bit paranoid: cope with the chance that the dimensions would
3448                // have different order in source and destination regions
3449                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3450                if (dimCase[type] >= zone) dimCase[type]++;
3451                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3452                dstDimRgn->CopyAssign(srcDimRgn);
3453                // if this is the upper most zone of the dimension passed to this
3454                // method, then correct (raise) its upper limit to 127
3455                if (newDef.split_type == split_type_normal && isLastZone)
3456                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3457            }
3458    
3459            // now tempRegion's dimensions and DimensionRegions basically reflect
3460            // what we wanted to get for this actual Region here, so we now just
3461            // delete and recreate the dimension in question with the new amount
3462            // zones and then copy back from tempRegion      
3463            DeleteDimension(oldDef);
3464            AddDimension(&newDef);
3465            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3466                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3467                if (!srcDimRgn) continue;
3468                std::map<dimension_t,int> dimCase;
3469                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3470                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3471                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3472                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3473                    baseBits += srcBits;
3474                }
3475                // a bit paranoid: cope with the chance that the dimensions would
3476                // have different order in source and destination regions
3477                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3478                if (!dstDimRgn) continue;
3479                dstDimRgn->CopyAssign(srcDimRgn);
3480            }
3481    
3482            // delete temporary region
3483            delete tempRgn;
3484    
3485            UpdateVelocityTable();
3486        }
3487    
3488        /** @brief Divide split zone of a dimension in two (increment zone amount).
3489         *
3490         * This will increment the amount of zones for the dimension (given by
3491         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3492         * in the middle of its zone range in two. So the two zones resulting from
3493         * the zone being splitted, will be an equivalent copy regarding all their
3494         * articulation informations and sample reference. The two zones will only
3495         * differ in their zone's upper limit
3496         * (DimensionRegion::DimensionUpperLimits).
3497         *
3498         * @param type - identifies the dimension where a zone shall be splitted
3499         * @param zone - index of the dimension split zone that shall be splitted
3500         * @throws gig::Exception if requested zone could not be splitted
3501         */
3502        void Region::SplitDimensionZone(dimension_t type, int zone) {
3503            dimension_def_t* oldDef = GetDimensionDefinition(type);
3504            if (!oldDef)
3505                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3506            if (zone < 0 || zone >= oldDef->zones)
3507                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3508    
3509            const int newZoneSize = oldDef->zones + 1;
3510    
3511            // create a temporary Region which just acts as a temporary copy
3512            // container and will be deleted at the end of this function and will
3513            // also not be visible through the API during this process
3514            gig::Region* tempRgn = NULL;
3515            {
3516                // adding these temporary chunks is probably not even necessary
3517                Instrument* instr = static_cast<Instrument*>(GetParent());
3518                RIFF::List* pCkInstrument = instr->pCkInstrument;
3519                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3520                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3521                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3522                tempRgn = new Region(instr, rgn);
3523            }
3524    
3525            // copy this region's dimensions (with already the dimension split size
3526            // requested by the arguments of this method call) to the temporary
3527            // region, and don't use Region::CopyAssign() here for this task, since
3528            // it would also alter fast lookup helper variables here and there
3529            dimension_def_t newDef;
3530            for (int i = 0; i < Dimensions; ++i) {
3531                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3532                // is this the dimension requested by the method arguments? ...
3533                if (def.dimension == type) { // ... if yes, increment zone amount by one
3534                    def.zones = newZoneSize;
3535                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3536                    newDef = def;
3537                }
3538                tempRgn->AddDimension(&def);
3539            }
3540    
3541            // find the dimension index in the tempRegion which is the dimension
3542            // type passed to this method (paranoidly expecting different order)
3543            int tempIncreasedDimensionIndex = -1;
3544            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3545                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3546                    tempIncreasedDimensionIndex = d;
3547                    break;
3548                }
3549            }
3550    
3551            // copy dimension regions from this region to the temporary region
3552            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3553                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3554                if (!srcDimRgn) continue;
3555                std::map<dimension_t,int> dimCase;
3556                bool isValidZone = true;
3557                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3558                    const int srcBits = pDimensionDefinitions[d].bits;
3559                    dimCase[pDimensionDefinitions[d].dimension] =
3560                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3561                    // there are also DimensionRegion objects for unused zones, skip them
3562                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3563                        isValidZone = false;
3564                        break;
3565                    }
3566                    baseBits += srcBits;
3567                }
3568                if (!isValidZone) continue;
3569                // a bit paranoid: cope with the chance that the dimensions would
3570                // have different order in source and destination regions            
3571                if (dimCase[type] > zone) dimCase[type]++;
3572                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3573                dstDimRgn->CopyAssign(srcDimRgn);
3574                // if this is the requested zone to be splitted, then also copy
3575                // the source DimensionRegion to the newly created target zone
3576                // and set the old zones upper limit lower
3577                if (dimCase[type] == zone) {
3578                    // lower old zones upper limit
3579                    if (newDef.split_type == split_type_normal) {
3580                        const int high =
3581                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3582                        int low = 0;
3583                        if (zone > 0) {
3584                            std::map<dimension_t,int> lowerCase = dimCase;
3585                            lowerCase[type]--;
3586                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3587                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3588                        }
3589                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3590                    }
3591                    // fill the newly created zone of the divided zone as well
3592                    dimCase[type]++;
3593                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3594                    dstDimRgn->CopyAssign(srcDimRgn);
3595                }
3596            }
3597    
3598            // now tempRegion's dimensions and DimensionRegions basically reflect
3599            // what we wanted to get for this actual Region here, so we now just
3600            // delete and recreate the dimension in question with the new amount
3601            // zones and then copy back from tempRegion      
3602            DeleteDimension(oldDef);
3603            AddDimension(&newDef);
3604            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3605                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3606                if (!srcDimRgn) continue;
3607                std::map<dimension_t,int> dimCase;
3608                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3609                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3610                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3611                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3612                    baseBits += srcBits;
3613                }
3614                // a bit paranoid: cope with the chance that the dimensions would
3615                // have different order in source and destination regions
3616                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3617                if (!dstDimRgn) continue;
3618                dstDimRgn->CopyAssign(srcDimRgn);
3619            }
3620    
3621            // delete temporary region
3622            delete tempRgn;
3623    
3624            UpdateVelocityTable();
3625        }
3626    
3627        /** @brief Change type of an existing dimension.
3628         *
3629         * Alters the dimension type of a dimension already existing on this
3630         * region. If there is currently no dimension on this Region with type
3631         * @a oldType, then this call with throw an Exception. Likewise there are
3632         * cases where the requested dimension type cannot be performed. For example
3633         * if the new dimension type shall be gig::dimension_samplechannel, and the
3634         * current dimension has more than 2 zones. In such cases an Exception is
3635         * thrown as well.
3636         *
3637         * @param oldType - identifies the existing dimension to be changed
3638         * @param newType - to which dimension type it should be changed to
3639         * @throws gig::Exception if requested change cannot be performed
3640         */
3641        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3642            if (oldType == newType) return;
3643            dimension_def_t* def = GetDimensionDefinition(oldType);
3644            if (!def)
3645                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3646            if (newType == dimension_samplechannel && def->zones != 2)
3647                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3648            if (GetDimensionDefinition(newType))
3649                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3650            def->dimension  = newType;
3651            def->split_type = __resolveSplitType(newType);
3652        }
3653    
3654        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3655            uint8_t bits[8] = {};
3656            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3657                 it != DimCase.end(); ++it)
3658            {
3659                for (int d = 0; d < Dimensions; ++d) {
3660                    if (pDimensionDefinitions[d].dimension == it->first) {
3661                        bits[d] = it->second;
3662                        goto nextDimCaseSlice;
3663                    }
3664                }
3665                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3666                nextDimCaseSlice:
3667                ; // noop
3668            }
3669            return GetDimensionRegionByBit(bits);
3670        }
3671    
3672        /**
3673         * Searches in the current Region for a dimension of the given dimension
3674         * type and returns the precise configuration of that dimension in this
3675         * Region.
3676         *
3677         * @param type - dimension type of the sought dimension
3678         * @returns dimension definition or NULL if there is no dimension with
3679         *          sought type in this Region.
3680         */
3681        dimension_def_t* Region::GetDimensionDefinition(dimension_t type) {
3682            for (int i = 0; i < Dimensions; ++i)
3683                if (pDimensionDefinitions[i].dimension == type)
3684                    return &pDimensionDefinitions[i];
3685            return NULL;
3686        }
3687    
3688      Region::~Region() {      Region::~Region() {
3689          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
3690              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
# Line 2427  namespace { Line 3723  namespace {
3723              } else {              } else {
3724                  switch (pDimensionDefinitions[i].split_type) {                  switch (pDimensionDefinitions[i].split_type) {
3725                      case split_type_normal:                      case split_type_normal:
3726                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3727                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3728                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3729                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3730                                }
3731                            } else {
3732                                // gig2: evenly sized zones
3733                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3734                            }
3735                          break;                          break;
3736                      case split_type_bit: // the value is already the sought dimension bit number                      case split_type_bit: // the value is already the sought dimension bit number
3737                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
# Line 2438  namespace { Line 3742  namespace {
3742              }              }
3743              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3744          }          }
3745          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3746            if (!dimreg) return NULL;
3747          if (veldim != -1) {          if (veldim != -1) {
3748              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3749              if (dimreg->VelocityUpperLimit) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3750                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3751              else // normal split type              else // normal split type
3752                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3753    
3754              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3755              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3756                dimreg = pDimensionRegions[dimregidx & 255];
3757          }          }
3758          return dimreg;          return dimreg;
3759      }      }
3760    
3761        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3762            uint8_t bits;
3763            int veldim = -1;
3764            int velbitpos;
3765            int bitpos = 0;
3766            int dimregidx = 0;
3767            for (uint i = 0; i < Dimensions; i++) {
3768                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3769                    // the velocity dimension must be handled after the other dimensions
3770                    veldim = i;
3771                    velbitpos = bitpos;
3772                } else {
3773                    switch (pDimensionDefinitions[i].split_type) {
3774                        case split_type_normal:
3775                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3776                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3777                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3778                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3779                                }
3780                            } else {
3781                                // gig2: evenly sized zones
3782                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3783                            }
3784                            break;
3785                        case split_type_bit: // the value is already the sought dimension bit number
3786                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3787                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3788                            break;
3789                    }
3790                    dimregidx |= bits << bitpos;
3791                }
3792                bitpos += pDimensionDefinitions[i].bits;
3793            }
3794            dimregidx &= 255;
3795            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3796            if (!dimreg) return -1;
3797            if (veldim != -1) {
3798                // (dimreg is now the dimension region for the lowest velocity)
3799                if (dimreg->VelocityTable) // custom defined zone ranges
3800                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3801                else // normal split type
3802                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3803    
3804                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3805                dimregidx |= (bits & limiter_mask) << velbitpos;
3806                dimregidx &= 255;
3807            }
3808            return dimregidx;
3809        }
3810    
3811      /**      /**
3812       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3813       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 2489  namespace { Line 3845  namespace {
3845      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
3846          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3847          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3848            if (!file->pWavePoolTable) return NULL;
3849          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3850          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3851          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
3852          while (sample) {          while (sample) {
3853              if (sample->ulWavePoolOffset == soughtoffset &&              if (sample->ulWavePoolOffset == soughtoffset &&
3854                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3855              sample = file->GetNextSample();              sample = file->GetNextSample();
3856          }          }
3857          return NULL;          return NULL;
3858      }      }
3859        
3860        /**
3861         * Make a (semi) deep copy of the Region object given by @a orig
3862         * and assign it to this object.
3863         *
3864         * Note that all sample pointers referenced by @a orig are simply copied as
3865         * memory address. Thus the respective samples are shared, not duplicated!
3866         *
3867         * @param orig - original Region object to be copied from
3868         */
3869        void Region::CopyAssign(const Region* orig) {
3870            CopyAssign(orig, NULL);
3871        }
3872        
3873        /**
3874         * Make a (semi) deep copy of the Region object given by @a orig and
3875         * assign it to this object
3876         *
3877         * @param mSamples - crosslink map between the foreign file's samples and
3878         *                   this file's samples
3879         */
3880        void Region::CopyAssign(const Region* orig, const std::map<Sample*,Sample*>* mSamples) {
3881            // handle base classes
3882            DLS::Region::CopyAssign(orig);
3883            
3884            if (mSamples && mSamples->count((gig::Sample*)orig->pSample)) {
3885                pSample = mSamples->find((gig::Sample*)orig->pSample)->second;
3886            }
3887            
3888            // handle own member variables
3889            for (int i = Dimensions - 1; i >= 0; --i) {
3890                DeleteDimension(&pDimensionDefinitions[i]);
3891            }
3892            Layers = 0; // just to be sure
3893            for (int i = 0; i < orig->Dimensions; i++) {
3894                // we need to copy the dim definition here, to avoid the compiler
3895                // complaining about const-ness issue
3896                dimension_def_t def = orig->pDimensionDefinitions[i];
3897                AddDimension(&def);
3898            }
3899            for (int i = 0; i < 256; i++) {
3900                if (pDimensionRegions[i] && orig->pDimensionRegions[i]) {
3901                    pDimensionRegions[i]->CopyAssign(
3902                        orig->pDimensionRegions[i],
3903                        mSamples
3904                    );
3905                }
3906            }
3907            Layers = orig->Layers;
3908        }
3909    
3910    
3911    // *************** MidiRule ***************
3912    // *
3913    
3914        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
3915            _3ewg->SetPos(36);
3916            Triggers = _3ewg->ReadUint8();
3917            _3ewg->SetPos(40);
3918            ControllerNumber = _3ewg->ReadUint8();
3919            _3ewg->SetPos(46);
3920            for (int i = 0 ; i < Triggers ; i++) {
3921                pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
3922                pTriggers[i].Descending = _3ewg->ReadUint8();
3923                pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
3924                pTriggers[i].Key = _3ewg->ReadUint8();
3925                pTriggers[i].NoteOff = _3ewg->ReadUint8();
3926                pTriggers[i].Velocity = _3ewg->ReadUint8();
3927                pTriggers[i].OverridePedal = _3ewg->ReadUint8();
3928                _3ewg->ReadUint8();
3929            }
3930        }
3931    
3932        MidiRuleCtrlTrigger::MidiRuleCtrlTrigger() :
3933            ControllerNumber(0),
3934            Triggers(0) {
3935        }
3936    
3937        void MidiRuleCtrlTrigger::UpdateChunks(uint8_t* pData) const {
3938            pData[32] = 4;
3939            pData[33] = 16;
3940            pData[36] = Triggers;
3941            pData[40] = ControllerNumber;
3942            for (int i = 0 ; i < Triggers ; i++) {
3943                pData[46 + i * 8] = pTriggers[i].TriggerPoint;
3944                pData[47 + i * 8] = pTriggers[i].Descending;
3945                pData[48 + i * 8] = pTriggers[i].VelSensitivity;
3946                pData[49 + i * 8] = pTriggers[i].Key;
3947                pData[50 + i * 8] = pTriggers[i].NoteOff;
3948                pData[51 + i * 8] = pTriggers[i].Velocity;
3949                pData[52 + i * 8] = pTriggers[i].OverridePedal;
3950            }
3951        }
3952    
3953        MidiRuleLegato::MidiRuleLegato(RIFF::Chunk* _3ewg) {
3954            _3ewg->SetPos(36);
3955            LegatoSamples = _3ewg->ReadUint8(); // always 12
3956            _3ewg->SetPos(40);
3957            BypassUseController = _3ewg->ReadUint8();
3958            BypassKey = _3ewg->ReadUint8();
3959            BypassController = _3ewg->ReadUint8();
3960            ThresholdTime = _3ewg->ReadUint16();
3961            _3ewg->ReadInt16();
3962            ReleaseTime = _3ewg->ReadUint16();
3963            _3ewg->ReadInt16();
3964            KeyRange.low = _3ewg->ReadUint8();
3965            KeyRange.high = _3ewg->ReadUint8();
3966            _3ewg->SetPos(64);
3967            ReleaseTriggerKey = _3ewg->ReadUint8();
3968            AltSustain1Key = _3ewg->ReadUint8();
3969            AltSustain2Key = _3ewg->ReadUint8();
3970        }
3971    
3972        MidiRuleLegato::MidiRuleLegato() :
3973            LegatoSamples(12),
3974            BypassUseController(false),
3975            BypassKey(0),
3976            BypassController(1),
3977            ThresholdTime(20),
3978            ReleaseTime(20),
3979            ReleaseTriggerKey(0),
3980            AltSustain1Key(0),
3981            AltSustain2Key(0)
3982        {
3983            KeyRange.low = KeyRange.high = 0;
3984        }
3985    
3986        void MidiRuleLegato::UpdateChunks(uint8_t* pData) const {
3987            pData[32] = 0;
3988            pData[33] = 16;
3989            pData[36] = LegatoSamples;
3990            pData[40] = BypassUseController;
3991            pData[41] = BypassKey;
3992            pData[42] = BypassController;
3993            store16(&pData[43], ThresholdTime);
3994            store16(&pData[47], ReleaseTime);
3995            pData[51] = KeyRange.low;
3996            pData[52] = KeyRange.high;
3997            pData[64] = ReleaseTriggerKey;
3998            pData[65] = AltSustain1Key;
3999            pData[66] = AltSustain2Key;
4000        }
4001    
4002        MidiRuleAlternator::MidiRuleAlternator(RIFF::Chunk* _3ewg) {
4003            _3ewg->SetPos(36);
4004            Articulations = _3ewg->ReadUint8();
4005            int flags = _3ewg->ReadUint8();
4006            Polyphonic = flags & 8;
4007            Chained = flags & 4;
4008            Selector = (flags & 2) ? selector_controller :
4009                (flags & 1) ? selector_key_switch : selector_none;
4010            Patterns = _3ewg->ReadUint8();
4011            _3ewg->ReadUint8(); // chosen row
4012            _3ewg->ReadUint8(); // unknown
4013            _3ewg->ReadUint8(); // unknown
4014            _3ewg->ReadUint8(); // unknown
4015            KeySwitchRange.low = _3ewg->ReadUint8();
4016            KeySwitchRange.high = _3ewg->ReadUint8();
4017            Controller = _3ewg->ReadUint8();
4018            PlayRange.low = _3ewg->ReadUint8();
4019            PlayRange.high = _3ewg->ReadUint8();
4020    
4021            int n = std::min(int(Articulations), 32);
4022            for (int i = 0 ; i < n ; i++) {
4023                _3ewg->ReadString(pArticulations[i], 32);
4024            }
4025            _3ewg->SetPos(1072);
4026            n = std::min(int(Patterns), 32);
4027            for (int i = 0 ; i < n ; i++) {
4028                _3ewg->ReadString(pPatterns[i].Name, 16);
4029                pPatterns[i].Size = _3ewg->ReadUint8();
4030                _3ewg->Read(&pPatterns[i][0], 1, 32);
4031            }
4032        }
4033    
4034        MidiRuleAlternator::MidiRuleAlternator() :
4035            Articulations(0),
4036            Patterns(0),
4037            Selector(selector_none),
4038            Controller(0),
4039            Polyphonic(false),
4040            Chained(false)
4041        {
4042            PlayRange.low = PlayRange.high = 0;
4043            KeySwitchRange.low = KeySwitchRange.high = 0;
4044        }
4045    
4046        void MidiRuleAlternator::UpdateChunks(uint8_t* pData) const {
4047            pData[32] = 3;
4048            pData[33] = 16;
4049            pData[36] = Articulations;
4050            pData[37] = (Polyphonic ? 8 : 0) | (Chained ? 4 : 0) |
4051                (Selector == selector_controller ? 2 :
4052                 (Selector == selector_key_switch ? 1 : 0));
4053            pData[38] = Patterns;
4054    
4055            pData[43] = KeySwitchRange.low;
4056            pData[44] = KeySwitchRange.high;
4057            pData[45] = Controller;
4058            pData[46] = PlayRange.low;
4059            pData[47] = PlayRange.high;
4060    
4061            char* str = reinterpret_cast<char*>(pData);
4062            int pos = 48;
4063            int n = std::min(int(Articulations), 32);
4064            for (int i = 0 ; i < n ; i++, pos += 32) {
4065                strncpy(&str[pos], pArticulations[i].c_str(), 32);
4066            }
4067    
4068            pos = 1072;
4069            n = std::min(int(Patterns), 32);
4070            for (int i = 0 ; i < n ; i++, pos += 49) {
4071                strncpy(&str[pos], pPatterns[i].Name.c_str(), 16);
4072                pData[pos + 16] = pPatterns[i].Size;
4073                memcpy(&pData[pos + 16], &(pPatterns[i][0]), 32);
4074            }
4075        }
4076    
4077    // *************** Script ***************
4078    // *
4079    
4080        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4081            pGroup = group;
4082            pChunk = ckScri;
4083            if (ckScri) { // object is loaded from file ...
4084                // read header
4085                uint32_t headerSize = ckScri->ReadUint32();
4086                Compression = (Compression_t) ckScri->ReadUint32();
4087                Encoding    = (Encoding_t) ckScri->ReadUint32();
4088                Language    = (Language_t) ckScri->ReadUint32();
4089                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4090                crc         = ckScri->ReadUint32();
4091                uint32_t nameSize = ckScri->ReadUint32();
4092                Name.resize(nameSize, ' ');
4093                for (int i = 0; i < nameSize; ++i)
4094                    Name[i] = ckScri->ReadUint8();
4095                // to handle potential future extensions of the header
4096                ckScri->SetPos(sizeof(int32_t) + headerSize);
4097                // read actual script data
4098                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4099                data.resize(scriptSize);
4100                for (int i = 0; i < scriptSize; ++i)
4101                    data[i] = ckScri->ReadUint8();
4102            } else { // this is a new script object, so just initialize it as such ...
4103                Compression = COMPRESSION_NONE;
4104                Encoding = ENCODING_ASCII;
4105                Language = LANGUAGE_NKSP;
4106                Bypass   = false;
4107                crc      = 0;
4108                Name     = "Unnamed Script";
4109            }
4110        }
4111    
4112        Script::~Script() {
4113        }
4114    
4115        /**
4116         * Returns the current script (i.e. as source code) in text format.
4117         */
4118        String Script::GetScriptAsText() {
4119            String s;
4120            s.resize(data.size(), ' ');
4121            memcpy(&s[0], &data[0], data.size());
4122            return s;
4123        }
4124    
4125        /**
4126         * Replaces the current script with the new script source code text given
4127         * by @a text.
4128         *
4129         * @param text - new script source code
4130         */
4131        void Script::SetScriptAsText(const String& text) {
4132            data.resize(text.size());
4133            memcpy(&data[0], &text[0], text.size());
4134        }
4135    
4136        /**
4137         * Apply this script to the respective RIFF chunks. You have to call
4138         * File::Save() to make changes persistent.
4139         *
4140         * Usually there is absolutely no need to call this method explicitly.
4141         * It will be called automatically when File::Save() was called.
4142         *
4143         * @param pProgress - callback function for progress notification
4144         */
4145        void Script::UpdateChunks(progress_t* pProgress) {
4146            // recalculate CRC32 check sum
4147            __resetCRC(crc);
4148            __calculateCRC(&data[0], data.size(), crc);
4149            __encodeCRC(crc);
4150            // make sure chunk exists and has the required size
4151            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4152            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4153            else pChunk->Resize(chunkSize);
4154            // fill the chunk data to be written to disk
4155            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4156            int pos = 0;
4157            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4158            pos += sizeof(int32_t);
4159            store32(&pData[pos], Compression);
4160            pos += sizeof(int32_t);
4161            store32(&pData[pos], Encoding);
4162            pos += sizeof(int32_t);
4163            store32(&pData[pos], Language);
4164            pos += sizeof(int32_t);
4165            store32(&pData[pos], Bypass ? 1 : 0);
4166            pos += sizeof(int32_t);
4167            store32(&pData[pos], crc);
4168            pos += sizeof(int32_t);
4169            store32(&pData[pos], Name.size());
4170            pos += sizeof(int32_t);
4171            for (int i = 0; i < Name.size(); ++i, ++pos)
4172                pData[pos] = Name[i];
4173            for (int i = 0; i < data.size(); ++i, ++pos)
4174                pData[pos] = data[i];
4175        }
4176    
4177        /**
4178         * Move this script from its current ScriptGroup to another ScriptGroup
4179         * given by @a pGroup.
4180         *
4181         * @param pGroup - script's new group
4182         */
4183        void Script::SetGroup(ScriptGroup* pGroup) {
4184            if (this->pGroup == pGroup) return;
4185            if (pChunk)
4186                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4187            this->pGroup = pGroup;
4188        }
4189    
4190        /**
4191         * Returns the script group this script currently belongs to. Each script
4192         * is a member of exactly one ScriptGroup.
4193         *
4194         * @returns current script group
4195         */
4196        ScriptGroup* Script::GetGroup() const {
4197            return pGroup;
4198        }
4199    
4200        void Script::RemoveAllScriptReferences() {
4201            File* pFile = pGroup->pFile;
4202            for (int i = 0; pFile->GetInstrument(i); ++i) {
4203                Instrument* instr = pFile->GetInstrument(i);
4204                instr->RemoveScript(this);
4205            }
4206        }
4207    
4208    // *************** ScriptGroup ***************
4209    // *
4210    
4211        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4212            pFile = file;
4213            pList = lstRTIS;
4214            pScripts = NULL;
4215            if (lstRTIS) {
4216                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4217                ::LoadString(ckName, Name);
4218            } else {
4219                Name = "Default Group";
4220            }
4221        }
4222    
4223        ScriptGroup::~ScriptGroup() {
4224            if (pScripts) {
4225                std::list<Script*>::iterator iter = pScripts->begin();
4226                std::list<Script*>::iterator end  = pScripts->end();
4227                while (iter != end) {
4228                    delete *iter;
4229                    ++iter;
4230                }
4231                delete pScripts;
4232            }
4233        }
4234    
4235        /**
4236         * Apply this script group to the respective RIFF chunks. You have to call
4237         * File::Save() to make changes persistent.
4238         *
4239         * Usually there is absolutely no need to call this method explicitly.
4240         * It will be called automatically when File::Save() was called.
4241         *
4242         * @param pProgress - callback function for progress notification
4243         */
4244        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4245            if (pScripts) {
4246                if (!pList)
4247                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4248    
4249                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4250                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4251    
4252                for (std::list<Script*>::iterator it = pScripts->begin();
4253                     it != pScripts->end(); ++it)
4254                {
4255                    (*it)->UpdateChunks(pProgress);
4256                }
4257            }
4258        }
4259    
4260        /** @brief Get instrument script.
4261         *
4262         * Returns the real-time instrument script with the given index.
4263         *
4264         * @param index - number of the sought script (0..n)
4265         * @returns sought script or NULL if there's no such script
4266         */
4267        Script* ScriptGroup::GetScript(uint index) {
4268            if (!pScripts) LoadScripts();
4269            std::list<Script*>::iterator it = pScripts->begin();
4270            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4271                if (i == index) return *it;
4272            return NULL;
4273        }
4274    
4275        /** @brief Add new instrument script.
4276         *
4277         * Adds a new real-time instrument script to the file. The script is not
4278         * actually used / executed unless it is referenced by an instrument to be
4279         * used. This is similar to samples, which you can add to a file, without
4280         * an instrument necessarily actually using it.
4281         *
4282         * You have to call Save() to make this persistent to the file.
4283         *
4284         * @return new empty script object
4285         */
4286        Script* ScriptGroup::AddScript() {
4287            if (!pScripts) LoadScripts();
4288            Script* pScript = new Script(this, NULL);
4289            pScripts->push_back(pScript);
4290            return pScript;
4291        }
4292    
4293        /** @brief Delete an instrument script.
4294         *
4295         * This will delete the given real-time instrument script. References of
4296         * instruments that are using that script will be removed accordingly.
4297         *
4298         * You have to call Save() to make this persistent to the file.
4299         *
4300         * @param pScript - script to delete
4301         * @throws gig::Exception if given script could not be found
4302         */
4303        void ScriptGroup::DeleteScript(Script* pScript) {
4304            if (!pScripts) LoadScripts();
4305            std::list<Script*>::iterator iter =
4306                find(pScripts->begin(), pScripts->end(), pScript);
4307            if (iter == pScripts->end())
4308                throw gig::Exception("Could not delete script, could not find given script");
4309            pScripts->erase(iter);
4310            pScript->RemoveAllScriptReferences();
4311            if (pScript->pChunk)
4312                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4313            delete pScript;
4314        }
4315    
4316        void ScriptGroup::LoadScripts() {
4317            if (pScripts) return;
4318            pScripts = new std::list<Script*>;
4319            if (!pList) return;
4320    
4321            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4322                 ck = pList->GetNextSubChunk())
4323            {
4324                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4325                    pScripts->push_back(new Script(this, ck));
4326                }
4327            }
4328        }
4329    
4330  // *************** Instrument ***************  // *************** Instrument ***************
4331  // *  // *
4332    
4333      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) {
4334            static const DLS::Info::string_length_t fixedStringLengths[] = {
4335                { CHUNK_ID_INAM, 64 },
4336                { CHUNK_ID_ISFT, 12 },
4337                { 0, 0 }
4338            };
4339            pInfo->SetFixedStringLengths(fixedStringLengths);
4340    
4341          // Initialization          // Initialization
4342          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4343            EffectSend = 0;
4344            Attenuation = 0;
4345            FineTune = 0;
4346            PitchbendRange = 0;
4347            PianoReleaseMode = false;
4348            DimensionKeyRange.low = 0;
4349            DimensionKeyRange.high = 0;
4350            pMidiRules = new MidiRule*[3];
4351            pMidiRules[0] = NULL;
4352            pScriptRefs = NULL;
4353    
4354          // Loading          // Loading
4355          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2522  namespace { Line 4364  namespace {
4364                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
4365                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
4366                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
4367    
4368                    if (_3ewg->GetSize() > 32) {
4369                        // read MIDI rules
4370                        int i = 0;
4371                        _3ewg->SetPos(32);
4372                        uint8_t id1 = _3ewg->ReadUint8();
4373                        uint8_t id2 = _3ewg->ReadUint8();
4374    
4375                        if (id2 == 16) {
4376                            if (id1 == 4) {
4377                                pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
4378                            } else if (id1 == 0) {
4379                                pMidiRules[i++] = new MidiRuleLegato(_3ewg);
4380                            } else if (id1 == 3) {
4381                                pMidiRules[i++] = new MidiRuleAlternator(_3ewg);
4382                            } else {
4383                                pMidiRules[i++] = new MidiRuleUnknown;
4384                            }
4385                        }
4386                        else if (id1 != 0 || id2 != 0) {
4387                            pMidiRules[i++] = new MidiRuleUnknown;
4388                        }
4389                        //TODO: all the other types of rules
4390    
4391                        pMidiRules[i] = NULL;
4392                    }
4393              }              }
4394          }          }
4395    
4396          if (!pRegions) pRegions = new RegionList;          if (pFile->GetAutoLoad()) {
4397          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);              if (!pRegions) pRegions = new RegionList;
4398          if (lrgn) {              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
4399              RIFF::List* rgn = lrgn->GetFirstSubList();              if (lrgn) {
4400              while (rgn) {                  RIFF::List* rgn = lrgn->GetFirstSubList();
4401                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  while (rgn) {
4402                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);                      if (rgn->GetListType() == LIST_TYPE_RGN) {
4403                      pRegions->push_back(new Region(this, rgn));                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
4404                            pRegions->push_back(new Region(this, rgn));
4405                        }
4406                        rgn = lrgn->GetNextSubList();
4407                    }
4408                    // Creating Region Key Table for fast lookup
4409                    UpdateRegionKeyTable();
4410                }
4411            }
4412    
4413            // own gig format extensions
4414            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4415            if (lst3LS) {
4416                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4417                if (ckSCSL) {
4418                    int headerSize = ckSCSL->ReadUint32();
4419                    int slotCount  = ckSCSL->ReadUint32();
4420                    if (slotCount) {
4421                        int slotSize  = ckSCSL->ReadUint32();
4422                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4423                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4424                        for (int i = 0; i < slotCount; ++i) {
4425                            _ScriptPooolEntry e;
4426                            e.fileOffset = ckSCSL->ReadUint32();
4427                            e.bypass     = ckSCSL->ReadUint32() & 1;
4428                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4429                            scriptPoolFileOffsets.push_back(e);
4430                        }
4431                  }                  }
                 rgn = lrgn->GetNextSubList();  
4432              }              }
             // Creating Region Key Table for fast lookup  
             UpdateRegionKeyTable();  
4433          }          }
4434    
4435          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4436      }      }
4437    
4438      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
4439            for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
4440          RegionList::iterator iter = pRegions->begin();          RegionList::iterator iter = pRegions->begin();
4441          RegionList::iterator end  = pRegions->end();          RegionList::iterator end  = pRegions->end();
4442          for (; iter != end; ++iter) {          for (; iter != end; ++iter) {
# Line 2555  namespace { Line 4448  namespace {
4448      }      }
4449    
4450      Instrument::~Instrument() {      Instrument::~Instrument() {
4451            for (int i = 0 ; pMidiRules[i] ; i++) {
4452                delete pMidiRules[i];
4453            }
4454            delete[] pMidiRules;
4455            if (pScriptRefs) delete pScriptRefs;
4456      }      }
4457    
4458      /**      /**
# Line 2564  namespace { Line 4462  namespace {
4462       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4463       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4464       *       *
4465         * @param pProgress - callback function for progress notification
4466       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4467       */       */
4468      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4469          // first update base classes' chunks          // first update base classes' chunks
4470          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4471    
4472          // update Regions' chunks          // update Regions' chunks
4473          {          {
4474              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4475              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4476              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4477                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4478          }          }
4479    
4480          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 2583  namespace { Line 4482  namespace {
4482          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);          if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
4483          // make sure '3ewg' RIFF chunk exists          // make sure '3ewg' RIFF chunk exists
4484          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);          RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
4485          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  {
4486                File* pFile = (File*) GetParent();
4487    
4488                // 3ewg is bigger in gig3, as it includes the iMIDI rules
4489                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
4490                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
4491                memset(_3ewg->LoadChunkData(), 0, size);
4492            }
4493          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
4494          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
4495          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
4496          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
4497          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
4498          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
4499          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
4500                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
4501          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
4502          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
4503    
4504            if (pMidiRules[0] == 0 && _3ewg->GetSize() >= 34) {
4505                pData[32] = 0;
4506                pData[33] = 0;
4507            } else {
4508                for (int i = 0 ; pMidiRules[i] ; i++) {
4509                    pMidiRules[i]->UpdateChunks(pData);
4510                }
4511            }
4512    
4513            // own gig format extensions
4514           if (ScriptSlotCount()) {
4515               // make sure we have converted the original loaded script file
4516               // offsets into valid Script object pointers
4517               LoadScripts();
4518    
4519               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4520               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4521               const int slotCount = pScriptRefs->size();
4522               const int headerSize = 3 * sizeof(uint32_t);
4523               const int slotSize  = 2 * sizeof(uint32_t);
4524               const int totalChunkSize = headerSize + slotCount * slotSize;
4525               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4526               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4527               else ckSCSL->Resize(totalChunkSize);
4528               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4529               int pos = 0;
4530               store32(&pData[pos], headerSize);
4531               pos += sizeof(uint32_t);
4532               store32(&pData[pos], slotCount);
4533               pos += sizeof(uint32_t);
4534               store32(&pData[pos], slotSize);
4535               pos += sizeof(uint32_t);
4536               for (int i = 0; i < slotCount; ++i) {
4537                   // arbitrary value, the actual file offset will be updated in
4538                   // UpdateScriptFileOffsets() after the file has been resized
4539                   int bogusFileOffset = 0;
4540                   store32(&pData[pos], bogusFileOffset);
4541                   pos += sizeof(uint32_t);
4542                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4543                   pos += sizeof(uint32_t);
4544               }
4545           } else {
4546               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4547               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4548               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4549           }
4550        }
4551    
4552        void Instrument::UpdateScriptFileOffsets() {
4553           // own gig format extensions
4554           if (pScriptRefs && pScriptRefs->size() > 0) {
4555               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4556               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4557               const int slotCount = pScriptRefs->size();
4558               const int headerSize = 3 * sizeof(uint32_t);
4559               ckSCSL->SetPos(headerSize);
4560               for (int i = 0; i < slotCount; ++i) {
4561                   uint32_t fileOffset =
4562                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4563                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4564                        CHUNK_HEADER_SIZE;
4565                   ckSCSL->WriteUint32(&fileOffset);
4566                   // jump over flags entry (containing the bypass flag)
4567                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4568               }
4569           }        
4570      }      }
4571    
4572      /**      /**
# Line 2604  namespace { Line 4577  namespace {
4577       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
4578       */       */
4579      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
4580          if (!pRegions || !pRegions->size() || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
4581          return RegionKeyTable[Key];          return RegionKeyTable[Key];
4582    
4583          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
# Line 2662  namespace { Line 4635  namespace {
4635          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4636      }      }
4637    
4638        /**
4639         * Move this instrument at the position before @arg dst.
4640         *
4641         * This method can be used to reorder the sequence of instruments in a
4642         * .gig file. This might be helpful especially on large .gig files which
4643         * contain a large number of instruments within the same .gig file. So
4644         * grouping such instruments to similar ones, can help to keep track of them
4645         * when working with such complex .gig files.
4646         *
4647         * When calling this method, this instrument will be removed from in its
4648         * current position in the instruments list and moved to the requested
4649         * target position provided by @param dst. You may also pass NULL as
4650         * argument to this method, in that case this intrument will be moved to the
4651         * very end of the .gig file's instrument list.
4652         *
4653         * You have to call Save() to make the order change persistent to the .gig
4654         * file.
4655         *
4656         * Currently this method is limited to moving the instrument within the same
4657         * .gig file. Trying to move it to another .gig file by calling this method
4658         * will throw an exception.
4659         *
4660         * @param dst - destination instrument at which this instrument will be
4661         *              moved to, or pass NULL for moving to end of list
4662         * @throw gig::Exception if this instrument and target instrument are not
4663         *                       part of the same file
4664         */
4665        void Instrument::MoveTo(Instrument* dst) {
4666            if (dst && GetParent() != dst->GetParent())
4667                throw Exception(
4668                    "gig::Instrument::MoveTo() can only be used for moving within "
4669                    "the same gig file."
4670                );
4671    
4672            File* pFile = (File*) GetParent();
4673    
4674            // move this instrument within the instrument list
4675            {
4676                File::InstrumentList& list = *pFile->pInstruments;
4677    
4678                File::InstrumentList::iterator itFrom =
4679                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4680    
4681                File::InstrumentList::iterator itTo =
4682                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4683    
4684                list.splice(itTo, list, itFrom);
4685            }
4686    
4687            // move the instrument's actual list RIFF chunk appropriately
4688            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4689            lstCkInstruments->MoveSubChunk(
4690                this->pCkInstrument,
4691                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4692            );
4693        }
4694    
4695        /**
4696         * Returns a MIDI rule of the instrument.
4697         *
4698         * The list of MIDI rules, at least in gig v3, always contains at
4699         * most two rules. The second rule can only be the DEF filter
4700         * (which currently isn't supported by libgig).
4701         *
4702         * @param i - MIDI rule number
4703         * @returns   pointer address to MIDI rule number i or NULL if there is none
4704         */
4705        MidiRule* Instrument::GetMidiRule(int i) {
4706            return pMidiRules[i];
4707        }
4708    
4709        /**
4710         * Adds the "controller trigger" MIDI rule to the instrument.
4711         *
4712         * @returns the new MIDI rule
4713         */
4714        MidiRuleCtrlTrigger* Instrument::AddMidiRuleCtrlTrigger() {
4715            delete pMidiRules[0];
4716            MidiRuleCtrlTrigger* r = new MidiRuleCtrlTrigger;
4717            pMidiRules[0] = r;
4718            pMidiRules[1] = 0;
4719            return r;
4720        }
4721    
4722        /**
4723         * Adds the legato MIDI rule to the instrument.
4724         *
4725         * @returns the new MIDI rule
4726         */
4727        MidiRuleLegato* Instrument::AddMidiRuleLegato() {
4728            delete pMidiRules[0];
4729            MidiRuleLegato* r = new MidiRuleLegato;
4730            pMidiRules[0] = r;
4731            pMidiRules[1] = 0;
4732            return r;
4733        }
4734    
4735        /**
4736         * Adds the alternator MIDI rule to the instrument.
4737         *
4738         * @returns the new MIDI rule
4739         */
4740        MidiRuleAlternator* Instrument::AddMidiRuleAlternator() {
4741            delete pMidiRules[0];
4742            MidiRuleAlternator* r = new MidiRuleAlternator;
4743            pMidiRules[0] = r;
4744            pMidiRules[1] = 0;
4745            return r;
4746        }
4747    
4748        /**
4749         * Deletes a MIDI rule from the instrument.
4750         *
4751         * @param i - MIDI rule number
4752         */
4753        void Instrument::DeleteMidiRule(int i) {
4754            delete pMidiRules[i];
4755            pMidiRules[i] = 0;
4756        }
4757    
4758        void Instrument::LoadScripts() {
4759            if (pScriptRefs) return;
4760            pScriptRefs = new std::vector<_ScriptPooolRef>;
4761            if (scriptPoolFileOffsets.empty()) return;
4762            File* pFile = (File*) GetParent();
4763            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4764                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4765                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4766                    ScriptGroup* group = pFile->GetScriptGroup(i);
4767                    for (uint s = 0; group->GetScript(s); ++s) {
4768                        Script* script = group->GetScript(s);
4769                        if (script->pChunk) {
4770                            uint32_t offset = script->pChunk->GetFilePos() -
4771                                              script->pChunk->GetPos() -
4772                                              CHUNK_HEADER_SIZE;
4773                            if (offset == soughtOffset)
4774                            {
4775                                _ScriptPooolRef ref;
4776                                ref.script = script;
4777                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4778                                pScriptRefs->push_back(ref);
4779                                break;
4780                            }
4781                        }
4782                    }
4783                }
4784            }
4785            // we don't need that anymore
4786            scriptPoolFileOffsets.clear();
4787        }
4788    
4789        /** @brief Get instrument script (gig format extension).
4790         *
4791         * Returns the real-time instrument script of instrument script slot
4792         * @a index.
4793         *
4794         * @note This is an own format extension which did not exist i.e. in the
4795         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4796         * gigedit.
4797         *
4798         * @param index - instrument script slot index
4799         * @returns script or NULL if index is out of bounds
4800         */
4801        Script* Instrument::GetScriptOfSlot(uint index) {
4802            LoadScripts();
4803            if (index >= pScriptRefs->size()) return NULL;
4804            return pScriptRefs->at(index).script;
4805        }
4806    
4807        /** @brief Add new instrument script slot (gig format extension).
4808         *
4809         * Add the given real-time instrument script reference to this instrument,
4810         * which shall be executed by the sampler for for this instrument. The
4811         * script will be added to the end of the script list of this instrument.
4812         * The positions of the scripts in the Instrument's Script list are
4813         * relevant, because they define in which order they shall be executed by
4814         * the sampler. For this reason it is also legal to add the same script
4815         * twice to an instrument, for example you might have a script called
4816         * "MyFilter" which performs an event filter task, and you might have
4817         * another script called "MyNoteTrigger" which triggers new notes, then you
4818         * might for example have the following list of scripts on the instrument:
4819         *
4820         * 1. Script "MyFilter"
4821         * 2. Script "MyNoteTrigger"
4822         * 3. Script "MyFilter"
4823         *
4824         * Which would make sense, because the 2nd script launched new events, which
4825         * you might need to filter as well.
4826         *
4827         * There are two ways to disable / "bypass" scripts. You can either disable
4828         * a script locally for the respective script slot on an instrument (i.e. by
4829         * passing @c false to the 2nd argument of this method, or by calling
4830         * SetScriptBypassed()). Or you can disable a script globally for all slots
4831         * and all instruments by setting Script::Bypass.
4832         *
4833         * @note This is an own format extension which did not exist i.e. in the
4834         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4835         * gigedit.
4836         *
4837         * @param pScript - script that shall be executed for this instrument
4838         * @param bypass  - if enabled, the sampler shall skip executing this
4839         *                  script (in the respective list position)
4840         * @see SetScriptBypassed()
4841         */
4842        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4843            LoadScripts();
4844            _ScriptPooolRef ref = { pScript, bypass };
4845            pScriptRefs->push_back(ref);
4846        }
4847    
4848        /** @brief Flip two script slots with each other (gig format extension).
4849         *
4850         * Swaps the position of the two given scripts in the Instrument's Script
4851         * list. The positions of the scripts in the Instrument's Script list are
4852         * relevant, because they define in which order they shall be executed by
4853         * the sampler.
4854         *
4855         * @note This is an own format extension which did not exist i.e. in the
4856         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4857         * gigedit.
4858         *
4859         * @param index1 - index of the first script slot to swap
4860         * @param index2 - index of the second script slot to swap
4861         */
4862        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4863            LoadScripts();
4864            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4865                return;
4866            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4867            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4868            (*pScriptRefs)[index2] = tmp;
4869        }
4870    
4871        /** @brief Remove script slot.
4872         *
4873         * Removes the script slot with the given slot index.
4874         *
4875         * @param index - index of script slot to remove
4876         */
4877        void Instrument::RemoveScriptSlot(uint index) {
4878            LoadScripts();
4879            if (index >= pScriptRefs->size()) return;
4880            pScriptRefs->erase( pScriptRefs->begin() + index );
4881        }
4882    
4883        /** @brief Remove reference to given Script (gig format extension).
4884         *
4885         * This will remove all script slots on the instrument which are referencing
4886         * the given script.
4887         *
4888         * @note This is an own format extension which did not exist i.e. in the
4889         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4890         * gigedit.
4891         *
4892         * @param pScript - script reference to remove from this instrument
4893         * @see RemoveScriptSlot()
4894         */
4895        void Instrument::RemoveScript(Script* pScript) {
4896            LoadScripts();
4897            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4898                if ((*pScriptRefs)[i].script == pScript) {
4899                    pScriptRefs->erase( pScriptRefs->begin() + i );
4900                }
4901            }
4902        }
4903    
4904        /** @brief Instrument's amount of script slots.
4905         *
4906         * This method returns the amount of script slots this instrument currently
4907         * uses.
4908         *
4909         * A script slot is a reference of a real-time instrument script to be
4910         * executed by the sampler. The scripts will be executed by the sampler in
4911         * sequence of the slots. One (same) script may be referenced multiple
4912         * times in different slots.
4913         *
4914         * @note This is an own format extension which did not exist i.e. in the
4915         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4916         * gigedit.
4917         */
4918        uint Instrument::ScriptSlotCount() const {
4919            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4920        }
4921    
4922        /** @brief Whether script execution shall be skipped.
4923         *
4924         * Defines locally for the Script reference slot in the Instrument's Script
4925         * list, whether the script shall be skipped by the sampler regarding
4926         * execution.
4927         *
4928         * It is also possible to ignore exeuction of the script globally, for all
4929         * slots and for all instruments by setting Script::Bypass.
4930         *
4931         * @note This is an own format extension which did not exist i.e. in the
4932         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4933         * gigedit.
4934         *
4935         * @param index - index of the script slot on this instrument
4936         * @see Script::Bypass
4937         */
4938        bool Instrument::IsScriptSlotBypassed(uint index) {
4939            if (index >= ScriptSlotCount()) return false;
4940            return pScriptRefs ? pScriptRefs->at(index).bypass
4941                               : scriptPoolFileOffsets.at(index).bypass;
4942            
4943        }
4944    
4945        /** @brief Defines whether execution shall be skipped.
4946         *
4947         * You can call this method to define locally whether or whether not the
4948         * given script slot shall be executed by the sampler.
4949         *
4950         * @note This is an own format extension which did not exist i.e. in the
4951         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4952         * gigedit.
4953         *
4954         * @param index - script slot index on this instrument
4955         * @param bBypass - if true, the script slot will be skipped by the sampler
4956         * @see Script::Bypass
4957         */
4958        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4959            if (index >= ScriptSlotCount()) return;
4960            if (pScriptRefs)
4961                pScriptRefs->at(index).bypass = bBypass;
4962            else
4963                scriptPoolFileOffsets.at(index).bypass = bBypass;
4964        }
4965    
4966        /**
4967         * Make a (semi) deep copy of the Instrument object given by @a orig
4968         * and assign it to this object.
4969         *
4970         * Note that all sample pointers referenced by @a orig are simply copied as
4971         * memory address. Thus the respective samples are shared, not duplicated!
4972         *
4973         * @param orig - original Instrument object to be copied from
4974         */
4975        void Instrument::CopyAssign(const Instrument* orig) {
4976            CopyAssign(orig, NULL);
4977        }
4978            
4979        /**
4980         * Make a (semi) deep copy of the Instrument object given by @a orig
4981         * and assign it to this object.
4982         *
4983         * @param orig - original Instrument object to be copied from
4984         * @param mSamples - crosslink map between the foreign file's samples and
4985         *                   this file's samples
4986         */
4987        void Instrument::CopyAssign(const Instrument* orig, const std::map<Sample*,Sample*>* mSamples) {
4988            // handle base class
4989            // (without copying DLS region stuff)
4990            DLS::Instrument::CopyAssignCore(orig);
4991            
4992            // handle own member variables
4993            Attenuation = orig->Attenuation;
4994            EffectSend = orig->EffectSend;
4995            FineTune = orig->FineTune;
4996            PitchbendRange = orig->PitchbendRange;
4997            PianoReleaseMode = orig->PianoReleaseMode;
4998            DimensionKeyRange = orig->DimensionKeyRange;
4999            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5000            pScriptRefs = orig->pScriptRefs;
5001            
5002            // free old midi rules
5003            for (int i = 0 ; pMidiRules[i] ; i++) {
5004                delete pMidiRules[i];
5005            }
5006            //TODO: MIDI rule copying
5007            pMidiRules[0] = NULL;
5008            
5009            // delete all old regions
5010            while (Regions) DeleteRegion(GetFirstRegion());
5011            // create new regions and copy them from original
5012            {
5013                RegionList::const_iterator it = orig->pRegions->begin();
5014                for (int i = 0; i < orig->Regions; ++i, ++it) {
5015                    Region* dstRgn = AddRegion();
5016                    //NOTE: Region does semi-deep copy !
5017                    dstRgn->CopyAssign(
5018                        static_cast<gig::Region*>(*it),
5019                        mSamples
5020                    );
5021                }
5022            }
5023    
5024            UpdateRegionKeyTable();
5025        }
5026    
5027    
5028    // *************** Group ***************
5029    // *
5030    
5031        /** @brief Constructor.
5032         *
5033         * @param file   - pointer to the gig::File object
5034         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
5035         *                 NULL if this is a new Group
5036         */
5037        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
5038            pFile      = file;
5039            pNameChunk = ck3gnm;
5040            ::LoadString(pNameChunk, Name);
5041        }
5042    
5043        Group::~Group() {
5044            // remove the chunk associated with this group (if any)
5045            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
5046        }
5047    
5048        /** @brief Update chunks with current group settings.
5049         *
5050         * Apply current Group field values to the respective chunks. You have
5051         * to call File::Save() to make changes persistent.
5052         *
5053         * Usually there is absolutely no need to call this method explicitly.
5054         * It will be called automatically when File::Save() was called.
5055         *
5056         * @param pProgress - callback function for progress notification
5057         */
5058        void Group::UpdateChunks(progress_t* pProgress) {
5059            // make sure <3gri> and <3gnl> list chunks exist
5060            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5061            if (!_3gri) {
5062                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
5063                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5064            }
5065            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5066            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5067    
5068            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
5069                // v3 has a fixed list of 128 strings, find a free one
5070                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
5071                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
5072                        pNameChunk = ck;
5073                        break;
5074                    }
5075                }
5076            }
5077    
5078            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
5079            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
5080        }
5081    
5082        /**
5083         * Returns the first Sample of this Group. You have to call this method
5084         * once before you use GetNextSample().
5085         *
5086         * <b>Notice:</b> this method might block for a long time, in case the
5087         * samples of this .gig file were not scanned yet
5088         *
5089         * @returns  pointer address to first Sample or NULL if there is none
5090         *           applied to this Group
5091         * @see      GetNextSample()
5092         */
5093        Sample* Group::GetFirstSample() {
5094            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5095            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
5096                if (pSample->GetGroup() == this) return pSample;
5097            }
5098            return NULL;
5099        }
5100    
5101        /**
5102         * Returns the next Sample of the Group. You have to call
5103         * GetFirstSample() once before you can use this method. By calling this
5104         * method multiple times it iterates through the Samples assigned to
5105         * this Group.
5106         *
5107         * @returns  pointer address to the next Sample of this Group or NULL if
5108         *           end reached
5109         * @see      GetFirstSample()
5110         */
5111        Sample* Group::GetNextSample() {
5112            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
5113            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
5114                if (pSample->GetGroup() == this) return pSample;
5115            }
5116            return NULL;
5117        }
5118    
5119        /**
5120         * Move Sample given by \a pSample from another Group to this Group.
5121         */
5122        void Group::AddSample(Sample* pSample) {
5123            pSample->pGroup = this;
5124        }
5125    
5126        /**
5127         * Move all members of this group to another group (preferably the 1st
5128         * one except this). This method is called explicitly by
5129         * File::DeleteGroup() thus when a Group was deleted. This code was
5130         * intentionally not placed in the destructor!
5131         */
5132        void Group::MoveAll() {
5133            // get "that" other group first
5134            Group* pOtherGroup = NULL;
5135            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
5136                if (pOtherGroup != this) break;
5137            }
5138            if (!pOtherGroup) throw Exception(
5139                "Could not move samples to another group, since there is no "
5140                "other Group. This is a bug, report it!"
5141            );
5142            // now move all samples of this group to the other group
5143            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5144                pOtherGroup->AddSample(pSample);
5145            }
5146        }
5147    
5148    
5149    
5150  // *************** File ***************  // *************** File ***************
5151  // *  // *
5152    
5153        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
5154        const DLS::version_t File::VERSION_2 = {
5155            0, 2, 19980628 & 0xffff, 19980628 >> 16
5156        };
5157    
5158        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
5159        const DLS::version_t File::VERSION_3 = {
5160            0, 3, 20030331 & 0xffff, 20030331 >> 16
5161        };
5162    
5163        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
5164            { CHUNK_ID_IARL, 256 },
5165            { CHUNK_ID_IART, 128 },
5166            { CHUNK_ID_ICMS, 128 },
5167            { CHUNK_ID_ICMT, 1024 },
5168            { CHUNK_ID_ICOP, 128 },
5169            { CHUNK_ID_ICRD, 128 },
5170            { CHUNK_ID_IENG, 128 },
5171            { CHUNK_ID_IGNR, 128 },
5172            { CHUNK_ID_IKEY, 128 },
5173            { CHUNK_ID_IMED, 128 },
5174            { CHUNK_ID_INAM, 128 },
5175            { CHUNK_ID_IPRD, 128 },
5176            { CHUNK_ID_ISBJ, 128 },
5177            { CHUNK_ID_ISFT, 128 },
5178            { CHUNK_ID_ISRC, 128 },
5179            { CHUNK_ID_ISRF, 128 },
5180            { CHUNK_ID_ITCH, 128 },
5181            { 0, 0 }
5182        };
5183    
5184      File::File() : DLS::File() {      File::File() : DLS::File() {
5185            bAutoLoad = true;
5186            *pVersion = VERSION_3;
5187            pGroups = NULL;
5188            pScriptGroups = NULL;
5189            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5190            pInfo->ArchivalLocation = String(256, ' ');
5191    
5192            // add some mandatory chunks to get the file chunks in right
5193            // order (INFO chunk will be moved to first position later)
5194            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
5195            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
5196            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
5197    
5198            GenerateDLSID();
5199      }      }
5200    
5201      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5202            bAutoLoad = true;
5203            pGroups = NULL;
5204            pScriptGroups = NULL;
5205            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5206        }
5207    
5208        File::~File() {
5209            if (pGroups) {
5210                std::list<Group*>::iterator iter = pGroups->begin();
5211                std::list<Group*>::iterator end  = pGroups->end();
5212                while (iter != end) {
5213                    delete *iter;
5214                    ++iter;
5215                }
5216                delete pGroups;
5217            }
5218            if (pScriptGroups) {
5219                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5220                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5221                while (iter != end) {
5222                    delete *iter;
5223                    ++iter;
5224                }
5225                delete pScriptGroups;
5226            }
5227      }      }
5228    
5229      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2685  namespace { Line 5238  namespace {
5238          SamplesIterator++;          SamplesIterator++;
5239          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
5240      }      }
5241        
5242        /**
5243         * Returns Sample object of @a index.
5244         *
5245         * @returns sample object or NULL if index is out of bounds
5246         */
5247        Sample* File::GetSample(uint index) {
5248            if (!pSamples) LoadSamples();
5249            if (!pSamples) return NULL;
5250            DLS::File::SampleList::iterator it = pSamples->begin();
5251            for (int i = 0; i < index; ++i) {
5252                ++it;
5253                if (it == pSamples->end()) return NULL;
5254            }
5255            if (it == pSamples->end()) return NULL;
5256            return static_cast<gig::Sample*>( *it );
5257        }
5258    
5259      /** @brief Add a new sample.      /** @brief Add a new sample.
5260       *       *
# Line 2700  namespace { Line 5270  namespace {
5270         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
5271         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
5272         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
5273    
5274           // add mandatory chunks to get the chunks in right order
5275           wave->AddSubChunk(CHUNK_ID_FMT, 16);
5276           wave->AddSubList(LIST_TYPE_INFO);
5277    
5278         pSamples->push_back(pSample);         pSamples->push_back(pSample);
5279         return pSample;         return pSample;
5280      }      }
5281    
5282      /** @brief Delete a sample.      /** @brief Delete a sample.
5283       *       *
5284       * This will delete the given Sample object from the gig file. You have       * This will delete the given Sample object from the gig file. Any
5285       * to call Save() to make this persistent to the file.       * references to this sample from Regions and DimensionRegions will be
5286         * removed. You have to call Save() to make this persistent to the file.
5287       *       *
5288       * @param pSample - sample to delete       * @param pSample - sample to delete
5289       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
# Line 2716  namespace { Line 5292  namespace {
5292          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
5293          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
5294          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
5295            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
5296          pSamples->erase(iter);          pSamples->erase(iter);
5297          delete pSample;          delete pSample;
5298    
5299            SampleList::iterator tmp = SamplesIterator;
5300            // remove all references to the sample
5301            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5302                 instrument = GetNextInstrument()) {
5303                for (Region* region = instrument->GetFirstRegion() ; region ;
5304                     region = instrument->GetNextRegion()) {
5305    
5306                    if (region->GetSample() == pSample) region->SetSample(NULL);
5307    
5308                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
5309                        gig::DimensionRegion *d = region->pDimensionRegions[i];
5310                        if (d->pSample == pSample) d->pSample = NULL;
5311                    }
5312                }
5313            }
5314            SamplesIterator = tmp; // restore iterator
5315      }      }
5316    
5317      void File::LoadSamples() {      void File::LoadSamples() {
# Line 2725  namespace { Line 5319  namespace {
5319      }      }
5320    
5321      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
5322            // Groups must be loaded before samples, because samples will try
5323            // to resolve the group they belong to
5324            if (!pGroups) LoadGroups();
5325    
5326          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
5327    
5328          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
# Line 2804  namespace { Line 5402  namespace {
5402              progress_t subprogress;              progress_t subprogress;
5403              __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
5404              __notify_progress(&subprogress, 0.0f);              __notify_progress(&subprogress, 0.0f);
5405              GetFirstSample(&subprogress); // now force all samples to be loaded              if (GetAutoLoad())
5406                    GetFirstSample(&subprogress); // now force all samples to be loaded
5407              __notify_progress(&subprogress, 1.0f);              __notify_progress(&subprogress, 1.0f);
5408    
5409              // instrument loading subtask              // instrument loading subtask
# Line 2837  namespace { Line 5436  namespace {
5436         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
5437         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
5438         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
5439    
5440           // add mandatory chunks to get the chunks in right order
5441           lstInstr->AddSubList(LIST_TYPE_INFO);
5442           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
5443    
5444         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
5445           pInstrument->GenerateDLSID();
5446    
5447           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
5448    
5449           // this string is needed for the gig to be loadable in GSt:
5450           pInstrument->pInfo->Software = "Endless Wave";
5451    
5452         pInstruments->push_back(pInstrument);         pInstruments->push_back(pInstrument);
5453         return pInstrument;         return pInstrument;
5454      }      }
5455        
5456        /** @brief Add a duplicate of an existing instrument.
5457         *
5458         * Duplicates the instrument definition given by @a orig and adds it
5459         * to this file. This allows in an instrument editor application to
5460         * easily create variations of an instrument, which will be stored in
5461         * the same .gig file, sharing i.e. the same samples.
5462         *
5463         * Note that all sample pointers referenced by @a orig are simply copied as
5464         * memory address. Thus the respective samples are shared, not duplicated!
5465         *
5466         * You have to call Save() to make this persistent to the file.
5467         *
5468         * @param orig - original instrument to be copied
5469         * @returns duplicated copy of the given instrument
5470         */
5471        Instrument* File::AddDuplicateInstrument(const Instrument* orig) {
5472            Instrument* instr = AddInstrument();
5473            instr->CopyAssign(orig);
5474            return instr;
5475        }
5476        
5477        /** @brief Add content of another existing file.
5478         *
5479         * Duplicates the samples, groups and instruments of the original file
5480         * given by @a pFile and adds them to @c this File. In case @c this File is
5481         * a new one that you haven't saved before, then you have to call
5482         * SetFileName() before calling AddContentOf(), because this method will
5483         * automatically save this file during operation, which is required for
5484         * writing the sample waveform data by disk streaming.
5485         *
5486         * @param pFile - original file whose's content shall be copied from
5487         */
5488        void File::AddContentOf(File* pFile) {
5489            static int iCallCount = -1;
5490            iCallCount++;
5491            std::map<Group*,Group*> mGroups;
5492            std::map<Sample*,Sample*> mSamples;
5493            
5494            // clone sample groups
5495            for (int i = 0; pFile->GetGroup(i); ++i) {
5496                Group* g = AddGroup();
5497                g->Name =
5498                    "COPY" + ToString(iCallCount) + "_" + pFile->GetGroup(i)->Name;
5499                mGroups[pFile->GetGroup(i)] = g;
5500            }
5501            
5502            // clone samples (not waveform data here yet)
5503            for (int i = 0; pFile->GetSample(i); ++i) {
5504                Sample* s = AddSample();
5505                s->CopyAssignMeta(pFile->GetSample(i));
5506                mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5507                mSamples[pFile->GetSample(i)] = s;
5508            }
5509            
5510            //BUG: For some reason this method only works with this additional
5511            //     Save() call in between here.
5512            //
5513            // Important: The correct one of the 2 Save() methods has to be called
5514            // here, depending on whether the file is completely new or has been
5515            // saved to disk already, otherwise it will result in data corruption.
5516            if (pRIFF->IsNew())
5517                Save(GetFileName());
5518            else
5519                Save();
5520            
5521            // clone instruments
5522            // (passing the crosslink table here for the cloned samples)
5523            for (int i = 0; pFile->GetInstrument(i); ++i) {
5524                Instrument* instr = AddInstrument();
5525                instr->CopyAssign(pFile->GetInstrument(i), &mSamples);
5526            }
5527            
5528            // Mandatory: file needs to be saved to disk at this point, so this
5529            // file has the correct size and data layout for writing the samples'
5530            // waveform data to disk.
5531            Save();
5532            
5533            // clone samples' waveform data
5534            // (using direct read & write disk streaming)
5535            for (int i = 0; pFile->GetSample(i); ++i) {
5536                mSamples[pFile->GetSample(i)]->CopyAssignWave(pFile->GetSample(i));
5537            }
5538        }
5539    
5540      /** @brief Delete an instrument.      /** @brief Delete an instrument.
5541       *       *
# Line 2848  namespace { Line 5543  namespace {
5543       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
5544       *       *
5545       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
5546       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
5547       */       */
5548      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
5549          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
# Line 2888  namespace { Line 5583  namespace {
5583          }          }
5584      }      }
5585    
5586        /// Updates the 3crc chunk with the checksum of a sample. The
5587        /// update is done directly to disk, as this method is called
5588        /// after File::Save()
5589        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
5590            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5591            if (!_3crc) return;
5592    
5593            // get the index of the sample
5594            int iWaveIndex = -1;
5595            File::SampleList::iterator iter = pSamples->begin();
5596            File::SampleList::iterator end  = pSamples->end();
5597            for (int index = 0; iter != end; ++iter, ++index) {
5598                if (*iter == pSample) {
5599                    iWaveIndex = index;
5600                    break;
5601                }
5602            }
5603            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5604    
5605            // write the CRC-32 checksum to disk
5606            _3crc->SetPos(iWaveIndex * 8);
5607            uint32_t tmp = 1;
5608            _3crc->WriteUint32(&tmp); // unknown, always 1?
5609            _3crc->WriteUint32(&crc);
5610        }
5611    
5612        Group* File::GetFirstGroup() {
5613            if (!pGroups) LoadGroups();
5614            // there must always be at least one group
5615            GroupsIterator = pGroups->begin();
5616            return *GroupsIterator;
5617        }
5618    
5619        Group* File::GetNextGroup() {
5620            if (!pGroups) return NULL;
5621            ++GroupsIterator;
5622            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
5623        }
5624    
5625        /**
5626         * Returns the group with the given index.
5627         *
5628         * @param index - number of the sought group (0..n)
5629         * @returns sought group or NULL if there's no such group
5630         */
5631        Group* File::GetGroup(uint index) {
5632            if (!pGroups) LoadGroups();
5633            GroupsIterator = pGroups->begin();
5634            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
5635                if (i == index) return *GroupsIterator;
5636                ++GroupsIterator;
5637            }
5638            return NULL;
5639        }
5640    
5641        /**
5642         * Returns the group with the given group name.
5643         *
5644         * Note: group names don't have to be unique in the gig format! So there
5645         * can be multiple groups with the same name. This method will simply
5646         * return the first group found with the given name.
5647         *
5648         * @param name - name of the sought group
5649         * @returns sought group or NULL if there's no group with that name
5650         */
5651        Group* File::GetGroup(String name) {
5652            if (!pGroups) LoadGroups();
5653            GroupsIterator = pGroups->begin();
5654            for (uint i = 0; GroupsIterator != pGroups->end(); ++GroupsIterator, ++i)
5655                if ((*GroupsIterator)->Name == name) return *GroupsIterator;
5656            return NULL;
5657        }
5658    
5659        Group* File::AddGroup() {
5660            if (!pGroups) LoadGroups();
5661            // there must always be at least one group
5662            __ensureMandatoryChunksExist();
5663            Group* pGroup = new Group(this, NULL);
5664            pGroups->push_back(pGroup);
5665            return pGroup;
5666        }
5667    
5668        /** @brief Delete a group and its samples.
5669         *
5670         * This will delete the given Group object and all the samples that
5671         * belong to this group from the gig file. You have to call Save() to
5672         * make this persistent to the file.
5673         *
5674         * @param pGroup - group to delete
5675         * @throws gig::Exception if given group could not be found
5676         */
5677        void File::DeleteGroup(Group* pGroup) {
5678            if (!pGroups) LoadGroups();
5679            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5680            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5681            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5682            // delete all members of this group
5683            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
5684                DeleteSample(pSample);
5685            }
5686            // now delete this group object
5687            pGroups->erase(iter);
5688            delete pGroup;
5689        }
5690    
5691        /** @brief Delete a group.
5692         *
5693         * This will delete the given Group object from the gig file. All the
5694         * samples that belong to this group will not be deleted, but instead
5695         * be moved to another group. You have to call Save() to make this
5696         * persistent to the file.
5697         *
5698         * @param pGroup - group to delete
5699         * @throws gig::Exception if given group could not be found
5700         */
5701        void File::DeleteGroupOnly(Group* pGroup) {
5702            if (!pGroups) LoadGroups();
5703            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
5704            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
5705            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
5706            // move all members of this group to another group
5707            pGroup->MoveAll();
5708            pGroups->erase(iter);
5709            delete pGroup;
5710        }
5711    
5712        void File::LoadGroups() {
5713            if (!pGroups) pGroups = new std::list<Group*>;
5714            // try to read defined groups from file
5715            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5716            if (lst3gri) {
5717                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
5718                if (lst3gnl) {
5719                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
5720                    while (ck) {
5721                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
5722                            if (pVersion && pVersion->major == 3 &&
5723                                strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) break;
5724    
5725                            pGroups->push_back(new Group(this, ck));
5726                        }
5727                        ck = lst3gnl->GetNextSubChunk();
5728                    }
5729                }
5730            }
5731            // if there were no group(s), create at least the mandatory default group
5732            if (!pGroups->size()) {
5733                Group* pGroup = new Group(this, NULL);
5734                pGroup->Name = "Default Group";
5735                pGroups->push_back(pGroup);
5736            }
5737        }
5738    
5739        /** @brief Get instrument script group (by index).
5740         *
5741         * Returns the real-time instrument script group with the given index.
5742         *
5743         * @param index - number of the sought group (0..n)
5744         * @returns sought script group or NULL if there's no such group
5745         */
5746        ScriptGroup* File::GetScriptGroup(uint index) {
5747            if (!pScriptGroups) LoadScriptGroups();
5748            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5749            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5750                if (i == index) return *it;
5751            return NULL;
5752        }
5753    
5754        /** @brief Get instrument script group (by name).
5755         *
5756         * Returns the first real-time instrument script group found with the given
5757         * group name. Note that group names may not necessarily be unique.
5758         *
5759         * @param name - name of the sought script group
5760         * @returns sought script group or NULL if there's no such group
5761         */
5762        ScriptGroup* File::GetScriptGroup(const String& name) {
5763            if (!pScriptGroups) LoadScriptGroups();
5764            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5765            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5766                if ((*it)->Name == name) return *it;
5767            return NULL;
5768        }
5769    
5770        /** @brief Add new instrument script group.
5771         *
5772         * Adds a new, empty real-time instrument script group to the file.
5773         *
5774         * You have to call Save() to make this persistent to the file.
5775         *
5776         * @return new empty script group
5777         */
5778        ScriptGroup* File::AddScriptGroup() {
5779            if (!pScriptGroups) LoadScriptGroups();
5780            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5781            pScriptGroups->push_back(pScriptGroup);
5782            return pScriptGroup;
5783        }
5784    
5785        /** @brief Delete an instrument script group.
5786         *
5787         * This will delete the given real-time instrument script group and all its
5788         * instrument scripts it contains. References inside instruments that are
5789         * using the deleted scripts will be removed from the respective instruments
5790         * accordingly.
5791         *
5792         * You have to call Save() to make this persistent to the file.
5793         *
5794         * @param pScriptGroup - script group to delete
5795         * @throws gig::Exception if given script group could not be found
5796         */
5797        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5798            if (!pScriptGroups) LoadScriptGroups();
5799            std::list<ScriptGroup*>::iterator iter =
5800                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5801            if (iter == pScriptGroups->end())
5802                throw gig::Exception("Could not delete script group, could not find given script group");
5803            pScriptGroups->erase(iter);
5804            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5805                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5806            if (pScriptGroup->pList)
5807                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5808            delete pScriptGroup;
5809        }
5810    
5811        void File::LoadScriptGroups() {
5812            if (pScriptGroups) return;
5813            pScriptGroups = new std::list<ScriptGroup*>;
5814            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
5815            if (lstLS) {
5816                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5817                     lst = lstLS->GetNextSubList())
5818                {
5819                    if (lst->GetListType() == LIST_TYPE_RTIS) {
5820                        pScriptGroups->push_back(new ScriptGroup(this, lst));
5821                    }
5822                }
5823            }
5824        }
5825    
5826        /**
5827         * Apply all the gig file's current instruments, samples, groups and settings
5828         * to the respective RIFF chunks. You have to call Save() to make changes
5829         * persistent.
5830         *
5831         * Usually there is absolutely no need to call this method explicitly.
5832         * It will be called automatically when File::Save() was called.
5833         *
5834         * @param pProgress - callback function for progress notification
5835         * @throws Exception - on errors
5836         */
5837        void File::UpdateChunks(progress_t* pProgress) {
5838            bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5839    
5840            b64BitWavePoolOffsets = pVersion && pVersion->major == 3;
5841    
5842            // update own gig format extension chunks
5843            // (not part of the GigaStudio 4 format)
5844            //
5845            // This must be performed before writing the chunks for instruments,
5846            // because the instruments' script slots will write the file offsets
5847            // of the respective instrument script chunk as reference.
5848            if (pScriptGroups) {
5849                RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5850                if (pScriptGroups->empty()) {
5851                    if (lst3LS) pRIFF->DeleteSubChunk(lst3LS);
5852                } else {
5853                    if (!lst3LS) lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5854    
5855                    // Update instrument script (group) chunks.
5856    
5857                    for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5858                         it != pScriptGroups->end(); ++it)
5859                    {
5860                        (*it)->UpdateChunks(pProgress);
5861                    }
5862                }
5863            }
5864    
5865            // first update base class's chunks
5866            DLS::File::UpdateChunks(pProgress);
5867    
5868            if (newFile) {
5869                // INFO was added by Resource::UpdateChunks - make sure it
5870                // is placed first in file
5871                RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
5872                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
5873                if (first != info) {
5874                    pRIFF->MoveSubChunk(info, first);
5875                }
5876            }
5877    
5878            // update group's chunks
5879            if (pGroups) {
5880                // make sure '3gri' and '3gnl' list chunks exist
5881                // (before updating the Group chunks)
5882                RIFF::List* _3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
5883                if (!_3gri) {
5884                    _3gri = pRIFF->AddSubList(LIST_TYPE_3GRI);
5885                    pRIFF->MoveSubChunk(_3gri, pRIFF->GetSubChunk(CHUNK_ID_PTBL));
5886                }
5887                RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
5888                if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
5889    
5890                // v3: make sure the file has 128 3gnm chunks
5891                // (before updating the Group chunks)
5892                if (pVersion && pVersion->major == 3) {
5893                    RIFF::Chunk* _3gnm = _3gnl->GetFirstSubChunk();
5894                    for (int i = 0 ; i < 128 ; i++) {
5895                        if (i >= pGroups->size()) ::SaveString(CHUNK_ID_3GNM, _3gnm, _3gnl, "", "", true, 64);
5896                        if (_3gnm) _3gnm = _3gnl->GetNextSubChunk();
5897                    }
5898                }
5899    
5900                std::list<Group*>::iterator iter = pGroups->begin();
5901                std::list<Group*>::iterator end  = pGroups->end();
5902                for (; iter != end; ++iter) {
5903                    (*iter)->UpdateChunks(pProgress);
5904                }
5905            }
5906    
5907            // update einf chunk
5908    
5909            // The einf chunk contains statistics about the gig file, such
5910            // as the number of regions and samples used by each
5911            // instrument. It is divided in equally sized parts, where the
5912            // first part contains information about the whole gig file,
5913            // and the rest of the parts map to each instrument in the
5914            // file.
5915            //
5916            // At the end of each part there is a bit map of each sample
5917            // in the file, where a set bit means that the sample is used
5918            // by the file/instrument.
5919            //
5920            // Note that there are several fields with unknown use. These
5921            // are set to zero.
5922    
5923            int sublen = pSamples->size() / 8 + 49;
5924            int einfSize = (Instruments + 1) * sublen;
5925    
5926            RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5927            if (einf) {
5928                if (einf->GetSize() != einfSize) {
5929                    einf->Resize(einfSize);
5930                    memset(einf->LoadChunkData(), 0, einfSize);
5931                }
5932            } else if (newFile) {
5933                einf = pRIFF->AddSubChunk(CHUNK_ID_EINF, einfSize);
5934            }
5935            if (einf) {
5936                uint8_t* pData = (uint8_t*) einf->LoadChunkData();
5937    
5938                std::map<gig::Sample*,int> sampleMap;
5939                int sampleIdx = 0;
5940                for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
5941                    sampleMap[pSample] = sampleIdx++;
5942                }
5943    
5944                int totnbusedsamples = 0;
5945                int totnbusedchannels = 0;
5946                int totnbregions = 0;
5947                int totnbdimregions = 0;
5948                int totnbloops = 0;
5949                int instrumentIdx = 0;
5950    
5951                memset(&pData[48], 0, sublen - 48);
5952    
5953                for (Instrument* instrument = GetFirstInstrument() ; instrument ;
5954                     instrument = GetNextInstrument()) {
5955                    int nbusedsamples = 0;
5956                    int nbusedchannels = 0;
5957                    int nbdimregions = 0;
5958                    int nbloops = 0;
5959    
5960                    memset(&pData[(instrumentIdx + 1) * sublen + 48], 0, sublen - 48);
5961    
5962                    for (Region* region = instrument->GetFirstRegion() ; region ;
5963                         region = instrument->GetNextRegion()) {
5964                        for (int i = 0 ; i < region->DimensionRegions ; i++) {
5965                            gig::DimensionRegion *d = region->pDimensionRegions[i];
5966                            if (d->pSample) {
5967                                int sampleIdx = sampleMap[d->pSample];
5968                                int byte = 48 + sampleIdx / 8;
5969                                int bit = 1 << (sampleIdx & 7);
5970                                if ((pData[(instrumentIdx + 1) * sublen + byte] & bit) == 0) {
5971                                    pData[(instrumentIdx + 1) * sublen + byte] |= bit;
5972                                    nbusedsamples++;
5973                                    nbusedchannels += d->pSample->Channels;
5974    
5975                                    if ((pData[byte] & bit) == 0) {
5976                                        pData[byte] |= bit;
5977                                        totnbusedsamples++;
5978                                        totnbusedchannels += d->pSample->Channels;
5979                                    }
5980                                }
5981                            }
5982                            if (d->SampleLoops) nbloops++;
5983                        }
5984                        nbdimregions += region->DimensionRegions;
5985                    }
5986                    // first 4 bytes unknown - sometimes 0, sometimes length of einf part
5987                    // store32(&pData[(instrumentIdx + 1) * sublen], sublen);
5988                    store32(&pData[(instrumentIdx + 1) * sublen + 4], nbusedchannels);
5989                    store32(&pData[(instrumentIdx + 1) * sublen + 8], nbusedsamples);
5990                    store32(&pData[(instrumentIdx + 1) * sublen + 12], 1);
5991                    store32(&pData[(instrumentIdx + 1) * sublen + 16], instrument->Regions);
5992                    store32(&pData[(instrumentIdx + 1) * sublen + 20], nbdimregions);
5993                    store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
5994                    // next 8 bytes unknown
5995                    store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
5996                    store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());
5997                    // next 4 bytes unknown
5998    
5999                    totnbregions += instrument->Regions;
6000                    totnbdimregions += nbdimregions;
6001                    totnbloops += nbloops;
6002                    instrumentIdx++;
6003                }
6004                // first 4 bytes unknown - sometimes 0, sometimes length of einf part
6005                // store32(&pData[0], sublen);
6006                store32(&pData[4], totnbusedchannels);
6007                store32(&pData[8], totnbusedsamples);
6008                store32(&pData[12], Instruments);
6009                store32(&pData[16], totnbregions);
6010                store32(&pData[20], totnbdimregions);
6011                store32(&pData[24], totnbloops);
6012                // next 8 bytes unknown
6013                // next 4 bytes unknown, not always 0
6014                store32(&pData[40], pSamples->size());
6015                // next 4 bytes unknown
6016            }
6017    
6018            // update 3crc chunk
6019    
6020            // The 3crc chunk contains CRC-32 checksums for the
6021            // samples. The actual checksum values will be filled in
6022            // later, by Sample::Write.
6023    
6024            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6025            if (_3crc) {
6026                _3crc->Resize(pSamples->size() * 8);
6027            } else if (newFile) {
6028                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
6029                _3crc->LoadChunkData();
6030    
6031                // the order of einf and 3crc is not the same in v2 and v3
6032                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6033            }
6034        }
6035        
6036        void File::UpdateFileOffsets() {
6037            DLS::File::UpdateFileOffsets();
6038    
6039            for (Instrument* instrument = GetFirstInstrument(); instrument;
6040                 instrument = GetNextInstrument())
6041            {
6042                instrument->UpdateScriptFileOffsets();
6043            }
6044        }
6045    
6046        /**
6047         * Enable / disable automatic loading. By default this properyt is
6048         * enabled and all informations are loaded automatically. However
6049         * loading all Regions, DimensionRegions and especially samples might
6050         * take a long time for large .gig files, and sometimes one might only
6051         * be interested in retrieving very superficial informations like the
6052         * amount of instruments and their names. In this case one might disable
6053         * automatic loading to avoid very slow response times.
6054         *
6055         * @e CAUTION: by disabling this property many pointers (i.e. sample
6056         * references) and informations will have invalid or even undefined
6057         * data! This feature is currently only intended for retrieving very
6058         * superficial informations in a very fast way. Don't use it to retrieve
6059         * details like synthesis informations or even to modify .gig files!
6060         */
6061        void File::SetAutoLoad(bool b) {
6062            bAutoLoad = b;
6063        }
6064    
6065        /**
6066         * Returns whether automatic loading is enabled.
6067         * @see SetAutoLoad()
6068         */
6069        bool File::GetAutoLoad() {
6070            return bAutoLoad;
6071        }
6072    
6073    
6074    
6075  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.858  
changed lines
  Added in v.2836

  ViewVC Help
Powered by ViewVC