/[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 406 by persson, Wed Feb 23 19:11:07 2005 UTC revision 1678 by persson, Sun Feb 10 16:07:22 2008 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-2007 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 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26    #include "helper.h"
27    
28    #include <math.h>
29  #include <iostream>  #include <iostream>
30    
31  namespace gig { namespace {  /// Initial size of the sample buffer which is used for decompression of
32    /// compressed sample wave streams - this value should always be bigger than
33    /// the biggest sample piece expected to be read by the sampler engine,
34    /// otherwise the buffer size will be raised at runtime and thus the buffer
35    /// reallocated which is time consuming and unefficient.
36    #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
37    
38    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
39    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
40    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
41    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
42    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
43    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
44    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
45    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
46    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
47    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
48    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
49    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
50    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
51    
52    namespace gig {
53    
54    // *************** progress_t ***************
55    // *
56    
57        progress_t::progress_t() {
58            callback    = NULL;
59            custom      = NULL;
60            __range_min = 0.0f;
61            __range_max = 1.0f;
62        }
63    
64        // private helper function to convert progress of a subprocess into the global progress
65        static void __notify_progress(progress_t* pProgress, float subprogress) {
66            if (pProgress && pProgress->callback) {
67                const float totalrange    = pProgress->__range_max - pProgress->__range_min;
68                const float totalprogress = pProgress->__range_min + subprogress * totalrange;
69                pProgress->factor         = totalprogress;
70                pProgress->callback(pProgress); // now actually notify about the progress
71            }
72        }
73    
74        // private helper function to divide a progress into subprogresses
75        static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
76            if (pParentProgress && pParentProgress->callback) {
77                const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;
78                pSubProgress->callback    = pParentProgress->callback;
79                pSubProgress->custom      = pParentProgress->custom;
80                pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
81                pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
82            }
83        }
84    
85  // *************** Internal functions for sample decopmression ***************  
86    // *************** Internal functions for sample decompression ***************
87  // *  // *
88    
89    namespace {
90    
91      inline int get12lo(const unsigned char* pSrc)      inline int get12lo(const unsigned char* pSrc)
92      {      {
93          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
# Line 53  namespace gig { namespace { Line 111  namespace gig { namespace {
111          return x & 0x800000 ? x - 0x1000000 : x;          return x & 0x800000 ? x - 0x1000000 : x;
112      }      }
113    
114        inline void store24(unsigned char* pDst, int x)
115        {
116            pDst[0] = x;
117            pDst[1] = x >> 8;
118            pDst[2] = x >> 16;
119        }
120    
121      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
122                        int srcStep, int dstStep,                        int srcStep, int dstStep,
123                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
# Line 92  namespace gig { namespace { Line 157  namespace gig { namespace {
157      }      }
158    
159      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
160                        int dstStep, const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
161                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
162                        unsigned long copysamples)                        unsigned long copysamples, int truncatedBits)
163      {      {
164          // Note: The 24 bits are truncated to 16 bits for now.          int y, dy, ddy, dddy;
165    
166          // Note: The calculation of the initial value of y is strange  #define GET_PARAMS(params)                      \
167          // and not 100% correct. What should the first two parameters          y    = get24(params);                   \
168          // really be used for? Why are they two? The correct value for          dy   = y - get24((params) + 3);         \
169          // y seems to lie somewhere between the values of the first          ddy  = get24((params) + 6);             \
170          // two parameters.          dddy = get24((params) + 9)
         //  
         // Strange thing #2: The formula in SKIP_ONE gives values for  
         // y that are twice as high as they should be. That's why  
         // COPY_ONE shifts 9 steps instead of 8, and also why y is  
         // initialized with a sum instead of a mean value.  
   
         int y, dy, ddy;  
   
 #define GET_PARAMS(params)                              \  
         y = (get24(params) + get24((params) + 3));      \  
         dy  = get24((params) + 6);                      \  
         ddy = get24((params) + 9)  
171    
172  #define SKIP_ONE(x)                             \  #define SKIP_ONE(x)                             \
173          ddy -= (x);                             \          dddy -= (x);                            \
174          dy -= ddy;                              \          ddy  -= dddy;                           \
175          y -= dy          dy   =  -dy - ddy;                      \
176            y    += dy
177    
178  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
179          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
180          *pDst = y >> 9;                         \          store24(pDst, y << truncatedBits);      \
181          pDst += dstStep          pDst += dstStep
182    
183          switch (compressionmode) {          switch (compressionmode) {
184              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
185                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
186                  while (copysamples) {                  while (copysamples) {
187                      *pDst = get24(pSrc) >> 8;                      store24(pDst, get24(pSrc) << truncatedBits);
188                      pDst += dstStep;                      pDst += dstStep;
189                      pSrc += 3;                      pSrc += 3;
190                      copysamples--;                      copysamples--;
# Line 200  namespace gig { namespace { Line 254  namespace gig { namespace {
254  }  }
255    
256    
257    
258    // *************** Internal CRC-32 (Cyclic Redundancy Check) functions  ***************
259    // *
260    
261        static uint32_t* __initCRCTable() {
262            static uint32_t res[256];
263    
264            for (int i = 0 ; i < 256 ; i++) {
265                uint32_t c = i;
266                for (int j = 0 ; j < 8 ; j++) {
267                    c = (c & 1) ? 0xedb88320 ^ (c >> 1) : c >> 1;
268                }
269                res[i] = c;
270            }
271            return res;
272        }
273    
274        static const uint32_t* __CRCTable = __initCRCTable();
275    
276        /**
277         * Initialize a CRC variable.
278         *
279         * @param crc - variable to be initialized
280         */
281        inline static void __resetCRC(uint32_t& crc) {
282            crc = 0xffffffff;
283        }
284    
285        /**
286         * Used to calculate checksums of the sample data in a gig file. The
287         * checksums are stored in the 3crc chunk of the gig file and
288         * automatically updated when a sample is written with Sample::Write().
289         *
290         * One should call __resetCRC() to initialize the CRC variable to be
291         * used before calling this function the first time.
292         *
293         * After initializing the CRC variable one can call this function
294         * arbitrary times, i.e. to split the overall CRC calculation into
295         * steps.
296         *
297         * Once the whole data was processed by __calculateCRC(), one should
298         * call __encodeCRC() to get the final CRC result.
299         *
300         * @param buf     - pointer to data the CRC shall be calculated of
301         * @param bufSize - size of the data to be processed
302         * @param crc     - variable the CRC sum shall be stored to
303         */
304        static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {
305            for (int i = 0 ; i < bufSize ; i++) {
306                crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
307            }
308        }
309    
310        /**
311         * Returns the final CRC result.
312         *
313         * @param crc - variable previously passed to __calculateCRC()
314         */
315        inline static uint32_t __encodeCRC(const uint32_t& crc) {
316            return crc ^ 0xffffffff;
317        }
318    
319    
320    
321    // *************** Other Internal functions  ***************
322    // *
323    
324        static split_type_t __resolveSplitType(dimension_t dimension) {
325            return (
326                dimension == dimension_layer ||
327                dimension == dimension_samplechannel ||
328                dimension == dimension_releasetrigger ||
329                dimension == dimension_keyboard ||
330                dimension == dimension_roundrobin ||
331                dimension == dimension_random ||
332                dimension == dimension_smartmidi ||
333                dimension == dimension_roundrobinkeyboard
334            ) ? split_type_bit : split_type_normal;
335        }
336    
337        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
338            return (dimension_definition.split_type == split_type_normal)
339            ? int(128.0 / dimension_definition.zones) : 0;
340        }
341    
342    
343    
344  // *************** Sample ***************  // *************** Sample ***************
345  // *  // *
346    
347      unsigned int Sample::Instances = 0;      unsigned int Sample::Instances = 0;
348      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
349    
350      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
351         *
352         * Load an existing sample or create a new one. A 'wave' list chunk must
353         * be given to this constructor. In case the given 'wave' list chunk
354         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
355         * format and sample data will be loaded from there, otherwise default
356         * values will be used and those chunks will be created when
357         * File::Save() will be called later on.
358         *
359         * @param pFile          - pointer to gig::File where this sample is
360         *                         located (or will be located)
361         * @param waveList       - pointer to 'wave' list chunk which is (or
362         *                         will be) associated with this sample
363         * @param WavePoolOffset - offset of this sample data from wave pool
364         *                         ('wvpl') list chunk
365         * @param fileNo         - number of an extension file where this sample
366         *                         is located, 0 otherwise
367         */
368        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
369            static const DLS::Info::string_length_t fixedStringLengths[] = {
370                { CHUNK_ID_INAM, 64 },
371                { 0, 0 }
372            };
373            pInfo->SetFixedStringLengths(fixedStringLengths);
374          Instances++;          Instances++;
375            FileNo = fileNo;
376    
377          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          __resetCRC(crc);
378          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");  
379          SampleGroup = _3gix->ReadInt16();          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
380            if (pCk3gix) {
381          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              uint16_t iSampleGroup = pCk3gix->ReadInt16();
382          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              pGroup = pFile->GetGroup(iSampleGroup);
383          Manufacturer      = smpl->ReadInt32();          } else { // '3gix' chunk missing
384          Product           = smpl->ReadInt32();              // by default assigned to that mandatory "Default Group"
385          SamplePeriod      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
386          MIDIUnityNote     = smpl->ReadInt32();          }
387          FineTune          = smpl->ReadInt32();  
388          smpl->Read(&SMPTEFormat, 1, 4);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
389          SMPTEOffset       = smpl->ReadInt32();          if (pCkSmpl) {
390          Loops             = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
391          smpl->ReadInt32(); // manufByt              Product       = pCkSmpl->ReadInt32();
392          LoopID            = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
393          smpl->Read(&LoopType, 1, 4);              MIDIUnityNote = pCkSmpl->ReadInt32();
394          LoopStart         = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
395          LoopEnd           = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
396          LoopFraction      = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
397          LoopPlayCount     = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
398                pCkSmpl->ReadInt32(); // manufByt
399                LoopID        = pCkSmpl->ReadInt32();
400                pCkSmpl->Read(&LoopType, 1, 4);
401                LoopStart     = pCkSmpl->ReadInt32();
402                LoopEnd       = pCkSmpl->ReadInt32();
403                LoopFraction  = pCkSmpl->ReadInt32();
404                LoopPlayCount = pCkSmpl->ReadInt32();
405            } else { // 'smpl' chunk missing
406                // use default values
407                Manufacturer  = 0;
408                Product       = 0;
409                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
410                MIDIUnityNote = 60;
411                FineTune      = 0;
412                SMPTEFormat   = smpte_format_no_offset;
413                SMPTEOffset   = 0;
414                Loops         = 0;
415                LoopID        = 0;
416                LoopType      = loop_type_normal;
417                LoopStart     = 0;
418                LoopEnd       = 0;
419                LoopFraction  = 0;
420                LoopPlayCount = 0;
421            }
422    
423          FrameTable                 = NULL;          FrameTable                 = NULL;
424          SamplePos                  = 0;          SamplePos                  = 0;
# Line 239  namespace gig { namespace { Line 428  namespace gig { namespace {
428    
429          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
430    
431          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
432            Compressed        = ewav;
433            Dithered          = false;
434            TruncatedBits     = 0;
435          if (Compressed) {          if (Compressed) {
436                uint32_t version = ewav->ReadInt32();
437                if (version == 3 && BitDepth == 24) {
438                    Dithered = ewav->ReadInt32();
439                    ewav->SetPos(Channels == 2 ? 84 : 64);
440                    TruncatedBits = ewav->ReadInt32();
441                }
442              ScanCompressedSample();              ScanCompressedSample();
443          }          }
444    
# Line 249  namespace gig { namespace { Line 447  namespace gig { namespace {
447              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
448              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
449          }          }
450          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
451    
452          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
453        }
454    
455        /**
456         * Apply sample and its settings to the respective RIFF chunks. You have
457         * to call File::Save() to make changes persistent.
458         *
459         * Usually there is absolutely no need to call this method explicitly.
460         * It will be called automatically when File::Save() was called.
461         *
462         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
463         *                        was provided yet
464         * @throws gig::Exception if there is any invalid sample setting
465         */
466        void Sample::UpdateChunks() {
467            // first update base class's chunks
468            DLS::Sample::UpdateChunks();
469    
470            // make sure 'smpl' chunk exists
471            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
472            if (!pCkSmpl) {
473                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
474                memset(pCkSmpl->LoadChunkData(), 0, 60);
475            }
476            // update 'smpl' chunk
477            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
478            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
479            store32(&pData[0], Manufacturer);
480            store32(&pData[4], Product);
481            store32(&pData[8], SamplePeriod);
482            store32(&pData[12], MIDIUnityNote);
483            store32(&pData[16], FineTune);
484            store32(&pData[20], SMPTEFormat);
485            store32(&pData[24], SMPTEOffset);
486            store32(&pData[28], Loops);
487    
488            // we skip 'manufByt' for now (4 bytes)
489    
490            store32(&pData[36], LoopID);
491            store32(&pData[40], LoopType);
492            store32(&pData[44], LoopStart);
493            store32(&pData[48], LoopEnd);
494            store32(&pData[52], LoopFraction);
495            store32(&pData[56], LoopPlayCount);
496    
497            // make sure '3gix' chunk exists
498            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
499            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
500            // determine appropriate sample group index (to be stored in chunk)
501            uint16_t iSampleGroup = 0; // 0 refers to default sample group
502            File* pFile = static_cast<File*>(pParent);
503            if (pFile->pGroups) {
504                std::list<Group*>::iterator iter = pFile->pGroups->begin();
505                std::list<Group*>::iterator end  = pFile->pGroups->end();
506                for (int i = 0; iter != end; i++, iter++) {
507                    if (*iter == pGroup) {
508                        iSampleGroup = i;
509                        break; // found
510                    }
511                }
512            }
513            // update '3gix' chunk
514            pData = (uint8_t*) pCk3gix->LoadChunkData();
515            store16(&pData[0], iSampleGroup);
516      }      }
517    
518      /// 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 454  namespace gig { namespace { Line 715  namespace gig { namespace {
715          RAMCache.Size   = 0;          RAMCache.Size   = 0;
716      }      }
717    
718        /** @brief Resize sample.
719         *
720         * Resizes the sample's wave form data, that is the actual size of
721         * sample wave data possible to be written for this sample. This call
722         * will return immediately and just schedule the resize operation. You
723         * should call File::Save() to actually perform the resize operation(s)
724         * "physically" to the file. As this can take a while on large files, it
725         * is recommended to call Resize() first on all samples which have to be
726         * resized and finally to call File::Save() to perform all those resize
727         * operations in one rush.
728         *
729         * The actual size (in bytes) is dependant to the current FrameSize
730         * value. You may want to set FrameSize before calling Resize().
731         *
732         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
733         * enlarged samples before calling File::Save() as this might exceed the
734         * current sample's boundary!
735         *
736         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
737         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
738         * other formats will fail!
739         *
740         * @param iNewSize - new sample wave data size in sample points (must be
741         *                   greater than zero)
742         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
743         *                         or if \a iNewSize is less than 1
744         * @throws gig::Exception if existing sample is compressed
745         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
746         *      DLS::Sample::FormatTag, File::Save()
747         */
748        void Sample::Resize(int iNewSize) {
749            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
750            DLS::Sample::Resize(iNewSize);
751        }
752    
753      /**      /**
754       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
755       * bytes). Use this method and <i>Read()</i> if you don't want to load       * bytes). Use this method and <i>Read()</i> if you don't want to load
# Line 543  namespace gig { namespace { Line 839  namespace gig { namespace {
839       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
840       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
841       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
842         * @param pDimRgn          dimension region with looping information
843       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
844       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
845       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
846       */       */
847      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,
848                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
849          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
850          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
851    
852          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
853    
854          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
855    
856              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
857                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
858    
859                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
860                      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  
861    
862                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
863                              // determine the end position within the loop first,                          do {
864                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
865                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
866                              // backward playback  
867                                if (!pPlaybackState->reverse) { // forward playback
868                              unsigned long swapareastart       = totalreadsamples;                                  do {
869                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
870                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
871                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
872                                        totalreadsamples += readsamples;
873                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
874                                            pPlaybackState->reverse = true;
875                              // read samples for backward playback                                          break;
876                              do {                                      }
877                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
878                                  samplestoreadinloop -= readsamples;                              }
879                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
880    
881                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
882                                    // determine the end position within the loop first,
883                                    // read forward from that 'end' and finally after
884                                    // reading, swap all sample frames so it reflects
885                                    // backward playback
886    
887                                    unsigned long swapareastart       = totalreadsamples;
888                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
889                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
890                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
891    
892                                    SetPos(reverseplaybackend);
893    
894                                    // read samples for backward playback
895                                    do {
896                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
897                                        samplestoreadinloop -= readsamples;
898                                        samplestoread       -= readsamples;
899                                        totalreadsamples    += readsamples;
900                                    } while (samplestoreadinloop && readsamples);
901    
902                                    SetPos(reverseplaybackend); // pretend we really read backwards
903    
904                                    if (reverseplaybackend == loop.LoopStart) {
905                                        pPlaybackState->loop_cycles_left--;
906                                        pPlaybackState->reverse = false;
907                                    }
908    
909                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
910                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
911                              }                              }
912                            } while (samplestoread && readsamples);
913                            break;
914                        }
915    
916                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
917                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
918                          }                          if (!pPlaybackState->reverse) do {
919                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
920                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
921                  }                              samplestoread    -= readsamples;
922                                totalreadsamples += readsamples;
923                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
924                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
925                      if (!pPlaybackState->reverse) do {                                  break;
926                          samplestoloopend  = this->LoopEnd - GetPos();                              }
927                          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);  
928    
929                      if (!samplestoread) break;                          if (!samplestoread) break;
930    
931                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
932                      // determine the end position within the loop first,                          // determine the end position within the loop first,
933                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
934                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
935                      // backward playback                          // backward playback
936    
937                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
938                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
939                      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)
940                                                                                : samplestoread;                                                                                    : samplestoread;
941                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
942    
943                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
944    
945                      // read samples for backward playback                          // read samples for backward playback
946                      do {                          do {
947                          // 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
948                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
949                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
950                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
951                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
952                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
953                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
954                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
955                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
956                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
957                          }                              }
958                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
959    
960                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
961    
962                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
963                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
964                      break;                          break;
965                  }                      }
966    
967                  default: case loop_type_normal: {                      default: case loop_type_normal: {
968                      do {                          do {
969                          // 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
970                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
971                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
972                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
973                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
974                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
975                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
976                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
977                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
978                          }                              }
979                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
980                      break;                          break;
981                        }
982                  }                  }
983              }              }
984          }          }
# Line 705  namespace gig { namespace { Line 1008  namespace gig { namespace {
1008       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
1009       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
1010       *       *
1011         * For 16 bit samples, the data in the buffer will be int16_t
1012         * (using native endianness). For 24 bit, the buffer will
1013         * contain three bytes per sample, little-endian.
1014         *
1015       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
1016       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
1017       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 715  namespace gig { namespace { Line 1022  namespace gig { namespace {
1022          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1023          if (!Compressed) {          if (!Compressed) {
1024              if (BitDepth == 24) {              if (BitDepth == 24) {
1025                  // 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);  
                 }  
1026              }              }
1027              else { // 16 bit              else { // 16 bit
1028                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 765  namespace gig { namespace { Line 1052  namespace gig { namespace {
1052    
1053              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1054              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
1055                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
1056              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1057    
1058              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 846  namespace gig { namespace { Line 1134  namespace gig { namespace {
1134                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1135                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1136    
1137                              Decompress24(mode_l, param_l, 2, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1138                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                                           skipsamples, copysamples, TruncatedBits);
1139                                           skipsamples, copysamples);                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1140                              pDst += copysamples << 1;                                           skipsamples, copysamples, TruncatedBits);
1141                                pDst24 += copysamples * 6;
1142                          }                          }
1143                          else { // Mono                          else { // Mono
1144                              Decompress24(mode_l, param_l, 1, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1145                              pDst += copysamples;                                           skipsamples, copysamples, TruncatedBits);
1146                                pDst24 += copysamples * 3;
1147                          }                          }
1148                      }                      }
1149                      else { // 16 bit                      else { // 16 bit
# Line 895  namespace gig { namespace { Line 1185  namespace gig { namespace {
1185          }          }
1186      }      }
1187    
1188        /** @brief Write sample wave data.
1189         *
1190         * Writes \a SampleCount number of sample points from the buffer pointed
1191         * by \a pBuffer and increments the position within the sample. Use this
1192         * method to directly write the sample data to disk, i.e. if you don't
1193         * want or cannot load the whole sample data into RAM.
1194         *
1195         * You have to Resize() the sample to the desired size and call
1196         * File::Save() <b>before</b> using Write().
1197         *
1198         * Note: there is currently no support for writing compressed samples.
1199         *
1200         * For 16 bit samples, the data in the source buffer should be
1201         * int16_t (using native endianness). For 24 bit, the buffer
1202         * should contain three bytes per sample, little-endian.
1203         *
1204         * @param pBuffer     - source buffer
1205         * @param SampleCount - number of sample points to write
1206         * @throws DLS::Exception if current sample size is too small
1207         * @throws gig::Exception if sample is compressed
1208         * @see DLS::LoadSampleData()
1209         */
1210        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1211            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1212    
1213            // if this is the first write in this sample, reset the
1214            // checksum calculator
1215            if (pCkData->GetPos() == 0) {
1216                __resetCRC(crc);
1217            }
1218            if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1219            unsigned long res;
1220            if (BitDepth == 24) {
1221                res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1222            } else { // 16 bit
1223                res = Channels == 2 ? pCkData->Write(pBuffer, SampleCount << 1, 2) >> 1
1224                                    : pCkData->Write(pBuffer, SampleCount, 2);
1225            }
1226            __calculateCRC((unsigned char *)pBuffer, SampleCount * FrameSize, crc);
1227    
1228            // if this is the last write, update the checksum chunk in the
1229            // file
1230            if (pCkData->GetPos() == pCkData->GetSize()) {
1231                File* pFile = static_cast<File*>(GetParent());
1232                pFile->SetSampleChecksum(this, __encodeCRC(crc));
1233            }
1234            return res;
1235        }
1236    
1237      /**      /**
1238       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1239       * with Sample::Read(). If you are using more than one streaming thread       * with Sample::Read(). If you are using more than one streaming thread
# Line 937  namespace gig { namespace { Line 1276  namespace gig { namespace {
1276          }          }
1277      }      }
1278    
1279        /**
1280         * Returns pointer to the Group this Sample belongs to. In the .gig
1281         * format a sample always belongs to one group. If it wasn't explicitly
1282         * assigned to a certain group, it will be automatically assigned to a
1283         * default group.
1284         *
1285         * @returns Sample's Group (never NULL)
1286         */
1287        Group* Sample::GetGroup() const {
1288            return pGroup;
1289        }
1290    
1291      Sample::~Sample() {      Sample::~Sample() {
1292          Instances--;          Instances--;
1293          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 956  namespace gig { namespace { Line 1307  namespace gig { namespace {
1307      uint                               DimensionRegion::Instances       = 0;      uint                               DimensionRegion::Instances       = 0;
1308      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1309    
1310      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1311          Instances++;          Instances++;
1312    
1313          memcpy(&Crossfade, &SamplerOptions, 4);          pSample = NULL;
1314            pRegion = pParent;
1315    
1316            if (_3ewl->GetSubChunk(CHUNK_ID_WSMP)) memcpy(&Crossfade, &SamplerOptions, 4);
1317            else memset(&Crossfade, 0, 4);
1318    
1319          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1320    
1321          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1322          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1323          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1324          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1325          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1326          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1327          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1328          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1329          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1330          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1331          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1332          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1333          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1334          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1335          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1336          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1337          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1338          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1339          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1340          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1341          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1342          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1343          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1344          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1345          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1346          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1347          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1348          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1349          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1350          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1351          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1352          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1353          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1354          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1355          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1356          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1357          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1358          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1359          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1360          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1361          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1362          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1363          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1364          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1365          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1366          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1367          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1368          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1369          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1370          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1371          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1372          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1373              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1374              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1375          }                  VelocityResponseDepth = velocityresponse;
1376          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1377              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1378              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1379          }              } else if (velocityresponse < 15) {
1380          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1381              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1382              VelocityResponseDepth = velocityresponse - 10;              } else {
1383                    VelocityResponseCurve = curve_type_unknown;
1384                    VelocityResponseDepth = 0;
1385                }
1386                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1387                if (releasevelocityresponse < 5) {
1388                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1389                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1390                } else if (releasevelocityresponse < 10) {
1391                    ReleaseVelocityResponseCurve = curve_type_linear;
1392                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1393                } else if (releasevelocityresponse < 15) {
1394                    ReleaseVelocityResponseCurve = curve_type_special;
1395                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1396                } else {
1397                    ReleaseVelocityResponseCurve = curve_type_unknown;
1398                    ReleaseVelocityResponseDepth = 0;
1399                }
1400                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1401                AttenuationControllerThreshold = _3ewa->ReadInt8();
1402                _3ewa->ReadInt32(); // unknown
1403                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1404                _3ewa->ReadInt16(); // unknown
1405                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1406                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1407                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1408                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1409                else                                       DimensionBypass = dim_bypass_ctrl_none;
1410                uint8_t pan = _3ewa->ReadUint8();
1411                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1412                SelfMask = _3ewa->ReadInt8() & 0x01;
1413                _3ewa->ReadInt8(); // unknown
1414                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1415                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1416                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1417                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1418                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1419                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1420                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1421                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1422                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1423                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1424                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1425                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1426                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1427                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1428                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1429                                                            : vcf_res_ctrl_none;
1430                uint16_t eg3depth = _3ewa->ReadUint16();
1431                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1432                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1433                _3ewa->ReadInt16(); // unknown
1434                ChannelOffset = _3ewa->ReadUint8() / 4;
1435                uint8_t regoptions = _3ewa->ReadUint8();
1436                MSDecode           = regoptions & 0x01; // bit 0
1437                SustainDefeat      = regoptions & 0x02; // bit 1
1438                _3ewa->ReadInt16(); // unknown
1439                VelocityUpperLimit = _3ewa->ReadInt8();
1440                _3ewa->ReadInt8(); // unknown
1441                _3ewa->ReadInt16(); // unknown
1442                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1443                _3ewa->ReadInt8(); // unknown
1444                _3ewa->ReadInt8(); // unknown
1445                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1446                uint8_t vcfcutoff = _3ewa->ReadUint8();
1447                VCFEnabled = vcfcutoff & 0x80; // bit 7
1448                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1449                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1450                uint8_t vcfvelscale = _3ewa->ReadUint8();
1451                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1452                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1453                _3ewa->ReadInt8(); // unknown
1454                uint8_t vcfresonance = _3ewa->ReadUint8();
1455                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1456                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1457                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1458                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1459                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1460                uint8_t vcfvelocity = _3ewa->ReadUint8();
1461                VCFVelocityDynamicRange = vcfvelocity % 5;
1462                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1463                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1464                if (VCFType == vcf_type_lowpass) {
1465                    if (lfo3ctrl & 0x40) // bit 6
1466                        VCFType = vcf_type_lowpassturbo;
1467                }
1468                if (_3ewa->RemainingBytes() >= 8) {
1469                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1470                } else {
1471                    memset(DimensionUpperLimits, 0, 8);
1472                }
1473            } else { // '3ewa' chunk does not exist yet
1474                // use default values
1475                LFO3Frequency                   = 1.0;
1476                EG3Attack                       = 0.0;
1477                LFO1InternalDepth               = 0;
1478                LFO3InternalDepth               = 0;
1479                LFO1ControlDepth                = 0;
1480                LFO3ControlDepth                = 0;
1481                EG1Attack                       = 0.0;
1482                EG1Decay1                       = 0.005;
1483                EG1Sustain                      = 1000;
1484                EG1Release                      = 0.3;
1485                EG1Controller.type              = eg1_ctrl_t::type_none;
1486                EG1Controller.controller_number = 0;
1487                EG1ControllerInvert             = false;
1488                EG1ControllerAttackInfluence    = 0;
1489                EG1ControllerDecayInfluence     = 0;
1490                EG1ControllerReleaseInfluence   = 0;
1491                EG2Controller.type              = eg2_ctrl_t::type_none;
1492                EG2Controller.controller_number = 0;
1493                EG2ControllerInvert             = false;
1494                EG2ControllerAttackInfluence    = 0;
1495                EG2ControllerDecayInfluence     = 0;
1496                EG2ControllerReleaseInfluence   = 0;
1497                LFO1Frequency                   = 1.0;
1498                EG2Attack                       = 0.0;
1499                EG2Decay1                       = 0.005;
1500                EG2Sustain                      = 1000;
1501                EG2Release                      = 0.3;
1502                LFO2ControlDepth                = 0;
1503                LFO2Frequency                   = 1.0;
1504                LFO2InternalDepth               = 0;
1505                EG1Decay2                       = 0.0;
1506                EG1InfiniteSustain              = true;
1507                EG1PreAttack                    = 0;
1508                EG2Decay2                       = 0.0;
1509                EG2InfiniteSustain              = true;
1510                EG2PreAttack                    = 0;
1511                VelocityResponseCurve           = curve_type_nonlinear;
1512                VelocityResponseDepth           = 3;
1513                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1514                ReleaseVelocityResponseDepth    = 3;
1515                VelocityResponseCurveScaling    = 32;
1516                AttenuationControllerThreshold  = 0;
1517                SampleStartOffset               = 0;
1518                PitchTrack                      = true;
1519                DimensionBypass                 = dim_bypass_ctrl_none;
1520                Pan                             = 0;
1521                SelfMask                        = true;
1522                LFO3Controller                  = lfo3_ctrl_modwheel;
1523                LFO3Sync                        = false;
1524                InvertAttenuationController     = false;
1525                AttenuationController.type      = attenuation_ctrl_t::type_none;
1526                AttenuationController.controller_number = 0;
1527                LFO2Controller                  = lfo2_ctrl_internal;
1528                LFO2FlipPhase                   = false;
1529                LFO2Sync                        = false;
1530                LFO1Controller                  = lfo1_ctrl_internal;
1531                LFO1FlipPhase                   = false;
1532                LFO1Sync                        = false;
1533                VCFResonanceController          = vcf_res_ctrl_none;
1534                EG3Depth                        = 0;
1535                ChannelOffset                   = 0;
1536                MSDecode                        = false;
1537                SustainDefeat                   = false;
1538                VelocityUpperLimit              = 0;
1539                ReleaseTriggerDecay             = 0;
1540                EG1Hold                         = false;
1541                VCFEnabled                      = false;
1542                VCFCutoff                       = 0;
1543                VCFCutoffController             = vcf_cutoff_ctrl_none;
1544                VCFCutoffControllerInvert       = false;
1545                VCFVelocityScale                = 0;
1546                VCFResonance                    = 0;
1547                VCFResonanceDynamic             = false;
1548                VCFKeyboardTracking             = false;
1549                VCFKeyboardTrackingBreakpoint   = 0;
1550                VCFVelocityDynamicRange         = 0x04;
1551                VCFVelocityCurve                = curve_type_linear;
1552                VCFType                         = vcf_type_lowpass;
1553                memset(DimensionUpperLimits, 127, 8);
1554            }
1555    
1556            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1557                                                         VelocityResponseDepth,
1558                                                         VelocityResponseCurveScaling);
1559    
1560            pVelocityReleaseTable = GetReleaseVelocityTable(
1561                                        ReleaseVelocityResponseCurve,
1562                                        ReleaseVelocityResponseDepth
1563                                    );
1564    
1565            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve,
1566                                                          VCFVelocityDynamicRange,
1567                                                          VCFVelocityScale,
1568                                                          VCFCutoffController);
1569    
1570            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1571            VelocityTable = 0;
1572        }
1573    
1574        /*
1575         * Constructs a DimensionRegion by copying all parameters from
1576         * another DimensionRegion
1577         */
1578        DimensionRegion::DimensionRegion(RIFF::List* _3ewl, const DimensionRegion& src) : DLS::Sampler(_3ewl) {
1579            Instances++;
1580            *this = src; // default memberwise shallow copy of all parameters
1581            pParentList = _3ewl; // restore the chunk pointer
1582    
1583            // deep copy of owned structures
1584            if (src.VelocityTable) {
1585                VelocityTable = new uint8_t[128];
1586                for (int k = 0 ; k < 128 ; k++)
1587                    VelocityTable[k] = src.VelocityTable[k];
1588            }
1589            if (src.pSampleLoops) {
1590                pSampleLoops = new DLS::sample_loop_t[src.SampleLoops];
1591                for (int k = 0 ; k < src.SampleLoops ; k++)
1592                    pSampleLoops[k] = src.pSampleLoops[k];
1593          }          }
1594          else {      }
1595              VelocityResponseCurve = curve_type_unknown;  
1596              VelocityResponseDepth = 0;      /**
1597         * Updates the respective member variable and updates @c SampleAttenuation
1598         * which depends on this value.
1599         */
1600        void DimensionRegion::SetGain(int32_t gain) {
1601            DLS::Sampler::SetGain(gain);
1602            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1603        }
1604    
1605        /**
1606         * Apply dimension region settings to the respective RIFF chunks. You
1607         * have to call File::Save() to make changes persistent.
1608         *
1609         * Usually there is absolutely no need to call this method explicitly.
1610         * It will be called automatically when File::Save() was called.
1611         */
1612        void DimensionRegion::UpdateChunks() {
1613            // first update base class's chunk
1614            DLS::Sampler::UpdateChunks();
1615    
1616            RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1617            uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
1618            pData[12] = Crossfade.in_start;
1619            pData[13] = Crossfade.in_end;
1620            pData[14] = Crossfade.out_start;
1621            pData[15] = Crossfade.out_end;
1622    
1623            // make sure '3ewa' chunk exists
1624            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1625            if (!_3ewa) {
1626                File* pFile = (File*) GetParent()->GetParent()->GetParent();
1627                bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
1628                _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, version3 ? 148 : 140);
1629            }
1630            pData = (uint8_t*) _3ewa->LoadChunkData();
1631    
1632            // update '3ewa' chunk with DimensionRegion's current settings
1633    
1634            const uint32_t chunksize = _3ewa->GetNewSize();
1635            store32(&pData[0], chunksize); // unknown, always chunk size?
1636    
1637            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1638            store32(&pData[4], lfo3freq);
1639    
1640            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1641            store32(&pData[8], eg3attack);
1642    
1643            // next 2 bytes unknown
1644    
1645            store16(&pData[14], LFO1InternalDepth);
1646    
1647            // next 2 bytes unknown
1648    
1649            store16(&pData[18], LFO3InternalDepth);
1650    
1651            // next 2 bytes unknown
1652    
1653            store16(&pData[22], LFO1ControlDepth);
1654    
1655            // next 2 bytes unknown
1656    
1657            store16(&pData[26], LFO3ControlDepth);
1658    
1659            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1660            store32(&pData[28], eg1attack);
1661    
1662            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1663            store32(&pData[32], eg1decay1);
1664    
1665            // next 2 bytes unknown
1666    
1667            store16(&pData[38], EG1Sustain);
1668    
1669            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1670            store32(&pData[40], eg1release);
1671    
1672            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1673            pData[44] = eg1ctl;
1674    
1675            const uint8_t eg1ctrloptions =
1676                (EG1ControllerInvert ? 0x01 : 0x00) |
1677                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1678                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1679                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1680            pData[45] = eg1ctrloptions;
1681    
1682            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1683            pData[46] = eg2ctl;
1684    
1685            const uint8_t eg2ctrloptions =
1686                (EG2ControllerInvert ? 0x01 : 0x00) |
1687                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1688                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1689                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1690            pData[47] = eg2ctrloptions;
1691    
1692            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1693            store32(&pData[48], lfo1freq);
1694    
1695            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1696            store32(&pData[52], eg2attack);
1697    
1698            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1699            store32(&pData[56], eg2decay1);
1700    
1701            // next 2 bytes unknown
1702    
1703            store16(&pData[62], EG2Sustain);
1704    
1705            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1706            store32(&pData[64], eg2release);
1707    
1708            // next 2 bytes unknown
1709    
1710            store16(&pData[70], LFO2ControlDepth);
1711    
1712            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1713            store32(&pData[72], lfo2freq);
1714    
1715            // next 2 bytes unknown
1716    
1717            store16(&pData[78], LFO2InternalDepth);
1718    
1719            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1720            store32(&pData[80], eg1decay2);
1721    
1722            // next 2 bytes unknown
1723    
1724            store16(&pData[86], EG1PreAttack);
1725    
1726            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1727            store32(&pData[88], eg2decay2);
1728    
1729            // next 2 bytes unknown
1730    
1731            store16(&pData[94], EG2PreAttack);
1732    
1733            {
1734                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1735                uint8_t velocityresponse = VelocityResponseDepth;
1736                switch (VelocityResponseCurve) {
1737                    case curve_type_nonlinear:
1738                        break;
1739                    case curve_type_linear:
1740                        velocityresponse += 5;
1741                        break;
1742                    case curve_type_special:
1743                        velocityresponse += 10;
1744                        break;
1745                    case curve_type_unknown:
1746                    default:
1747                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1748                }
1749                pData[96] = velocityresponse;
1750          }          }
1751          uint8_t releasevelocityresponse = _3ewa->ReadUint8();  
1752          if (releasevelocityresponse < 5) {          {
1753              ReleaseVelocityResponseCurve = curve_type_nonlinear;              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1754              ReleaseVelocityResponseDepth = releasevelocityresponse;              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1755          }              switch (ReleaseVelocityResponseCurve) {
1756          else if (releasevelocityresponse < 10) {                  case curve_type_nonlinear:
1757              ReleaseVelocityResponseCurve = curve_type_linear;                      break;
1758              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  case curve_type_linear:
1759          }                      releasevelocityresponse += 5;
1760          else if (releasevelocityresponse < 15) {                      break;
1761              ReleaseVelocityResponseCurve = curve_type_special;                  case curve_type_special:
1762              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;                      releasevelocityresponse += 10;
1763                        break;
1764                    case curve_type_unknown:
1765                    default:
1766                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1767                }
1768                pData[97] = releasevelocityresponse;
1769          }          }
1770          else {  
1771              ReleaseVelocityResponseCurve = curve_type_unknown;          pData[98] = VelocityResponseCurveScaling;
1772              ReleaseVelocityResponseDepth = 0;  
1773            pData[99] = AttenuationControllerThreshold;
1774    
1775            // next 4 bytes unknown
1776    
1777            store16(&pData[104], SampleStartOffset);
1778    
1779            // next 2 bytes unknown
1780    
1781            {
1782                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1783                switch (DimensionBypass) {
1784                    case dim_bypass_ctrl_94:
1785                        pitchTrackDimensionBypass |= 0x10;
1786                        break;
1787                    case dim_bypass_ctrl_95:
1788                        pitchTrackDimensionBypass |= 0x20;
1789                        break;
1790                    case dim_bypass_ctrl_none:
1791                        //FIXME: should we set anything here?
1792                        break;
1793                    default:
1794                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1795                }
1796                pData[108] = pitchTrackDimensionBypass;
1797          }          }
1798          VelocityResponseCurveScaling = _3ewa->ReadUint8();  
1799          AttenuationControllerThreshold = _3ewa->ReadInt8();          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1800          _3ewa->ReadInt32(); // unknown          pData[109] = pan;
1801          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
1802          _3ewa->ReadInt16(); // unknown          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1803          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          pData[110] = selfmask;
1804          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1805          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          // next byte unknown
1806          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
1807          else                                       DimensionBypass = dim_bypass_ctrl_none;          {
1808          uint8_t pan = _3ewa->ReadUint8();              uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1809          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1810          SelfMask = _3ewa->ReadInt8() & 0x01;              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1811          _3ewa->ReadInt8(); // unknown              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1812          uint8_t lfo3ctrl = _3ewa->ReadUint8();              pData[112] = lfo3ctrl;
         LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits  
         LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
         InvertAttenuationController = lfo3ctrl & 0x80; // bit 7  
         AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));  
         uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
         LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits  
         LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7  
         LFO2Sync               = lfo2ctrl & 0x20; // bit 5  
         bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6  
         uint8_t lfo1ctrl       = _3ewa->ReadUint8();  
         LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits  
         LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7  
         LFO1Sync               = lfo1ctrl & 0x40; // bit 6  
         VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))  
                                                     : vcf_res_ctrl_none;  
         uint16_t eg3depth = _3ewa->ReadUint16();  
         EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */  
                                       : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */  
         _3ewa->ReadInt16(); // unknown  
         ChannelOffset = _3ewa->ReadUint8() / 4;  
         uint8_t regoptions = _3ewa->ReadUint8();  
         MSDecode           = regoptions & 0x01; // bit 0  
         SustainDefeat      = regoptions & 0x02; // bit 1  
         _3ewa->ReadInt16(); // unknown  
         VelocityUpperLimit = _3ewa->ReadInt8();  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt16(); // unknown  
         ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt8(); // unknown  
         EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
         uint8_t vcfcutoff = _3ewa->ReadUint8();  
         VCFEnabled = vcfcutoff & 0x80; // bit 7  
         VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits  
         VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());  
         VCFVelocityScale = _3ewa->ReadUint8();  
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
1813          }          }
1814    
1815          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1816          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;          pData[113] = attenctl;
1817    
1818            {
1819                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1820                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1821                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1822                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1823                pData[114] = lfo2ctrl;
1824            }
1825    
1826            {
1827                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1828                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1829                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1830                if (VCFResonanceController != vcf_res_ctrl_none)
1831                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1832                pData[115] = lfo1ctrl;
1833            }
1834    
1835            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1836                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1837            pData[116] = eg3depth;
1838    
1839            // next 2 bytes unknown
1840    
1841            const uint8_t channeloffset = ChannelOffset * 4;
1842            pData[120] = channeloffset;
1843    
1844            {
1845                uint8_t regoptions = 0;
1846                if (MSDecode)      regoptions |= 0x01; // bit 0
1847                if (SustainDefeat) regoptions |= 0x02; // bit 1
1848                pData[121] = regoptions;
1849            }
1850    
1851            // next 2 bytes unknown
1852    
1853            pData[124] = VelocityUpperLimit;
1854    
1855            // next 3 bytes unknown
1856    
1857            pData[128] = ReleaseTriggerDecay;
1858    
1859            // next 2 bytes unknown
1860    
1861            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1862            pData[131] = eg1hold;
1863    
1864            const uint8_t vcfcutoff = (VCFEnabled ? 0x80 : 0x00) |  /* bit 7 */
1865                                      (VCFCutoff & 0x7f);   /* lower 7 bits */
1866            pData[132] = vcfcutoff;
1867    
1868            pData[133] = VCFCutoffController;
1869    
1870            const uint8_t vcfvelscale = (VCFCutoffControllerInvert ? 0x80 : 0x00) | /* bit 7 */
1871                                        (VCFVelocityScale & 0x7f); /* lower 7 bits */
1872            pData[134] = vcfvelscale;
1873    
1874            // next byte unknown
1875    
1876            const uint8_t vcfresonance = (VCFResonanceDynamic ? 0x00 : 0x80) | /* bit 7 */
1877                                         (VCFResonance & 0x7f); /* lower 7 bits */
1878            pData[136] = vcfresonance;
1879    
1880            const uint8_t vcfbreakpoint = (VCFKeyboardTracking ? 0x80 : 0x00) | /* bit 7 */
1881                                          (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1882            pData[137] = vcfbreakpoint;
1883    
1884            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1885                                        VCFVelocityCurve * 5;
1886            pData[138] = vcfvelocity;
1887    
1888            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1889            pData[139] = vcftype;
1890    
1891            if (chunksize >= 148) {
1892                memcpy(&pData[140], DimensionUpperLimits, 8);
1893            }
1894        }
1895    
1896        double* DimensionRegion::GetReleaseVelocityTable(curve_type_t releaseVelocityResponseCurve, uint8_t releaseVelocityResponseDepth) {
1897            curve_type_t curveType = releaseVelocityResponseCurve;
1898            uint8_t depth = releaseVelocityResponseDepth;
1899            // this models a strange behaviour or bug in GSt: two of the
1900            // velocity response curves for release time are not used even
1901            // if specified, instead another curve is chosen.
1902            if ((curveType == curve_type_nonlinear && depth == 0) ||
1903                (curveType == curve_type_special   && depth == 4)) {
1904                curveType = curve_type_nonlinear;
1905                depth = 3;
1906            }
1907            return GetVelocityTable(curveType, depth, 0);
1908        }
1909    
1910        double* DimensionRegion::GetCutoffVelocityTable(curve_type_t vcfVelocityCurve,
1911                                                        uint8_t vcfVelocityDynamicRange,
1912                                                        uint8_t vcfVelocityScale,
1913                                                        vcf_cutoff_ctrl_t vcfCutoffController)
1914        {
1915            curve_type_t curveType = vcfVelocityCurve;
1916            uint8_t depth = vcfVelocityDynamicRange;
1917            // even stranger GSt: two of the velocity response curves for
1918            // filter cutoff are not used, instead another special curve
1919            // is chosen. This curve is not used anywhere else.
1920            if ((curveType == curve_type_nonlinear && depth == 0) ||
1921                (curveType == curve_type_special   && depth == 4)) {
1922                curveType = curve_type_special;
1923                depth = 5;
1924            }
1925            return GetVelocityTable(curveType, depth,
1926                                    (vcfCutoffController <= vcf_cutoff_ctrl_none2)
1927                                        ? vcfVelocityScale : 0);
1928        }
1929    
1930        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1931        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1932        {
1933            double* table;
1934            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1935          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1936              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1937          }          }
1938          else {          else {
1939              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1940                  CreateVelocityTable(VelocityResponseCurve,              (*pVelocityTables)[tableKey] = table; // put the new table into the tables map
                                     VelocityResponseDepth,  
                                     VelocityResponseCurveScaling);  
             (*pVelocityTables)[tableKey] = pVelocityAttenuationTable; // put the new table into the tables map  
1941          }          }
1942            return table;
1943        }
1944    
1945          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));      Region* DimensionRegion::GetParent() const {
1946            return pRegion;
1947      }      }
1948    
1949      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1247  namespace gig { namespace { Line 2064  namespace gig { namespace {
2064          return decodedcontroller;          return decodedcontroller;
2065      }      }
2066    
2067        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
2068            _lev_ctrl_t encodedcontroller;
2069            switch (DecodedController.type) {
2070                // special controller
2071                case leverage_ctrl_t::type_none:
2072                    encodedcontroller = _lev_ctrl_none;
2073                    break;
2074                case leverage_ctrl_t::type_velocity:
2075                    encodedcontroller = _lev_ctrl_velocity;
2076                    break;
2077                case leverage_ctrl_t::type_channelaftertouch:
2078                    encodedcontroller = _lev_ctrl_channelaftertouch;
2079                    break;
2080    
2081                // ordinary MIDI control change controller
2082                case leverage_ctrl_t::type_controlchange:
2083                    switch (DecodedController.controller_number) {
2084                        case 1:
2085                            encodedcontroller = _lev_ctrl_modwheel;
2086                            break;
2087                        case 2:
2088                            encodedcontroller = _lev_ctrl_breath;
2089                            break;
2090                        case 4:
2091                            encodedcontroller = _lev_ctrl_foot;
2092                            break;
2093                        case 12:
2094                            encodedcontroller = _lev_ctrl_effect1;
2095                            break;
2096                        case 13:
2097                            encodedcontroller = _lev_ctrl_effect2;
2098                            break;
2099                        case 16:
2100                            encodedcontroller = _lev_ctrl_genpurpose1;
2101                            break;
2102                        case 17:
2103                            encodedcontroller = _lev_ctrl_genpurpose2;
2104                            break;
2105                        case 18:
2106                            encodedcontroller = _lev_ctrl_genpurpose3;
2107                            break;
2108                        case 19:
2109                            encodedcontroller = _lev_ctrl_genpurpose4;
2110                            break;
2111                        case 5:
2112                            encodedcontroller = _lev_ctrl_portamentotime;
2113                            break;
2114                        case 64:
2115                            encodedcontroller = _lev_ctrl_sustainpedal;
2116                            break;
2117                        case 65:
2118                            encodedcontroller = _lev_ctrl_portamento;
2119                            break;
2120                        case 66:
2121                            encodedcontroller = _lev_ctrl_sostenutopedal;
2122                            break;
2123                        case 67:
2124                            encodedcontroller = _lev_ctrl_softpedal;
2125                            break;
2126                        case 80:
2127                            encodedcontroller = _lev_ctrl_genpurpose5;
2128                            break;
2129                        case 81:
2130                            encodedcontroller = _lev_ctrl_genpurpose6;
2131                            break;
2132                        case 82:
2133                            encodedcontroller = _lev_ctrl_genpurpose7;
2134                            break;
2135                        case 83:
2136                            encodedcontroller = _lev_ctrl_genpurpose8;
2137                            break;
2138                        case 91:
2139                            encodedcontroller = _lev_ctrl_effect1depth;
2140                            break;
2141                        case 92:
2142                            encodedcontroller = _lev_ctrl_effect2depth;
2143                            break;
2144                        case 93:
2145                            encodedcontroller = _lev_ctrl_effect3depth;
2146                            break;
2147                        case 94:
2148                            encodedcontroller = _lev_ctrl_effect4depth;
2149                            break;
2150                        case 95:
2151                            encodedcontroller = _lev_ctrl_effect5depth;
2152                            break;
2153                        default:
2154                            throw gig::Exception("leverage controller number is not supported by the gig format");
2155                    }
2156                    break;
2157                default:
2158                    throw gig::Exception("Unknown leverage controller type.");
2159            }
2160            return encodedcontroller;
2161        }
2162    
2163      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
2164          Instances--;          Instances--;
2165          if (!Instances) {          if (!Instances) {
# Line 1260  namespace gig { namespace { Line 2173  namespace gig { namespace {
2173              delete pVelocityTables;              delete pVelocityTables;
2174              pVelocityTables = NULL;              pVelocityTables = NULL;
2175          }          }
2176            if (VelocityTable) delete[] VelocityTable;
2177      }      }
2178    
2179      /**      /**
# Line 1277  namespace gig { namespace { Line 2191  namespace gig { namespace {
2191          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
2192      }      }
2193    
2194        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2195            return pVelocityReleaseTable[MIDIKeyVelocity];
2196        }
2197    
2198        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2199            return pVelocityCutoffTable[MIDIKeyVelocity];
2200        }
2201    
2202        /**
2203         * Updates the respective member variable and the lookup table / cache
2204         * that depends on this value.
2205         */
2206        void DimensionRegion::SetVelocityResponseCurve(curve_type_t curve) {
2207            pVelocityAttenuationTable =
2208                GetVelocityTable(
2209                    curve, VelocityResponseDepth, VelocityResponseCurveScaling
2210                );
2211            VelocityResponseCurve = curve;
2212        }
2213    
2214        /**
2215         * Updates the respective member variable and the lookup table / cache
2216         * that depends on this value.
2217         */
2218        void DimensionRegion::SetVelocityResponseDepth(uint8_t depth) {
2219            pVelocityAttenuationTable =
2220                GetVelocityTable(
2221                    VelocityResponseCurve, depth, VelocityResponseCurveScaling
2222                );
2223            VelocityResponseDepth = depth;
2224        }
2225    
2226        /**
2227         * Updates the respective member variable and the lookup table / cache
2228         * that depends on this value.
2229         */
2230        void DimensionRegion::SetVelocityResponseCurveScaling(uint8_t scaling) {
2231            pVelocityAttenuationTable =
2232                GetVelocityTable(
2233                    VelocityResponseCurve, VelocityResponseDepth, scaling
2234                );
2235            VelocityResponseCurveScaling = scaling;
2236        }
2237    
2238        /**
2239         * Updates the respective member variable and the lookup table / cache
2240         * that depends on this value.
2241         */
2242        void DimensionRegion::SetReleaseVelocityResponseCurve(curve_type_t curve) {
2243            pVelocityReleaseTable = GetReleaseVelocityTable(curve, ReleaseVelocityResponseDepth);
2244            ReleaseVelocityResponseCurve = curve;
2245        }
2246    
2247        /**
2248         * Updates the respective member variable and the lookup table / cache
2249         * that depends on this value.
2250         */
2251        void DimensionRegion::SetReleaseVelocityResponseDepth(uint8_t depth) {
2252            pVelocityReleaseTable = GetReleaseVelocityTable(ReleaseVelocityResponseCurve, depth);
2253            ReleaseVelocityResponseDepth = depth;
2254        }
2255    
2256        /**
2257         * Updates the respective member variable and the lookup table / cache
2258         * that depends on this value.
2259         */
2260        void DimensionRegion::SetVCFCutoffController(vcf_cutoff_ctrl_t controller) {
2261            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, VCFVelocityScale, controller);
2262            VCFCutoffController = controller;
2263        }
2264    
2265        /**
2266         * Updates the respective member variable and the lookup table / cache
2267         * that depends on this value.
2268         */
2269        void DimensionRegion::SetVCFVelocityCurve(curve_type_t curve) {
2270            pVelocityCutoffTable = GetCutoffVelocityTable(curve, VCFVelocityDynamicRange, VCFVelocityScale, VCFCutoffController);
2271            VCFVelocityCurve = curve;
2272        }
2273    
2274        /**
2275         * Updates the respective member variable and the lookup table / cache
2276         * that depends on this value.
2277         */
2278        void DimensionRegion::SetVCFVelocityDynamicRange(uint8_t range) {
2279            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, range, VCFVelocityScale, VCFCutoffController);
2280            VCFVelocityDynamicRange = range;
2281        }
2282    
2283        /**
2284         * Updates the respective member variable and the lookup table / cache
2285         * that depends on this value.
2286         */
2287        void DimensionRegion::SetVCFVelocityScale(uint8_t scaling) {
2288            pVelocityCutoffTable = GetCutoffVelocityTable(VCFVelocityCurve, VCFVelocityDynamicRange, scaling, VCFCutoffController);
2289            VCFVelocityScale = scaling;
2290        }
2291    
2292      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) {
2293    
2294          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1310  namespace gig { namespace { Line 2322  namespace gig { namespace {
2322          const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,          const int spe4[] = { 1, 4, 23, 5, 49, 13, 57, 17, 92, 57, 122, 127,
2323                               127, 127 };                               127, 127 };
2324    
2325            // this is only used by the VCF velocity curve
2326            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2327                                 91, 127, 127, 127 };
2328    
2329          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2330                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2331                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2332    
2333          double* const table = new double[128];          double* const table = new double[128];
2334    
# Line 1356  namespace gig { namespace { Line 2372  namespace gig { namespace {
2372    
2373          // Actual Loading          // Actual Loading
2374    
2375            if (!file->GetAutoLoad()) return;
2376    
2377          LoadDimensionRegions(rgnList);          LoadDimensionRegions(rgnList);
2378    
2379          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);          RIFF::Chunk* _3lnk = rgnList->GetSubChunk(CHUNK_ID_3LNK);
# Line 1364  namespace gig { namespace { Line 2382  namespace gig { namespace {
2382              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2383                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2384                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2385                    _3lnk->ReadUint8(); // bit position of the dimension (bits[0] + bits[1] + ... + bits[i-1])
2386                    _3lnk->ReadUint8(); // (1 << bit position of next dimension) - (1 << bit position of this dimension)
2387                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2388                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2389                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2390                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2391                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2392                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2393                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2394                  }                  }
2395                  else { // active dimension                  else { // active dimension
2396                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2397                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2398                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2399                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2400                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger) ? split_type_bit  
                                                                                                   : split_type_normal;  
                     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2401                      Dimensions++;                      Dimensions++;
2402    
2403                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2404                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2405                  }                  }
2406                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2407              }              }
2408                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2409    
2410              // check velocity dimension (if there is one) for custom defined zone ranges              // if there's a velocity dimension and custom velocity zone splits are used,
2411              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2412                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
                 if (pDimDef->dimension == dimension_velocity) {  
                     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {  
                         // no custom defined ranges  
                         pDimDef->split_type = split_type_normal;  
                         pDimDef->ranges     = NULL;  
                     }  
                     else { // custom defined ranges  
                         pDimDef->split_type = split_type_customvelocity;  
                         pDimDef->ranges     = new range_t[pDimDef->zones];  
                         uint8_t bits[8] = { 0 };  
                         int previousUpperLimit = -1;  
                         for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {  
                             bits[i] = velocityZone;  
                             DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);  
   
                             pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;  
                             pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;  
                             previousUpperLimit = pDimDef->ranges[velocityZone].high;  
                             // fill velocity table  
                             for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {  
                                 VelocityTable[i] = velocityZone;  
                             }  
                         }  
                     }  
                 }  
             }  
2413    
2414              // jump to start of the wave pool indices (if not already there)              // jump to start of the wave pool indices (if not already there)
             File* file = (File*) GetParent()->GetParent();  
2415              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2416                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2417              else              else
2418                  _3lnk->SetPos(44);                  _3lnk->SetPos(44);
2419    
2420              // load sample references              // load sample references (if auto loading is enabled)
2421              for (uint i = 0; i < DimensionRegions; i++) {              if (file->GetAutoLoad()) {
2422                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  for (uint i = 0; i < DimensionRegions; i++) {
2423                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                      uint32_t wavepoolindex = _3lnk->ReadUint32();
2424                        if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2425                    }
2426                    GetSample(); // load global region sample reference
2427                }
2428            } else {
2429                DimensionRegions = 0;
2430                for (int i = 0 ; i < 8 ; i++) {
2431                    pDimensionDefinitions[i].dimension  = dimension_none;
2432                    pDimensionDefinitions[i].bits       = 0;
2433                    pDimensionDefinitions[i].zones      = 0;
2434                }
2435            }
2436    
2437            // make sure there is at least one dimension region
2438            if (!DimensionRegions) {
2439                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2440                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2441                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2442                pDimensionRegions[0] = new DimensionRegion(this, _3ewl);
2443                DimensionRegions = 1;
2444            }
2445        }
2446    
2447        /**
2448         * Apply Region settings and all its DimensionRegions to the respective
2449         * RIFF chunks. You have to call File::Save() to make changes persistent.
2450         *
2451         * Usually there is absolutely no need to call this method explicitly.
2452         * It will be called automatically when File::Save() was called.
2453         *
2454         * @throws gig::Exception if samples cannot be dereferenced
2455         */
2456        void Region::UpdateChunks() {
2457            // in the gig format we don't care about the Region's sample reference
2458            // but we still have to provide some existing one to not corrupt the
2459            // file, so to avoid the latter we simply always assign the sample of
2460            // the first dimension region of this region
2461            pSample = pDimensionRegions[0]->pSample;
2462    
2463            // first update base class's chunks
2464            DLS::Region::UpdateChunks();
2465    
2466            // update dimension region's chunks
2467            for (int i = 0; i < DimensionRegions; i++) {
2468                pDimensionRegions[i]->UpdateChunks();
2469            }
2470    
2471            File* pFile = (File*) GetParent()->GetParent();
2472            bool version3 = pFile->pVersion && pFile->pVersion->major == 3;
2473            const int iMaxDimensions =  version3 ? 8 : 5;
2474            const int iMaxDimensionRegions = version3 ? 256 : 32;
2475    
2476            // make sure '3lnk' chunk exists
2477            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2478            if (!_3lnk) {
2479                const int _3lnkChunkSize = version3 ? 1092 : 172;
2480                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2481                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2482    
2483                // move 3prg to last position
2484                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
2485            }
2486    
2487            // update dimension definitions in '3lnk' chunk
2488            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2489            store32(&pData[0], DimensionRegions);
2490            int shift = 0;
2491            for (int i = 0; i < iMaxDimensions; i++) {
2492                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2493                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2494                pData[6 + i * 8] = pDimensionDefinitions[i].dimension == dimension_none ? 0 : shift;
2495                pData[7 + i * 8] = (1 << (shift + pDimensionDefinitions[i].bits)) - (1 << shift);
2496                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2497                // next 3 bytes unknown, always zero?
2498    
2499                shift += pDimensionDefinitions[i].bits;
2500            }
2501    
2502            // update wave pool table in '3lnk' chunk
2503            const int iWavePoolOffset = version3 ? 68 : 44;
2504            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2505                int iWaveIndex = -1;
2506                if (i < DimensionRegions) {
2507                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2508                    File::SampleList::iterator iter = pFile->pSamples->begin();
2509                    File::SampleList::iterator end  = pFile->pSamples->end();
2510                    for (int index = 0; iter != end; ++iter, ++index) {
2511                        if (*iter == pDimensionRegions[i]->pSample) {
2512                            iWaveIndex = index;
2513                            break;
2514                        }
2515                    }
2516              }              }
2517                store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2518          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2519      }      }
2520    
2521      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1445  namespace gig { namespace { Line 2525  namespace gig { namespace {
2525              RIFF::List* _3ewl = _3prg->GetFirstSubList();              RIFF::List* _3ewl = _3prg->GetFirstSubList();
2526              while (_3ewl) {              while (_3ewl) {
2527                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {                  if (_3ewl->GetListType() == LIST_TYPE_3EWL) {
2528                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(_3ewl);                      pDimensionRegions[dimensionRegionNr] = new DimensionRegion(this, _3ewl);
2529                      dimensionRegionNr++;                      dimensionRegionNr++;
2530                  }                  }
2531                  _3ewl = _3prg->GetNextSubList();                  _3ewl = _3prg->GetNextSubList();
# Line 1454  namespace gig { namespace { Line 2534  namespace gig { namespace {
2534          }          }
2535      }      }
2536    
2537      Region::~Region() {      void Region::SetKeyRange(uint16_t Low, uint16_t High) {
2538          for (uint i = 0; i < Dimensions; i++) {          // update KeyRange struct and make sure regions are in correct order
2539              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          DLS::Region::SetKeyRange(Low, High);
2540            // update Region key table for fast lookup
2541            ((gig::Instrument*)GetParent())->UpdateRegionKeyTable();
2542        }
2543    
2544        void Region::UpdateVelocityTable() {
2545            // get velocity dimension's index
2546            int veldim = -1;
2547            for (int i = 0 ; i < Dimensions ; i++) {
2548                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2549                    veldim = i;
2550                    break;
2551                }
2552          }          }
2553            if (veldim == -1) return;
2554    
2555            int step = 1;
2556            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2557            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2558            int end = step * pDimensionDefinitions[veldim].zones;
2559    
2560            // loop through all dimension regions for all dimensions except the velocity dimension
2561            int dim[8] = { 0 };
2562            for (int i = 0 ; i < DimensionRegions ; i++) {
2563    
2564                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2565                    pDimensionRegions[i]->VelocityUpperLimit) {
2566                    // create the velocity table
2567                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2568                    if (!table) {
2569                        table = new uint8_t[128];
2570                        pDimensionRegions[i]->VelocityTable = table;
2571                    }
2572                    int tableidx = 0;
2573                    int velocityZone = 0;
2574                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2575                        for (int k = i ; k < end ; k += step) {
2576                            DimensionRegion *d = pDimensionRegions[k];
2577                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2578                            velocityZone++;
2579                        }
2580                    } else { // gig2
2581                        for (int k = i ; k < end ; k += step) {
2582                            DimensionRegion *d = pDimensionRegions[k];
2583                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2584                            velocityZone++;
2585                        }
2586                    }
2587                } else {
2588                    if (pDimensionRegions[i]->VelocityTable) {
2589                        delete[] pDimensionRegions[i]->VelocityTable;
2590                        pDimensionRegions[i]->VelocityTable = 0;
2591                    }
2592                }
2593    
2594                int j;
2595                int shift = 0;
2596                for (j = 0 ; j < Dimensions ; j++) {
2597                    if (j == veldim) i += skipveldim; // skip velocity dimension
2598                    else {
2599                        dim[j]++;
2600                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2601                        else {
2602                            // skip unused dimension regions
2603                            dim[j] = 0;
2604                            i += ((1 << pDimensionDefinitions[j].bits) -
2605                                  pDimensionDefinitions[j].zones) << shift;
2606                        }
2607                    }
2608                    shift += pDimensionDefinitions[j].bits;
2609                }
2610                if (j == Dimensions) break;
2611            }
2612        }
2613    
2614        /** @brief Einstein would have dreamed of it - create a new dimension.
2615         *
2616         * Creates a new dimension with the dimension definition given by
2617         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2618         * There is a hard limit of dimensions and total amount of "bits" all
2619         * dimensions can have. This limit is dependant to what gig file format
2620         * version this file refers to. The gig v2 (and lower) format has a
2621         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2622         * format has a limit of 8.
2623         *
2624         * @param pDimDef - defintion of the new dimension
2625         * @throws gig::Exception if dimension of the same type exists already
2626         * @throws gig::Exception if amount of dimensions or total amount of
2627         *                        dimension bits limit is violated
2628         */
2629        void Region::AddDimension(dimension_def_t* pDimDef) {
2630            // check if max. amount of dimensions reached
2631            File* file = (File*) GetParent()->GetParent();
2632            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2633            if (Dimensions >= iMaxDimensions)
2634                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2635            // check if max. amount of dimension bits reached
2636            int iCurrentBits = 0;
2637            for (int i = 0; i < Dimensions; i++)
2638                iCurrentBits += pDimensionDefinitions[i].bits;
2639            if (iCurrentBits >= iMaxDimensions)
2640                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2641            const int iNewBits = iCurrentBits + pDimDef->bits;
2642            if (iNewBits > iMaxDimensions)
2643                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2644            // check if there's already a dimensions of the same type
2645            for (int i = 0; i < Dimensions; i++)
2646                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2647                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2648    
2649            // pos is where the new dimension should be placed, normally
2650            // last in list, except for the samplechannel dimension which
2651            // has to be first in list
2652            int pos = pDimDef->dimension == dimension_samplechannel ? 0 : Dimensions;
2653            int bitpos = 0;
2654            for (int i = 0 ; i < pos ; i++)
2655                bitpos += pDimensionDefinitions[i].bits;
2656    
2657            // make room for the new dimension
2658            for (int i = Dimensions ; i > pos ; i--) pDimensionDefinitions[i] = pDimensionDefinitions[i - 1];
2659            for (int i = 0 ; i < (1 << iCurrentBits) ; i++) {
2660                for (int j = Dimensions ; j > pos ; j--) {
2661                    pDimensionRegions[i]->DimensionUpperLimits[j] =
2662                        pDimensionRegions[i]->DimensionUpperLimits[j - 1];
2663                }
2664            }
2665    
2666            // assign definition of new dimension
2667            pDimensionDefinitions[pos] = *pDimDef;
2668    
2669            // auto correct certain dimension definition fields (where possible)
2670            pDimensionDefinitions[pos].split_type  =
2671                __resolveSplitType(pDimensionDefinitions[pos].dimension);
2672            pDimensionDefinitions[pos].zone_size =
2673                __resolveZoneSize(pDimensionDefinitions[pos]);
2674    
2675            // create new dimension region(s) for this new dimension, and make
2676            // sure that the dimension regions are placed correctly in both the
2677            // RIFF list and the pDimensionRegions array
2678            RIFF::Chunk* moveTo = NULL;
2679            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2680            for (int i = (1 << iCurrentBits) - (1 << bitpos) ; i >= 0 ; i -= (1 << bitpos)) {
2681                for (int k = 0 ; k < (1 << bitpos) ; k++) {
2682                    pDimensionRegions[(i << pDimDef->bits) + k] = pDimensionRegions[i + k];
2683                }
2684                for (int j = 1 ; j < (1 << pDimDef->bits) ; j++) {
2685                    for (int k = 0 ; k < (1 << bitpos) ; k++) {
2686                        RIFF::List* pNewDimRgnListChunk = _3prg->AddSubList(LIST_TYPE_3EWL);
2687                        if (moveTo) _3prg->MoveSubChunk(pNewDimRgnListChunk, moveTo);
2688                        // create a new dimension region and copy all parameter values from
2689                        // an existing dimension region
2690                        pDimensionRegions[(i << pDimDef->bits) + (j << bitpos) + k] =
2691                            new DimensionRegion(pNewDimRgnListChunk, *pDimensionRegions[i + k]);
2692    
2693                        DimensionRegions++;
2694                    }
2695                }
2696                moveTo = pDimensionRegions[i]->pParentList;
2697            }
2698    
2699            // initialize the upper limits for this dimension
2700            int mask = (1 << bitpos) - 1;
2701            for (int z = 0 ; z < pDimDef->zones ; z++) {
2702                uint8_t upperLimit = uint8_t((z + 1) * 128.0 / pDimDef->zones - 1);
2703                for (int i = 0 ; i < 1 << iCurrentBits ; i++) {
2704                    pDimensionRegions[((i & ~mask) << pDimDef->bits) |
2705                                      (z << bitpos) |
2706                                      (i & mask)]->DimensionUpperLimits[pos] = upperLimit;
2707                }
2708            }
2709    
2710            Dimensions++;
2711    
2712            // if this is a layer dimension, update 'Layers' attribute
2713            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2714    
2715            UpdateVelocityTable();
2716        }
2717    
2718        /** @brief Delete an existing dimension.
2719         *
2720         * Deletes the dimension given by \a pDimDef and deletes all respective
2721         * dimension regions, that is all dimension regions where the dimension's
2722         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2723         * for example this would delete all dimension regions for the case(s)
2724         * where the sustain pedal is pressed down.
2725         *
2726         * @param pDimDef - dimension to delete
2727         * @throws gig::Exception if given dimension cannot be found
2728         */
2729        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2730            // get dimension's index
2731            int iDimensionNr = -1;
2732            for (int i = 0; i < Dimensions; i++) {
2733                if (&pDimensionDefinitions[i] == pDimDef) {
2734                    iDimensionNr = i;
2735                    break;
2736                }
2737            }
2738            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2739    
2740            // get amount of bits below the dimension to delete
2741            int iLowerBits = 0;
2742            for (int i = 0; i < iDimensionNr; i++)
2743                iLowerBits += pDimensionDefinitions[i].bits;
2744    
2745            // get amount ot bits above the dimension to delete
2746            int iUpperBits = 0;
2747            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2748                iUpperBits += pDimensionDefinitions[i].bits;
2749    
2750            RIFF::List* _3prg = pCkRegion->GetSubList(LIST_TYPE_3PRG);
2751    
2752            // delete dimension regions which belong to the given dimension
2753            // (that is where the dimension's bit > 0)
2754            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2755                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2756                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2757                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2758                                        iObsoleteBit << iLowerBits |
2759                                        iLowerBit;
2760    
2761                        _3prg->DeleteSubChunk(pDimensionRegions[iToDelete]->pParentList);
2762                        delete pDimensionRegions[iToDelete];
2763                        pDimensionRegions[iToDelete] = NULL;
2764                        DimensionRegions--;
2765                    }
2766                }
2767            }
2768    
2769            // defrag pDimensionRegions array
2770            // (that is remove the NULL spaces within the pDimensionRegions array)
2771            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2772                if (!pDimensionRegions[iTo]) {
2773                    if (iFrom <= iTo) iFrom = iTo + 1;
2774                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2775                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2776                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2777                        pDimensionRegions[iFrom] = NULL;
2778                    }
2779                }
2780            }
2781    
2782            // remove the this dimension from the upper limits arrays
2783            for (int j = 0 ; j < 256 && pDimensionRegions[j] ; j++) {
2784                DimensionRegion* d = pDimensionRegions[j];
2785                for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2786                    d->DimensionUpperLimits[i - 1] = d->DimensionUpperLimits[i];
2787                }
2788                d->DimensionUpperLimits[Dimensions - 1] = 127;
2789            }
2790    
2791            // 'remove' dimension definition
2792            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2793                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2794            }
2795            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2796            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2797            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2798    
2799            Dimensions--;
2800    
2801            // if this was a layer dimension, update 'Layers' attribute
2802            if (pDimDef->dimension == dimension_layer) Layers = 1;
2803        }
2804    
2805        Region::~Region() {
2806          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2807              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2808          }          }
# Line 1482  namespace gig { namespace { Line 2827  namespace gig { namespace {
2827       * @see             Dimensions       * @see             Dimensions
2828       */       */
2829      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2830          uint8_t bits[8] = { 0 };          uint8_t bits;
2831            int veldim = -1;
2832            int velbitpos;
2833            int bitpos = 0;
2834            int dimregidx = 0;
2835          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2836              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2837              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2838                  case split_type_normal:                  veldim = i;
2839                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
2840                      break;              } else {
2841                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2842                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2843                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2844                  case split_type_bit: // the value is already the sought dimension bit number                              // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2845                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2846                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                                  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2847                      break;                              }
2848              }                          } else {
2849                                // gig2: evenly sized zones
2850                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2851                            }
2852                            break;
2853                        case split_type_bit: // the value is already the sought dimension bit number
2854                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2855                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2856                            break;
2857                    }
2858                    dimregidx |= bits << bitpos;
2859                }
2860                bitpos += pDimensionDefinitions[i].bits;
2861            }
2862            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2863            if (veldim != -1) {
2864                // (dimreg is now the dimension region for the lowest velocity)
2865                if (dimreg->VelocityTable) // custom defined zone ranges
2866                    bits = dimreg->VelocityTable[DimValues[veldim]];
2867                else // normal split type
2868                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2869    
2870                dimregidx |= bits << velbitpos;
2871                dimreg = pDimensionRegions[dimregidx];
2872          }          }
2873          return GetDimensionRegionByBit(bits);          return dimreg;
2874      }      }
2875    
2876      /**      /**
# Line 1535  namespace gig { namespace { Line 2907  namespace gig { namespace {
2907          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2908      }      }
2909    
2910      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2911          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2912          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2913            if (!file->pWavePoolTable) return NULL;
2914          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2915          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2916            Sample* sample = file->GetFirstSample(pProgress);
2917          while (sample) {          while (sample) {
2918              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2919                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2920              sample = file->GetNextSample();              sample = file->GetNextSample();
2921          }          }
2922          return NULL;          return NULL;
2923      }      }
2924    
2925    
2926    // *************** MidiRule ***************
2927    // *
2928    
2929    MidiRuleCtrlTrigger::MidiRuleCtrlTrigger(RIFF::Chunk* _3ewg) {
2930        _3ewg->SetPos(36);
2931        Triggers = _3ewg->ReadUint8();
2932        _3ewg->SetPos(40);
2933        ControllerNumber = _3ewg->ReadUint8();
2934        _3ewg->SetPos(46);
2935        for (int i = 0 ; i < Triggers ; i++) {
2936            pTriggers[i].TriggerPoint = _3ewg->ReadUint8();
2937            pTriggers[i].Descending = _3ewg->ReadUint8();
2938            pTriggers[i].VelSensitivity = _3ewg->ReadUint8();
2939            pTriggers[i].Key = _3ewg->ReadUint8();
2940            pTriggers[i].NoteOff = _3ewg->ReadUint8();
2941            pTriggers[i].Velocity = _3ewg->ReadUint8();
2942            pTriggers[i].OverridePedal = _3ewg->ReadUint8();
2943            _3ewg->ReadUint8();
2944        }
2945    }
2946    
2947    
2948  // *************** Instrument ***************  // *************** Instrument ***************
2949  // *  // *
2950    
2951      Instrument::Instrument(File* pFile, RIFF::List* insList) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2952            static const DLS::Info::string_length_t fixedStringLengths[] = {
2953                { CHUNK_ID_INAM, 64 },
2954                { CHUNK_ID_ISFT, 12 },
2955                { 0, 0 }
2956            };
2957            pInfo->SetFixedStringLengths(fixedStringLengths);
2958    
2959          // Initialization          // Initialization
2960          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2961          RegionIndex = -1;          EffectSend = 0;
2962            Attenuation = 0;
2963            FineTune = 0;
2964            PitchbendRange = 0;
2965            PianoReleaseMode = false;
2966            DimensionKeyRange.low = 0;
2967            DimensionKeyRange.high = 0;
2968            pMidiRules = new MidiRule*[3];
2969            pMidiRules[0] = NULL;
2970    
2971          // Loading          // Loading
2972          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1570  namespace gig { namespace { Line 2981  namespace gig { namespace {
2981                  PianoReleaseMode       = dimkeystart & 0x01;                  PianoReleaseMode       = dimkeystart & 0x01;
2982                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2983                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2984    
2985                    if (_3ewg->GetSize() > 32) {
2986                        // read MIDI rules
2987                        int i = 0;
2988                        _3ewg->SetPos(32);
2989                        uint8_t id1 = _3ewg->ReadUint8();
2990                        uint8_t id2 = _3ewg->ReadUint8();
2991    
2992                        if (id1 == 4 && id2 == 16) {
2993                            pMidiRules[i++] = new MidiRuleCtrlTrigger(_3ewg);
2994                        }
2995                        //TODO: all the other types of rules
2996    
2997                        pMidiRules[i] = NULL;
2998                    }
2999              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
3000          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
3001    
3002          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          if (pFile->GetAutoLoad()) {
3003          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");              if (!pRegions) pRegions = new RegionList;
3004          pRegions = new Region*[Regions];              RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
3005          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              if (lrgn) {
3006          RIFF::List* rgn = lrgn->GetFirstSubList();                  RIFF::List* rgn = lrgn->GetFirstSubList();
3007          unsigned int iRegion = 0;                  while (rgn) {
3008          while (rgn) {                      if (rgn->GetListType() == LIST_TYPE_RGN) {
3009              if (rgn->GetListType() == LIST_TYPE_RGN) {                          __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
3010                  pRegions[iRegion] = new Region(this, rgn);                          pRegions->push_back(new Region(this, rgn));
3011                  iRegion++;                      }
3012              }                      rgn = lrgn->GetNextSubList();
3013              rgn = lrgn->GetNextSubList();                  }
3014          }                  // Creating Region Key Table for fast lookup
3015                    UpdateRegionKeyTable();
         // Creating Region Key Table for fast lookup  
         for (uint iReg = 0; iReg < Regions; iReg++) {  
             for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {  
                 RegionKeyTable[iKey] = pRegions[iReg];  
3016              }              }
3017          }          }
3018    
3019            __notify_progress(pProgress, 1.0f); // notify done
3020      }      }
3021    
3022      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
3023          for (uint i = 0; i < Regions; i++) {          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
3024              if (pRegions) {          RegionList::iterator iter = pRegions->begin();
3025                  if (pRegions[i]) delete (pRegions[i]);          RegionList::iterator end  = pRegions->end();
3026            for (; iter != end; ++iter) {
3027                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
3028                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
3029                    RegionKeyTable[iKey] = pRegion;
3030              }              }
3031          }          }
3032          if (pRegions) delete[] pRegions;      }
3033    
3034        Instrument::~Instrument() {
3035            delete[] pMidiRules;
3036        }
3037    
3038        /**
3039         * Apply Instrument with all its Regions to the respective RIFF chunks.
3040         * You have to call File::Save() to make changes persistent.
3041         *
3042         * Usually there is absolutely no need to call this method explicitly.
3043         * It will be called automatically when File::Save() was called.
3044         *
3045         * @throws gig::Exception if samples cannot be dereferenced
3046         */
3047        void Instrument::UpdateChunks() {
3048            // first update base classes' chunks
3049            DLS::Instrument::UpdateChunks();
3050    
3051            // update Regions' chunks
3052            {
3053                RegionList::iterator iter = pRegions->begin();
3054                RegionList::iterator end  = pRegions->end();
3055                for (; iter != end; ++iter)
3056                    (*iter)->UpdateChunks();
3057            }
3058    
3059            // make sure 'lart' RIFF list chunk exists
3060            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
3061            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
3062            // make sure '3ewg' RIFF chunk exists
3063            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
3064            if (!_3ewg)  {
3065                File* pFile = (File*) GetParent();
3066    
3067                // 3ewg is bigger in gig3, as it includes the iMIDI rules
3068                int size = (pFile->pVersion && pFile->pVersion->major == 3) ? 16416 : 12;
3069                _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, size);
3070                memset(_3ewg->LoadChunkData(), 0, size);
3071            }
3072            // update '3ewg' RIFF chunk
3073            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
3074            store16(&pData[0], EffectSend);
3075            store32(&pData[2], Attenuation);
3076            store16(&pData[6], FineTune);
3077            store16(&pData[8], PitchbendRange);
3078            const uint8_t dimkeystart = (PianoReleaseMode ? 0x01 : 0x00) |
3079                                        DimensionKeyRange.low << 1;
3080            pData[10] = dimkeystart;
3081            pData[11] = DimensionKeyRange.high;
3082      }      }
3083    
3084      /**      /**
# Line 1614  namespace gig { namespace { Line 3089  namespace gig { namespace {
3089       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
3090       */       */
3091      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
3092          if (!pRegions || Key > 127) return NULL;          if (!pRegions || pRegions->empty() || Key > 127) return NULL;
3093          return RegionKeyTable[Key];          return RegionKeyTable[Key];
3094    
3095          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
3096              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
3097                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1631  namespace gig { namespace { Line 3107  namespace gig { namespace {
3107       * @see      GetNextRegion()       * @see      GetNextRegion()
3108       */       */
3109      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
3110          if (!Regions) return NULL;          if (!pRegions) return NULL;
3111          RegionIndex = 1;          RegionsIterator = pRegions->begin();
3112          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3113      }      }
3114    
3115      /**      /**
# Line 1645  namespace gig { namespace { Line 3121  namespace gig { namespace {
3121       * @see      GetFirstRegion()       * @see      GetFirstRegion()
3122       */       */
3123      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
3124          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
3125          return pRegions[RegionIndex++];          RegionsIterator++;
3126            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
3127        }
3128    
3129        Region* Instrument::AddRegion() {
3130            // create new Region object (and its RIFF chunks)
3131            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3132            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3133            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3134            Region* pNewRegion = new Region(this, rgn);
3135            pRegions->push_back(pNewRegion);
3136            Regions = pRegions->size();
3137            // update Region key table for fast lookup
3138            UpdateRegionKeyTable();
3139            // done
3140            return pNewRegion;
3141        }
3142    
3143        void Instrument::DeleteRegion(Region* pRegion) {
3144            if (!pRegions) return;
3145            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
3146            // update Region key table for fast lookup
3147            UpdateRegionKeyTable();
3148      }      }
3149    
3150        /**
3151         * Returns a MIDI rule of the instrument.
3152         *
3153         * The list of MIDI rules, at least in gig v3, always contains at
3154         * most two rules. The second rule can only be the DEF filter
3155         * (which currently isn't supported by libgig).
3156         *
3157         * @param i - MIDI rule number
3158         * @returns   pointer address to MIDI rule number i or NULL if there is none
3159         */
3160        MidiRule* Instrument::GetMidiRule(int i) {
3161            return pMidiRules[i];
3162        }
3163    
3164    
3165  // *************** File ***************  // *************** Group ***************
3166  // *  // *
3167    
3168      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      /** @brief Constructor.
3169          pSamples     = NULL;       *
3170          pInstruments = NULL;       * @param file   - pointer to the gig::File object
3171         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
3172         *                 NULL if this is a new Group
3173         */
3174        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
3175            pFile      = file;
3176            pNameChunk = ck3gnm;
3177            ::LoadString(pNameChunk, Name);
3178      }      }
3179    
3180      File::~File() {      Group::~Group() {
3181          // free samples          // remove the chunk associated with this group (if any)
3182          if (pSamples) {          if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
3183              SamplesIterator = pSamples->begin();      }
3184              while (SamplesIterator != pSamples->end() ) {  
3185                  delete (*SamplesIterator);      /** @brief Update chunks with current group settings.
3186                  SamplesIterator++;       *
3187         * Apply current Group field values to the respective chunks. You have
3188         * to call File::Save() to make changes persistent.
3189         *
3190         * Usually there is absolutely no need to call this method explicitly.
3191         * It will be called automatically when File::Save() was called.
3192         */
3193        void Group::UpdateChunks() {
3194            // make sure <3gri> and <3gnl> list chunks exist
3195            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
3196            if (!_3gri) {
3197                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
3198                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
3199            }
3200            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
3201            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
3202    
3203            if (!pNameChunk && pFile->pVersion && pFile->pVersion->major == 3) {
3204                // v3 has a fixed list of 128 strings, find a free one
3205                for (RIFF::Chunk* ck = _3gnl->GetFirstSubChunk() ; ck ; ck = _3gnl->GetNextSubChunk()) {
3206                    if (strcmp(static_cast<char*>(ck->LoadChunkData()), "") == 0) {
3207                        pNameChunk = ck;
3208                        break;
3209                    }
3210              }              }
3211              pSamples->clear();          }
3212              delete pSamples;  
3213            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
3214            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
3215        }
3216    
3217        /**
3218         * Returns the first Sample of this Group. You have to call this method
3219         * once before you use GetNextSample().
3220         *
3221         * <b>Notice:</b> this method might block for a long time, in case the
3222         * samples of this .gig file were not scanned yet
3223         *
3224         * @returns  pointer address to first Sample or NULL if there is none
3225         *           applied to this Group
3226         * @see      GetNextSample()
3227         */
3228        Sample* Group::GetFirstSample() {
3229            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3230            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
3231                if (pSample->GetGroup() == this) return pSample;
3232            }
3233            return NULL;
3234        }
3235    
3236        /**
3237         * Returns the next Sample of the Group. You have to call
3238         * GetFirstSample() once before you can use this method. By calling this
3239         * method multiple times it iterates through the Samples assigned to
3240         * this Group.
3241         *
3242         * @returns  pointer address to the next Sample of this Group or NULL if
3243         *           end reached
3244         * @see      GetFirstSample()
3245         */
3246        Sample* Group::GetNextSample() {
3247            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
3248            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
3249                if (pSample->GetGroup() == this) return pSample;
3250            }
3251            return NULL;
3252        }
3253    
3254        /**
3255         * Move Sample given by \a pSample from another Group to this Group.
3256         */
3257        void Group::AddSample(Sample* pSample) {
3258            pSample->pGroup = this;
3259        }
3260    
3261        /**
3262         * Move all members of this group to another group (preferably the 1st
3263         * one except this). This method is called explicitly by
3264         * File::DeleteGroup() thus when a Group was deleted. This code was
3265         * intentionally not placed in the destructor!
3266         */
3267        void Group::MoveAll() {
3268            // get "that" other group first
3269            Group* pOtherGroup = NULL;
3270            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
3271                if (pOtherGroup != this) break;
3272            }
3273            if (!pOtherGroup) throw Exception(
3274                "Could not move samples to another group, since there is no "
3275                "other Group. This is a bug, report it!"
3276            );
3277            // now move all samples of this group to the other group
3278            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
3279                pOtherGroup->AddSample(pSample);
3280          }          }
3281          // free instruments      }
3282          if (pInstruments) {  
3283              InstrumentsIterator = pInstruments->begin();  
3284              while (InstrumentsIterator != pInstruments->end() ) {  
3285                  delete (*InstrumentsIterator);  // *************** File ***************
3286                  InstrumentsIterator++;  // *
3287    
3288        /// Reflects Gigasampler file format version 2.0 (1998-06-28).
3289        const DLS::version_t File::VERSION_2 = {
3290            0, 2, 19980628 & 0xffff, 19980628 >> 16
3291        };
3292    
3293        /// Reflects Gigasampler file format version 3.0 (2003-03-31).
3294        const DLS::version_t File::VERSION_3 = {
3295            0, 3, 20030331 & 0xffff, 20030331 >> 16
3296        };
3297    
3298        static const DLS::Info::string_length_t _FileFixedStringLengths[] = {
3299            { CHUNK_ID_IARL, 256 },
3300            { CHUNK_ID_IART, 128 },
3301            { CHUNK_ID_ICMS, 128 },
3302            { CHUNK_ID_ICMT, 1024 },
3303            { CHUNK_ID_ICOP, 128 },
3304            { CHUNK_ID_ICRD, 128 },
3305            { CHUNK_ID_IENG, 128 },
3306            { CHUNK_ID_IGNR, 128 },
3307            { CHUNK_ID_IKEY, 128 },
3308            { CHUNK_ID_IMED, 128 },
3309            { CHUNK_ID_INAM, 128 },
3310            { CHUNK_ID_IPRD, 128 },
3311            { CHUNK_ID_ISBJ, 128 },
3312            { CHUNK_ID_ISFT, 128 },
3313            { CHUNK_ID_ISRC, 128 },
3314            { CHUNK_ID_ISRF, 128 },
3315            { CHUNK_ID_ITCH, 128 },
3316            { 0, 0 }
3317        };
3318    
3319        File::File() : DLS::File() {
3320            bAutoLoad = true;
3321            *pVersion = VERSION_3;
3322            pGroups = NULL;
3323            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3324            pInfo->ArchivalLocation = String(256, ' ');
3325    
3326            // add some mandatory chunks to get the file chunks in right
3327            // order (INFO chunk will be moved to first position later)
3328            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
3329            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
3330            pRIFF->AddSubChunk(CHUNK_ID_DLID, 16);
3331    
3332            GenerateDLSID();
3333        }
3334    
3335        File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
3336            bAutoLoad = true;
3337            pGroups = NULL;
3338            pInfo->SetFixedStringLengths(_FileFixedStringLengths);
3339        }
3340    
3341        File::~File() {
3342            if (pGroups) {
3343                std::list<Group*>::iterator iter = pGroups->begin();
3344                std::list<Group*>::iterator end  = pGroups->end();
3345                while (iter != end) {
3346                    delete *iter;
3347                    ++iter;
3348              }              }
3349              pInstruments->clear();              delete pGroups;
             delete pInstruments;  
3350          }          }
3351      }      }
3352    
3353      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
3354          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
3355          if (!pSamples) return NULL;          if (!pSamples) return NULL;
3356          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
3357          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1696  namespace gig { namespace { Line 3363  namespace gig { namespace {
3363          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
3364      }      }
3365    
3366      void File::LoadSamples() {      /** @brief Add a new sample.
3367          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);       *
3368          if (wvpl) {       * This will create a new Sample object for the gig file. You have to
3369              unsigned long wvplFileOffset = wvpl->GetFilePos();       * call Save() to make this persistent to the file.
3370              RIFF::List* wave = wvpl->GetFirstSubList();       *
3371              while (wave) {       * @returns pointer to new Sample object
3372                  if (wave->GetListType() == LIST_TYPE_WAVE) {       */
3373                      if (!pSamples) pSamples = new SampleList;      Sample* File::AddSample() {
3374                      unsigned long waveFileOffset = wave->GetFilePos();         if (!pSamples) LoadSamples();
3375                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));         __ensureMandatoryChunksExist();
3376           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
3377           // create new Sample object and its respective 'wave' list chunk
3378           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
3379           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
3380    
3381           // add mandatory chunks to get the chunks in right order
3382           wave->AddSubChunk(CHUNK_ID_FMT, 16);
3383           wave->AddSubList(LIST_TYPE_INFO);
3384    
3385           pSamples->push_back(pSample);
3386           return pSample;
3387        }
3388    
3389        /** @brief Delete a sample.
3390         *
3391         * This will delete the given Sample object from the gig file. Any
3392         * references to this sample from Regions and DimensionRegions will be
3393         * removed. You have to call Save() to make this persistent to the file.
3394         *
3395         * @param pSample - sample to delete
3396         * @throws gig::Exception if given sample could not be found
3397         */
3398        void File::DeleteSample(Sample* pSample) {
3399            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
3400            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
3401            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
3402            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
3403            pSamples->erase(iter);
3404            delete pSample;
3405    
3406            SampleList::iterator tmp = SamplesIterator;
3407            // remove all references to the sample
3408            for (Instrument* instrument = GetFirstInstrument() ; instrument ;
3409                 instrument = GetNextInstrument()) {
3410                for (Region* region = instrument->GetFirstRegion() ; region ;
3411                     region = instrument->GetNextRegion()) {
3412    
3413                    if (region->GetSample() == pSample) region->SetSample(NULL);
3414    
3415                    for (int i = 0 ; i < region->DimensionRegions ; i++) {
3416                        gig::DimensionRegion *d = region->pDimensionRegions[i];
3417                        if (d->pSample == pSample) d->pSample = NULL;
3418                  }                  }
                 wave = wvpl->GetNextSubList();  
3419              }              }
3420          }          }
3421          else throw gig::Exception("Mandatory <wvpl> chunk not found.");          SamplesIterator = tmp; // restore iterator
3422        }
3423    
3424        void File::LoadSamples() {
3425            LoadSamples(NULL);
3426        }
3427    
3428        void File::LoadSamples(progress_t* pProgress) {
3429            // Groups must be loaded before samples, because samples will try
3430            // to resolve the group they belong to
3431            if (!pGroups) LoadGroups();
3432    
3433            if (!pSamples) pSamples = new SampleList;
3434    
3435            RIFF::File* file = pRIFF;
3436    
3437            // just for progress calculation
3438            int iSampleIndex  = 0;
3439            int iTotalSamples = WavePoolCount;
3440    
3441            // check if samples should be loaded from extension files
3442            int lastFileNo = 0;
3443            for (int i = 0 ; i < WavePoolCount ; i++) {
3444                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
3445            }
3446            String name(pRIFF->GetFileName());
3447            int nameLen = name.length();
3448            char suffix[6];
3449            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
3450    
3451            for (int fileNo = 0 ; ; ) {
3452                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
3453                if (wvpl) {
3454                    unsigned long wvplFileOffset = wvpl->GetFilePos();
3455                    RIFF::List* wave = wvpl->GetFirstSubList();
3456                    while (wave) {
3457                        if (wave->GetListType() == LIST_TYPE_WAVE) {
3458                            // notify current progress
3459                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
3460                            __notify_progress(pProgress, subprogress);
3461    
3462                            unsigned long waveFileOffset = wave->GetFilePos();
3463                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
3464    
3465                            iSampleIndex++;
3466                        }
3467                        wave = wvpl->GetNextSubList();
3468                    }
3469    
3470                    if (fileNo == lastFileNo) break;
3471    
3472                    // open extension file (*.gx01, *.gx02, ...)
3473                    fileNo++;
3474                    sprintf(suffix, ".gx%02d", fileNo);
3475                    name.replace(nameLen, 5, suffix);
3476                    file = new RIFF::File(name);
3477                    ExtensionFiles.push_back(file);
3478                } else break;
3479            }
3480    
3481            __notify_progress(pProgress, 1.0); // notify done
3482      }      }
3483    
3484      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
3485          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
3486          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3487          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3488          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3489      }      }
3490    
3491      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
3492          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3493          InstrumentsIterator++;          InstrumentsIterator++;
3494          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3495      }      }
3496    
3497      /**      /**
3498       * Returns the instrument with the given index.       * Returns the instrument with the given index.
3499       *       *
3500         * @param index     - number of the sought instrument (0..n)
3501         * @param pProgress - optional: callback function for progress notification
3502       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
3503       */       */
3504      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
3505          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
3506                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
3507    
3508                // sample loading subtask
3509                progress_t subprogress;
3510                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
3511                __notify_progress(&subprogress, 0.0f);
3512                if (GetAutoLoad())
3513                    GetFirstSample(&subprogress); // now force all samples to be loaded
3514                __notify_progress(&subprogress, 1.0f);
3515    
3516                // instrument loading subtask
3517                if (pProgress && pProgress->callback) {
3518                    subprogress.__range_min = subprogress.__range_max;
3519                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
3520                }
3521                __notify_progress(&subprogress, 0.0f);
3522                LoadInstruments(&subprogress);
3523                __notify_progress(&subprogress, 1.0f);
3524            }
3525          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3526          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3527          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
3528              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
3529              InstrumentsIterator++;              InstrumentsIterator++;
3530          }          }
3531          return NULL;          return NULL;
3532      }      }
3533    
3534        /** @brief Add a new instrument definition.
3535         *
3536         * This will create a new Instrument object for the gig file. You have
3537         * to call Save() to make this persistent to the file.
3538         *
3539         * @returns pointer to new Instrument object
3540         */
3541        Instrument* File::AddInstrument() {
3542           if (!pInstruments) LoadInstruments();
3543           __ensureMandatoryChunksExist();
3544           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3545           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
3546    
3547           // add mandatory chunks to get the chunks in right order
3548           lstInstr->AddSubList(LIST_TYPE_INFO);
3549           lstInstr->AddSubChunk(CHUNK_ID_DLID, 16);
3550    
3551           Instrument* pInstrument = new Instrument(this, lstInstr);
3552           pInstrument->GenerateDLSID();
3553    
3554           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
3555    
3556           // this string is needed for the gig to be loadable in GSt:
3557           pInstrument->pInfo->Software = "Endless Wave";
3558    
3559           pInstruments->push_back(pInstrument);
3560           return pInstrument;
3561        }
3562    
3563        /** @brief Delete an instrument.
3564         *
3565         * This will delete the given Instrument object from the gig file. You
3566         * have to call Save() to make this persistent to the file.
3567         *
3568         * @param pInstrument - instrument to delete
3569         * @throws gig::Exception if given instrument could not be found
3570         */
3571        void File::DeleteInstrument(Instrument* pInstrument) {
3572            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
3573            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
3574            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
3575            pInstruments->erase(iter);
3576            delete pInstrument;
3577        }
3578    
3579      void File::LoadInstruments() {      void File::LoadInstruments() {
3580            LoadInstruments(NULL);
3581        }
3582    
3583        void File::LoadInstruments(progress_t* pProgress) {
3584            if (!pInstruments) pInstruments = new InstrumentList;
3585          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3586          if (lstInstruments) {          if (lstInstruments) {
3587                int iInstrumentIndex = 0;
3588              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
3589              while (lstInstr) {              while (lstInstr) {
3590                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
3591                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
3592                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
3593                        __notify_progress(pProgress, localProgress);
3594    
3595                        // divide local progress into subprogress for loading current Instrument
3596                        progress_t subprogress;
3597                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
3598    
3599                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
3600    
3601                        iInstrumentIndex++;
3602                  }                  }
3603                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
3604              }              }
3605                __notify_progress(pProgress, 1.0); // notify done
3606          }          }
3607          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
3608    
3609        /// Updates the 3crc chunk with the checksum of a sample. The
3610        /// update is done directly to disk, as this method is called
3611        /// after File::Save()
3612        void File::SetSampleChecksum(Sample* pSample, uint32_t crc) {
3613            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
3614            if (!_3crc) return;
3615    
3616            // get the index of the sample
3617            int iWaveIndex = -1;
3618            File::SampleList::iterator iter = pSamples->begin();
3619            File::SampleList::iterator end  = pSamples->end();
3620            for (int index = 0; iter != end; ++iter, ++index) {
3621                if (*iter == pSample) {
3622                    iWaveIndex = index;
3623                    break;
3624                }
3625            }
3626            if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
3627    
3628            // write the CRC-32 checksum to disk
3629            _3crc->SetPos(iWaveIndex * 8);
3630            uint32_t tmp = 1;
3631            _3crc->WriteUint32(&tmp); // unknown, always 1?
3632            _3crc->WriteUint32(&crc);
3633        }
3634    
3635        Group* File::GetFirstGroup() {
3636            if (!pGroups) LoadGroups();
3637            // there must always be at least one group
3638            GroupsIterator = pGroups->begin();
3639            return *GroupsIterator;
3640        }
3641    
3642        Group* File::GetNextGroup() {
3643            if (!pGroups) return NULL;
3644            ++GroupsIterator;
3645            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
3646        }
3647    
3648        /**
3649         * Returns the group with the given index.
3650         *
3651         * @param index - number of the sought group (0..n)
3652         * @returns sought group or NULL if there's no such group
3653         */
3654        Group* File::GetGroup(uint index) {
3655            if (!pGroups) LoadGroups();
3656            GroupsIterator = pGroups->begin();
3657            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
3658                if (i == index) return *GroupsIterator;
3659                ++GroupsIterator;
3660            }
3661            return NULL;
3662        }
3663    
3664        Group* File::AddGroup() {
3665            if (!pGroups) LoadGroups();
3666            // there must always be at least one group
3667            __ensureMandatoryChunksExist();
3668            Group* pGroup = new Group(this, NULL);
3669            pGroups->push_back(pGroup);
3670            return pGroup;
3671        }
3672    
3673        /** @brief Delete a group and its samples.
3674         *
3675         * This will delete the given Group object and all the samples that
3676         * belong to this group from the gig file. You have to call Save() to
3677         * make this persistent to the file.
3678         *
3679         * @param pGroup - group to delete
3680         * @throws gig::Exception if given group could not be found
3681         */
3682        void File::DeleteGroup(Group* pGroup) {
3683            if (!pGroups) LoadGroups();
3684            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3685            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3686            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3687            // delete all members of this group
3688            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
3689                DeleteSample(pSample);
3690            }
3691            // now delete this group object
3692            pGroups->erase(iter);
3693            delete pGroup;
3694        }
3695    
3696        /** @brief Delete a group.
3697         *
3698         * This will delete the given Group object from the gig file. All the
3699         * samples that belong to this group will not be deleted, but instead
3700         * be moved to another group. You have to call Save() to make this
3701         * persistent to the file.
3702         *
3703         * @param pGroup - group to delete
3704         * @throws gig::Exception if given group could not be found
3705         */
3706        void File::DeleteGroupOnly(Group* pGroup) {
3707            if (!pGroups) LoadGroups();
3708            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3709            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3710            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3711            // move all members of this group to another group
3712            pGroup->MoveAll();
3713            pGroups->erase(iter);
3714            delete pGroup;
3715        }
3716    
3717        void File::LoadGroups() {