/[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 384 by schoenebeck, Thu Feb 17 02:22:26 2005 UTC revision 858 by persson, Sat May 6 11:29:29 2006 UTC
# 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 94  namespace gig { namespace { Line 152  namespace gig { namespace {
152      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
153                        int dstStep, const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, int16_t* pDst,
154                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
155                        unsigned long copysamples)                        unsigned long copysamples, int truncatedBits)
156      {      {
157          // Note: The 24 bits are truncated to 16 bits for now.          // Note: The 24 bits are truncated to 16 bits for now.
158    
159          // Note: The calculation of the initial value of y is strange          int y, dy, ddy, dddy;
160          // and not 100% correct. What should the first two parameters          const int shift = 8 - truncatedBits;
161          // really be used for? Why are they two? The correct value for  
162          // y seems to lie somewhere between the values of the first  #define GET_PARAMS(params)                      \
163          // two parameters.          y    = get24(params);                   \
164          //          dy   = y - get24((params) + 3);         \
165          // Strange thing #2: The formula in SKIP_ONE gives values for          ddy  = get24((params) + 6);             \
166          // y that are twice as high as they should be. That's why          dddy = get24((params) + 9)
         // 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)  
167    
168  #define SKIP_ONE(x)                             \  #define SKIP_ONE(x)                             \
169          ddy -= (x);                             \          dddy -= (x);                            \
170          dy -= ddy;                              \          ddy  -= dddy;                           \
171          y -= dy          dy   =  -dy - ddy;                      \
172            y    += dy
173    
174  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
175          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
176          *pDst = y >> 9;                         \          *pDst = y >> shift;                     \
177          pDst += dstStep          pDst += dstStep
178    
179          switch (compressionmode) {          switch (compressionmode) {
180              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
181                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
182                  while (copysamples) {                  while (copysamples) {
183                      *pDst = get24(pSrc) >> 8;                      *pDst = get24(pSrc) >> shift;
184                      pDst += dstStep;                      pDst += dstStep;
185                      pSrc += 3;                      pSrc += 3;
186                      copysamples--;                      copysamples--;
# Line 206  namespace gig { namespace { Line 256  namespace gig { namespace {
256      unsigned int Sample::Instances = 0;      unsigned int Sample::Instances = 0;
257      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
258    
259      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
260         *
261         * Load an existing sample or create a new one. A 'wave' list chunk must
262         * be given to this constructor. In case the given 'wave' list chunk
263         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
264         * format and sample data will be loaded from there, otherwise default
265         * values will be used and those chunks will be created when
266         * File::Save() will be called later on.
267         *
268         * @param pFile          - pointer to gig::File where this sample is
269         *                         located (or will be located)
270         * @param waveList       - pointer to 'wave' list chunk which is (or
271         *                         will be) associated with this sample
272         * @param WavePoolOffset - offset of this sample data from wave pool
273         *                         ('wvpl') list chunk
274         * @param fileNo         - number of an extension file where this sample
275         *                         is located, 0 otherwise
276         */
277        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
278          Instances++;          Instances++;
279            FileNo = fileNo;
280    
281          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
282          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
283          SampleGroup = _3gix->ReadInt16();              SampleGroup = pCk3gix->ReadInt16();
284            } else { // '3gix' chunk missing
285          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              // use default value(s)
286          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              SampleGroup = 0;
287          Manufacturer      = smpl->ReadInt32();          }
288          Product           = smpl->ReadInt32();  
289          SamplePeriod      = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
290          MIDIUnityNote     = smpl->ReadInt32();          if (pCkSmpl) {
291          FineTune          = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
292          smpl->Read(&SMPTEFormat, 1, 4);              Product       = pCkSmpl->ReadInt32();
293          SMPTEOffset       = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
294          Loops             = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
295          smpl->ReadInt32(); // manufByt              FineTune      = pCkSmpl->ReadInt32();
296          LoopID            = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
297          smpl->Read(&LoopType, 1, 4);              SMPTEOffset   = pCkSmpl->ReadInt32();
298          LoopStart         = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
299          LoopEnd           = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
300          LoopFraction      = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
301          LoopPlayCount     = smpl->ReadInt32();              pCkSmpl->Read(&LoopType, 1, 4);
302                LoopStart     = pCkSmpl->ReadInt32();
303                LoopEnd       = pCkSmpl->ReadInt32();
304                LoopFraction  = pCkSmpl->ReadInt32();
305                LoopPlayCount = pCkSmpl->ReadInt32();
306            } else { // 'smpl' chunk missing
307                // use default values
308                Manufacturer  = 0;
309                Product       = 0;
310                SamplePeriod  = 1 / SamplesPerSecond;
311                MIDIUnityNote = 64;
312                FineTune      = 0;
313                SMPTEOffset   = 0;
314                Loops         = 0;
315                LoopID        = 0;
316                LoopStart     = 0;
317                LoopEnd       = 0;
318                LoopFraction  = 0;
319                LoopPlayCount = 0;
320            }
321    
322          FrameTable                 = NULL;          FrameTable                 = NULL;
323          SamplePos                  = 0;          SamplePos                  = 0;
# Line 239  namespace gig { namespace { Line 327  namespace gig { namespace {
327    
328          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");
329    
330          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
331            Compressed        = ewav;
332            Dithered          = false;
333            TruncatedBits     = 0;
334          if (Compressed) {          if (Compressed) {
335                uint32_t version = ewav->ReadInt32();
336                if (version == 3 && BitDepth == 24) {
337                    Dithered = ewav->ReadInt32();
338                    ewav->SetPos(Channels == 2 ? 84 : 64);
339                    TruncatedBits = ewav->ReadInt32();
340                }
341              ScanCompressedSample();              ScanCompressedSample();
342          }          }
343    
# Line 249  namespace gig { namespace { Line 346  namespace gig { namespace {
346              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
347              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
348          }          }
349          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
350    
351          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart;
352      }      }
353    
354        /**
355         * Apply sample and its settings to the respective RIFF chunks. You have
356         * to call File::Save() to make changes persistent.
357         *
358         * Usually there is absolutely no need to call this method explicitly.
359         * It will be called automatically when File::Save() was called.
360         *
361         * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
362         *                        was provided yet
363         * @throws gig::Exception if there is any invalid sample setting
364         */
365        void Sample::UpdateChunks() {
366            // first update base class's chunks
367            DLS::Sample::UpdateChunks();
368    
369            // make sure 'smpl' chunk exists
370            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
371            if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
372            // update 'smpl' chunk
373            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
374            SamplePeriod = 1 / SamplesPerSecond;
375            memcpy(&pData[0], &Manufacturer, 4);
376            memcpy(&pData[4], &Product, 4);
377            memcpy(&pData[8], &SamplePeriod, 4);
378            memcpy(&pData[12], &MIDIUnityNote, 4);
379            memcpy(&pData[16], &FineTune, 4);
380            memcpy(&pData[20], &SMPTEFormat, 4);
381            memcpy(&pData[24], &SMPTEOffset, 4);
382            memcpy(&pData[28], &Loops, 4);
383    
384            // we skip 'manufByt' for now (4 bytes)
385    
386            memcpy(&pData[36], &LoopID, 4);
387            memcpy(&pData[40], &LoopType, 4);
388            memcpy(&pData[44], &LoopStart, 4);
389            memcpy(&pData[48], &LoopEnd, 4);
390            memcpy(&pData[52], &LoopFraction, 4);
391            memcpy(&pData[56], &LoopPlayCount, 4);
392    
393            // make sure '3gix' chunk exists
394            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
395            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
396            // update '3gix' chunk
397            pData = (uint8_t*) pCk3gix->LoadChunkData();
398            memcpy(&pData[0], &SampleGroup, 2);
399        }
400    
401      /// 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).
402      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
403          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
# Line 454  namespace gig { namespace { Line 598  namespace gig { namespace {
598          RAMCache.Size   = 0;          RAMCache.Size   = 0;
599      }      }
600    
601        /** @brief Resize sample.
602         *
603         * Resizes the sample's wave form data, that is the actual size of
604         * sample wave data possible to be written for this sample. This call
605         * will return immediately and just schedule the resize operation. You
606         * should call File::Save() to actually perform the resize operation(s)
607         * "physically" to the file. As this can take a while on large files, it
608         * is recommended to call Resize() first on all samples which have to be
609         * resized and finally to call File::Save() to perform all those resize
610         * operations in one rush.
611         *
612         * The actual size (in bytes) is dependant to the current FrameSize
613         * value. You may want to set FrameSize before calling Resize().
614         *
615         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
616         * enlarged samples before calling File::Save() as this might exceed the
617         * current sample's boundary!
618         *
619         * Also note: only WAVE_FORMAT_PCM is currently supported, that is
620         * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
621         * other formats will fail!
622         *
623         * @param iNewSize - new sample wave data size in sample points (must be
624         *                   greater than zero)
625         * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM
626         *                         or if \a iNewSize is less than 1
627         * @throws gig::Exception if existing sample is compressed
628         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
629         *      DLS::Sample::FormatTag, File::Save()
630         */
631        void Sample::Resize(int iNewSize) {
632            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
633            DLS::Sample::Resize(iNewSize);
634        }
635    
636      /**      /**
637       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
638       * 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 846  namespace gig { namespace { Line 1025  namespace gig { namespace {
1025                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1026                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1027    
1028                              Decompress24(mode_l, param_l, 2, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 2, pSrc, pDst,
1029                                             skipsamples, copysamples, TruncatedBits);
1030                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
1031                                           skipsamples, copysamples);                                           skipsamples, copysamples, TruncatedBits);
1032                              pDst += copysamples << 1;                              pDst += copysamples << 1;
1033                          }                          }
1034                          else { // Mono                          else { // Mono
1035                              Decompress24(mode_l, param_l, 1, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 1, pSrc, pDst,
1036                                             skipsamples, copysamples, TruncatedBits);
1037                              pDst += copysamples;                              pDst += copysamples;
1038                          }                          }
1039                      }                      }
# Line 895  namespace gig { namespace { Line 1076  namespace gig { namespace {
1076          }          }
1077      }      }
1078    
1079        /** @brief Write sample wave data.
1080         *
1081         * Writes \a SampleCount number of sample points from the buffer pointed
1082         * by \a pBuffer and increments the position within the sample. Use this
1083         * method to directly write the sample data to disk, i.e. if you don't
1084         * want or cannot load the whole sample data into RAM.
1085         *
1086         * You have to Resize() the sample to the desired size and call
1087         * File::Save() <b>before</b> using Write().
1088         *
1089         * Note: there is currently no support for writing compressed samples.
1090         *
1091         * @param pBuffer     - source buffer
1092         * @param SampleCount - number of sample points to write
1093         * @throws DLS::Exception if current sample size is too small
1094         * @throws gig::Exception if sample is compressed
1095         * @see DLS::LoadSampleData()
1096         */
1097        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1098            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1099            return DLS::Sample::Write(pBuffer, SampleCount);
1100        }
1101    
1102      /**      /**
1103       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1104       * 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 959  namespace gig { namespace { Line 1163  namespace gig { namespace {
1163      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1164          Instances++;          Instances++;
1165    
1166            pSample = NULL;
1167    
1168          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1169          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1170    
1171          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1172          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1173          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1174          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1175          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1176          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1177          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1178          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1179          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1180          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1181          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1182          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1183          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1184          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1185          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1186          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1187          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1188          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1189          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1190          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1191          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1192          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1193          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1194          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1195          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1196          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1197          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1198          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1199          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1200          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1201          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1202          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1203          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1204          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1205          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1206          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1207          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1208          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1209          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1210          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1211          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1212          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1213          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1214          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1215          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1216          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1217          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1218          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1219          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1220          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1221          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1222          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1223              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1224              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1225          }                  VelocityResponseDepth = velocityresponse;
1226          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1227              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1228              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1229          }              } else if (velocityresponse < 15) {
1230          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1231              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1232              VelocityResponseDepth = velocityresponse - 10;              } else {
1233                    VelocityResponseCurve = curve_type_unknown;
1234                    VelocityResponseDepth = 0;
1235                }
1236                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1237                if (releasevelocityresponse < 5) {
1238                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1239                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1240                } else if (releasevelocityresponse < 10) {
1241                    ReleaseVelocityResponseCurve = curve_type_linear;
1242                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1243                } else if (releasevelocityresponse < 15) {
1244                    ReleaseVelocityResponseCurve = curve_type_special;
1245                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1246                } else {
1247                    ReleaseVelocityResponseCurve = curve_type_unknown;
1248                    ReleaseVelocityResponseDepth = 0;
1249                }
1250                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1251                AttenuationControllerThreshold = _3ewa->ReadInt8();
1252                _3ewa->ReadInt32(); // unknown
1253                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1254                _3ewa->ReadInt16(); // unknown
1255                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1256                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1257                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1258                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1259                else                                       DimensionBypass = dim_bypass_ctrl_none;
1260                uint8_t pan = _3ewa->ReadUint8();
1261                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1262                SelfMask = _3ewa->ReadInt8() & 0x01;
1263                _3ewa->ReadInt8(); // unknown
1264                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1265                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1266                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1267                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1268                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1269                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1270                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1271                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1272                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1273                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1274                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1275                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1276                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1277                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1278                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1279                                                            : vcf_res_ctrl_none;
1280                uint16_t eg3depth = _3ewa->ReadUint16();
1281                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1282                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1283                _3ewa->ReadInt16(); // unknown
1284                ChannelOffset = _3ewa->ReadUint8() / 4;
1285                uint8_t regoptions = _3ewa->ReadUint8();
1286                MSDecode           = regoptions & 0x01; // bit 0
1287                SustainDefeat      = regoptions & 0x02; // bit 1
1288                _3ewa->ReadInt16(); // unknown
1289                VelocityUpperLimit = _3ewa->ReadInt8();
1290                _3ewa->ReadInt8(); // unknown
1291                _3ewa->ReadInt16(); // unknown
1292                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1293                _3ewa->ReadInt8(); // unknown
1294                _3ewa->ReadInt8(); // unknown
1295                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1296                uint8_t vcfcutoff = _3ewa->ReadUint8();
1297                VCFEnabled = vcfcutoff & 0x80; // bit 7
1298                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1299                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1300                uint8_t vcfvelscale = _3ewa->ReadUint8();
1301                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1302                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1303                _3ewa->ReadInt8(); // unknown
1304                uint8_t vcfresonance = _3ewa->ReadUint8();
1305                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1306                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1307                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1308                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1309                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1310                uint8_t vcfvelocity = _3ewa->ReadUint8();
1311                VCFVelocityDynamicRange = vcfvelocity % 5;
1312                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1313                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1314                if (VCFType == vcf_type_lowpass) {
1315                    if (lfo3ctrl & 0x40) // bit 6
1316                        VCFType = vcf_type_lowpassturbo;
1317                }
1318            } else { // '3ewa' chunk does not exist yet
1319                // use default values
1320                LFO3Frequency                   = 1.0;
1321                EG3Attack                       = 0.0;
1322                LFO1InternalDepth               = 0;
1323                LFO3InternalDepth               = 0;
1324                LFO1ControlDepth                = 0;
1325                LFO3ControlDepth                = 0;
1326                EG1Attack                       = 0.0;
1327                EG1Decay1                       = 0.0;
1328                EG1Sustain                      = 0;
1329                EG1Release                      = 0.0;
1330                EG1Controller.type              = eg1_ctrl_t::type_none;
1331                EG1Controller.controller_number = 0;
1332                EG1ControllerInvert             = false;
1333                EG1ControllerAttackInfluence    = 0;
1334                EG1ControllerDecayInfluence     = 0;
1335                EG1ControllerReleaseInfluence   = 0;
1336                EG2Controller.type              = eg2_ctrl_t::type_none;
1337                EG2Controller.controller_number = 0;
1338                EG2ControllerInvert             = false;
1339                EG2ControllerAttackInfluence    = 0;
1340                EG2ControllerDecayInfluence     = 0;
1341                EG2ControllerReleaseInfluence   = 0;
1342                LFO1Frequency                   = 1.0;
1343                EG2Attack                       = 0.0;
1344                EG2Decay1                       = 0.0;
1345                EG2Sustain                      = 0;
1346                EG2Release                      = 0.0;
1347                LFO2ControlDepth                = 0;
1348                LFO2Frequency                   = 1.0;
1349                LFO2InternalDepth               = 0;
1350                EG1Decay2                       = 0.0;
1351                EG1InfiniteSustain              = false;
1352                EG1PreAttack                    = 1000;
1353                EG2Decay2                       = 0.0;
1354                EG2InfiniteSustain              = false;
1355                EG2PreAttack                    = 1000;
1356                VelocityResponseCurve           = curve_type_nonlinear;
1357                VelocityResponseDepth           = 3;
1358                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1359                ReleaseVelocityResponseDepth    = 3;
1360                VelocityResponseCurveScaling    = 32;
1361                AttenuationControllerThreshold  = 0;
1362                SampleStartOffset               = 0;
1363                PitchTrack                      = true;
1364                DimensionBypass                 = dim_bypass_ctrl_none;
1365                Pan                             = 0;
1366                SelfMask                        = true;
1367                LFO3Controller                  = lfo3_ctrl_modwheel;
1368                LFO3Sync                        = false;
1369                InvertAttenuationController     = false;
1370                AttenuationController.type      = attenuation_ctrl_t::type_none;
1371                AttenuationController.controller_number = 0;
1372                LFO2Controller                  = lfo2_ctrl_internal;
1373                LFO2FlipPhase                   = false;
1374                LFO2Sync                        = false;
1375                LFO1Controller                  = lfo1_ctrl_internal;
1376                LFO1FlipPhase                   = false;
1377                LFO1Sync                        = false;
1378                VCFResonanceController          = vcf_res_ctrl_none;
1379                EG3Depth                        = 0;
1380                ChannelOffset                   = 0;
1381                MSDecode                        = false;
1382                SustainDefeat                   = false;
1383                VelocityUpperLimit              = 0;
1384                ReleaseTriggerDecay             = 0;
1385                EG1Hold                         = false;
1386                VCFEnabled                      = false;
1387                VCFCutoff                       = 0;
1388                VCFCutoffController             = vcf_cutoff_ctrl_none;
1389                VCFCutoffControllerInvert       = false;
1390                VCFVelocityScale                = 0;
1391                VCFResonance                    = 0;
1392                VCFResonanceDynamic             = false;
1393                VCFKeyboardTracking             = false;
1394                VCFKeyboardTrackingBreakpoint   = 0;
1395                VCFVelocityDynamicRange         = 0x04;
1396                VCFVelocityCurve                = curve_type_linear;
1397                VCFType                         = vcf_type_lowpass;
1398            }
1399    
1400            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1401                                                         VelocityResponseDepth,
1402                                                         VelocityResponseCurveScaling);
1403    
1404            curve_type_t curveType = ReleaseVelocityResponseCurve;
1405            uint8_t depth = ReleaseVelocityResponseDepth;
1406    
1407            // this models a strange behaviour or bug in GSt: two of the
1408            // velocity response curves for release time are not used even
1409            // if specified, instead another curve is chosen.
1410            if ((curveType == curve_type_nonlinear && depth == 0) ||
1411                (curveType == curve_type_special   && depth == 4)) {
1412                curveType = curve_type_nonlinear;
1413                depth = 3;
1414            }
1415            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1416    
1417            curveType = VCFVelocityCurve;
1418            depth = VCFVelocityDynamicRange;
1419    
1420            // even stranger GSt: two of the velocity response curves for
1421            // filter cutoff are not used, instead another special curve
1422            // is chosen. This curve is not used anywhere else.
1423            if ((curveType == curve_type_nonlinear && depth == 0) ||
1424                (curveType == curve_type_special   && depth == 4)) {
1425                curveType = curve_type_special;
1426                depth = 5;
1427          }          }
1428          else {          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1429              VelocityResponseCurve = curve_type_unknown;                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1430              VelocityResponseDepth = 0;  
1431            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1432            VelocityTable = 0;
1433        }
1434    
1435        /**
1436         * Apply dimension region settings to the respective RIFF chunks. You
1437         * have to call File::Save() to make changes persistent.
1438         *
1439         * Usually there is absolutely no need to call this method explicitly.
1440         * It will be called automatically when File::Save() was called.
1441         */
1442        void DimensionRegion::UpdateChunks() {
1443            // first update base class's chunk
1444            DLS::Sampler::UpdateChunks();
1445    
1446            // make sure '3ewa' chunk exists
1447            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1448            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1449            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1450    
1451            // update '3ewa' chunk with DimensionRegion's current settings
1452    
1453            const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1454            memcpy(&pData[0], &unknown, 4);
1455    
1456            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1457            memcpy(&pData[4], &lfo3freq, 4);
1458    
1459            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1460            memcpy(&pData[4], &eg3attack, 4);
1461    
1462            // next 2 bytes unknown
1463    
1464            memcpy(&pData[10], &LFO1InternalDepth, 2);
1465    
1466            // next 2 bytes unknown
1467    
1468            memcpy(&pData[14], &LFO3InternalDepth, 2);
1469    
1470            // next 2 bytes unknown
1471    
1472            memcpy(&pData[18], &LFO1ControlDepth, 2);
1473    
1474            // next 2 bytes unknown
1475    
1476            memcpy(&pData[22], &LFO3ControlDepth, 2);
1477    
1478            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1479            memcpy(&pData[24], &eg1attack, 4);
1480    
1481            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1482            memcpy(&pData[28], &eg1decay1, 4);
1483    
1484            // next 2 bytes unknown
1485    
1486            memcpy(&pData[34], &EG1Sustain, 2);
1487    
1488            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1489            memcpy(&pData[36], &eg1release, 4);
1490    
1491            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1492            memcpy(&pData[40], &eg1ctl, 1);
1493    
1494            const uint8_t eg1ctrloptions =
1495                (EG1ControllerInvert) ? 0x01 : 0x00 |
1496                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1497                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1498                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1499            memcpy(&pData[41], &eg1ctrloptions, 1);
1500    
1501            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1502            memcpy(&pData[42], &eg2ctl, 1);
1503    
1504            const uint8_t eg2ctrloptions =
1505                (EG2ControllerInvert) ? 0x01 : 0x00 |
1506                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1507                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1508                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1509            memcpy(&pData[43], &eg2ctrloptions, 1);
1510    
1511            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1512            memcpy(&pData[44], &lfo1freq, 4);
1513    
1514            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1515            memcpy(&pData[48], &eg2attack, 4);
1516    
1517            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1518            memcpy(&pData[52], &eg2decay1, 4);
1519    
1520            // next 2 bytes unknown
1521    
1522            memcpy(&pData[58], &EG2Sustain, 2);
1523    
1524            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1525            memcpy(&pData[60], &eg2release, 4);
1526    
1527            // next 2 bytes unknown
1528    
1529            memcpy(&pData[66], &LFO2ControlDepth, 2);
1530    
1531            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1532            memcpy(&pData[68], &lfo2freq, 4);
1533    
1534            // next 2 bytes unknown
1535    
1536            memcpy(&pData[72], &LFO2InternalDepth, 2);
1537    
1538            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1539            memcpy(&pData[74], &eg1decay2, 4);
1540    
1541            // next 2 bytes unknown
1542    
1543            memcpy(&pData[80], &EG1PreAttack, 2);
1544    
1545            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1546            memcpy(&pData[82], &eg2decay2, 4);
1547    
1548            // next 2 bytes unknown
1549    
1550            memcpy(&pData[88], &EG2PreAttack, 2);
1551    
1552            {
1553                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1554                uint8_t velocityresponse = VelocityResponseDepth;
1555                switch (VelocityResponseCurve) {
1556                    case curve_type_nonlinear:
1557                        break;
1558                    case curve_type_linear:
1559                        velocityresponse += 5;
1560                        break;
1561                    case curve_type_special:
1562                        velocityresponse += 10;
1563                        break;
1564                    case curve_type_unknown:
1565                    default:
1566                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1567                }
1568                memcpy(&pData[90], &velocityresponse, 1);
1569          }          }
1570          uint8_t releasevelocityresponse = _3ewa->ReadUint8();  
1571          if (releasevelocityresponse < 5) {          {
1572              ReleaseVelocityResponseCurve = curve_type_nonlinear;              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1573              ReleaseVelocityResponseDepth = releasevelocityresponse;              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1574          }              switch (ReleaseVelocityResponseCurve) {
1575          else if (releasevelocityresponse < 10) {                  case curve_type_nonlinear:
1576              ReleaseVelocityResponseCurve = curve_type_linear;                      break;
1577              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  case curve_type_linear:
1578          }                      releasevelocityresponse += 5;
1579          else if (releasevelocityresponse < 15) {                      break;
1580              ReleaseVelocityResponseCurve = curve_type_special;                  case curve_type_special:
1581              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;                      releasevelocityresponse += 10;
1582                        break;
1583                    case curve_type_unknown:
1584                    default:
1585                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1586                }
1587                memcpy(&pData[91], &releasevelocityresponse, 1);
1588          }          }
1589          else {  
1590              ReleaseVelocityResponseCurve = curve_type_unknown;          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1591              ReleaseVelocityResponseDepth = 0;  
1592            memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1593    
1594            // next 4 bytes unknown
1595    
1596            memcpy(&pData[98], &SampleStartOffset, 2);
1597    
1598            // next 2 bytes unknown
1599    
1600            {
1601                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1602                switch (DimensionBypass) {
1603                    case dim_bypass_ctrl_94:
1604                        pitchTrackDimensionBypass |= 0x10;
1605                        break;
1606                    case dim_bypass_ctrl_95:
1607                        pitchTrackDimensionBypass |= 0x20;
1608                        break;
1609                    case dim_bypass_ctrl_none:
1610                        //FIXME: should we set anything here?
1611                        break;
1612                    default:
1613                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1614                }
1615                memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1616          }          }
1617          VelocityResponseCurveScaling = _3ewa->ReadUint8();  
1618          AttenuationControllerThreshold = _3ewa->ReadInt8();          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1619          _3ewa->ReadInt32(); // unknown          memcpy(&pData[103], &pan, 1);
1620          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
1621          _3ewa->ReadInt16(); // unknown          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1622          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          memcpy(&pData[104], &selfmask, 1);
1623          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1624          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          // next byte unknown
1625          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
1626          else                                       DimensionBypass = dim_bypass_ctrl_none;          {
1627          uint8_t pan = _3ewa->ReadUint8();              uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1628          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1629          SelfMask = _3ewa->ReadInt8() & 0x01;              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1630          _3ewa->ReadInt8(); // unknown              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1631          uint8_t lfo3ctrl = _3ewa->ReadUint8();              memcpy(&pData[106], &lfo3ctrl, 1);
         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;  
1632          }          }
1633    
1634          // 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);
1635          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;          memcpy(&pData[107], &attenctl, 1);
1636    
1637            {
1638                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1639                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1640                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1641                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1642                memcpy(&pData[108], &lfo2ctrl, 1);
1643            }
1644    
1645            {
1646                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1647                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1648                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1649                if (VCFResonanceController != vcf_res_ctrl_none)
1650                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1651                memcpy(&pData[109], &lfo1ctrl, 1);
1652            }
1653    
1654            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1655                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1656            memcpy(&pData[110], &eg3depth, 1);
1657    
1658            // next 2 bytes unknown
1659    
1660            const uint8_t channeloffset = ChannelOffset * 4;
1661            memcpy(&pData[113], &channeloffset, 1);
1662    
1663            {
1664                uint8_t regoptions = 0;
1665                if (MSDecode)      regoptions |= 0x01; // bit 0
1666                if (SustainDefeat) regoptions |= 0x02; // bit 1
1667                memcpy(&pData[114], &regoptions, 1);
1668            }
1669    
1670            // next 2 bytes unknown
1671    
1672            memcpy(&pData[117], &VelocityUpperLimit, 1);
1673    
1674            // next 3 bytes unknown
1675    
1676            memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1677    
1678            // next 2 bytes unknown
1679    
1680            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1681            memcpy(&pData[124], &eg1hold, 1);
1682    
1683            const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1684                                      (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */
1685            memcpy(&pData[125], &vcfcutoff, 1);
1686    
1687            memcpy(&pData[126], &VCFCutoffController, 1);
1688    
1689            const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1690                                        (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1691            memcpy(&pData[127], &vcfvelscale, 1);
1692    
1693            // next byte unknown
1694    
1695            const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1696                                         (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1697            memcpy(&pData[129], &vcfresonance, 1);
1698    
1699            const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1700                                          (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1701            memcpy(&pData[130], &vcfbreakpoint, 1);
1702    
1703            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1704                                        VCFVelocityCurve * 5;
1705            memcpy(&pData[131], &vcfvelocity, 1);
1706    
1707            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1708            memcpy(&pData[132], &vcftype, 1);
1709        }
1710    
1711        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1712        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1713        {
1714            double* table;
1715            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1716          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1717              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1718          }          }
1719          else {          else {
1720              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1721                  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  
1722          }          }
1723            return table;
1724      }      }
1725    
1726      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1245  namespace gig { namespace { Line 1841  namespace gig { namespace {
1841          return decodedcontroller;          return decodedcontroller;
1842      }      }
1843    
1844        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1845            _lev_ctrl_t encodedcontroller;
1846            switch (DecodedController.type) {
1847                // special controller
1848                case leverage_ctrl_t::type_none:
1849                    encodedcontroller = _lev_ctrl_none;
1850                    break;
1851                case leverage_ctrl_t::type_velocity:
1852                    encodedcontroller = _lev_ctrl_velocity;
1853                    break;
1854                case leverage_ctrl_t::type_channelaftertouch:
1855                    encodedcontroller = _lev_ctrl_channelaftertouch;
1856                    break;
1857    
1858                // ordinary MIDI control change controller
1859                case leverage_ctrl_t::type_controlchange:
1860                    switch (DecodedController.controller_number) {
1861                        case 1:
1862                            encodedcontroller = _lev_ctrl_modwheel;
1863                            break;
1864                        case 2:
1865                            encodedcontroller = _lev_ctrl_breath;
1866                            break;
1867                        case 4:
1868                            encodedcontroller = _lev_ctrl_foot;
1869                            break;
1870                        case 12:
1871                            encodedcontroller = _lev_ctrl_effect1;
1872                            break;
1873                        case 13:
1874                            encodedcontroller = _lev_ctrl_effect2;
1875                            break;
1876                        case 16:
1877                            encodedcontroller = _lev_ctrl_genpurpose1;
1878                            break;
1879                        case 17:
1880                            encodedcontroller = _lev_ctrl_genpurpose2;
1881                            break;
1882                        case 18:
1883                            encodedcontroller = _lev_ctrl_genpurpose3;
1884                            break;
1885                        case 19:
1886                            encodedcontroller = _lev_ctrl_genpurpose4;
1887                            break;
1888                        case 5:
1889                            encodedcontroller = _lev_ctrl_portamentotime;
1890                            break;
1891                        case 64:
1892                            encodedcontroller = _lev_ctrl_sustainpedal;
1893                            break;
1894                        case 65:
1895                            encodedcontroller = _lev_ctrl_portamento;
1896                            break;
1897                        case 66:
1898                            encodedcontroller = _lev_ctrl_sostenutopedal;
1899                            break;
1900                        case 67:
1901                            encodedcontroller = _lev_ctrl_softpedal;
1902                            break;
1903                        case 80:
1904                            encodedcontroller = _lev_ctrl_genpurpose5;
1905                            break;
1906                        case 81:
1907                            encodedcontroller = _lev_ctrl_genpurpose6;
1908                            break;
1909                        case 82:
1910                            encodedcontroller = _lev_ctrl_genpurpose7;
1911                            break;
1912                        case 83:
1913                            encodedcontroller = _lev_ctrl_genpurpose8;
1914                            break;
1915                        case 91:
1916                            encodedcontroller = _lev_ctrl_effect1depth;
1917                            break;
1918                        case 92:
1919                            encodedcontroller = _lev_ctrl_effect2depth;
1920                            break;
1921                        case 93:
1922                            encodedcontroller = _lev_ctrl_effect3depth;
1923                            break;
1924                        case 94:
1925                            encodedcontroller = _lev_ctrl_effect4depth;
1926                            break;
1927                        case 95:
1928                            encodedcontroller = _lev_ctrl_effect5depth;
1929                            break;
1930                        default:
1931                            throw gig::Exception("leverage controller number is not supported by the gig format");
1932                    }
1933                default:
1934                    throw gig::Exception("Unknown leverage controller type.");
1935            }
1936            return encodedcontroller;
1937        }
1938    
1939      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
1940          Instances--;          Instances--;
1941          if (!Instances) {          if (!Instances) {
# Line 1258  namespace gig { namespace { Line 1949  namespace gig { namespace {
1949              delete pVelocityTables;              delete pVelocityTables;
1950              pVelocityTables = NULL;              pVelocityTables = NULL;
1951          }          }
1952            if (VelocityTable) delete[] VelocityTable;
1953      }      }
1954    
1955      /**      /**
# Line 1275  namespace gig { namespace { Line 1967  namespace gig { namespace {
1967          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1968      }      }
1969    
1970        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1971            return pVelocityReleaseTable[MIDIKeyVelocity];
1972        }
1973    
1974        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1975            return pVelocityCutoffTable[MIDIKeyVelocity];
1976        }
1977    
1978      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) {
1979    
1980          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1308  namespace gig { namespace { Line 2008  namespace gig { namespace {
2008          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,
2009                               127, 127 };                               127, 127 };
2010    
2011            // this is only used by the VCF velocity curve
2012            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2013                                 91, 127, 127, 127 };
2014    
2015          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2016                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2017                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2018    
2019          double* const table = new double[128];          double* const table = new double[128];
2020    
# Line 1362  namespace gig { namespace { Line 2066  namespace gig { namespace {
2066              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2067                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2068                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2069                    _3lnk->ReadUint8(); // probably the position of the dimension
2070                    _3lnk->ReadUint8(); // unknown
2071                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2072                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2073                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2074                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2075                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2076                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2077                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2078                  }                  }
2079                  else { // active dimension                  else { // active dimension
2080                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2081                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2082                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2083                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2084                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2085                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
2086                                                                                                    : split_type_normal;                                                             dimension == dimension_roundrobin ||
2087                      pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point                                                             dimension == dimension_random) ? split_type_bit
2088                                                                                              : split_type_normal;
2089                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2090                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2091                                                                                     : 0;                                                                                     : 0;
2092                      Dimensions++;                      Dimensions++;
2093    
2094                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2095                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2096                  }                  }
2097                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2098              }              }
2099                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2100    
2101              // 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,
2102              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2103                  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;  
                             }  
                         }  
                     }  
                 }  
             }  
2104    
2105              // 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();  
2106              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2107                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2108              else              else
# Line 1433  namespace gig { namespace { Line 2114  namespace gig { namespace {
2114                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2115              }              }
2116          }          }
2117          else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2118            // make sure there is at least one dimension region
2119            if (!DimensionRegions) {
2120                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2121                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2122                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2123                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2124                DimensionRegions = 1;
2125            }
2126        }
2127    
2128        /**
2129         * Apply Region settings and all its DimensionRegions to the respective
2130         * RIFF chunks. You have to call File::Save() to make changes persistent.
2131         *
2132         * Usually there is absolutely no need to call this method explicitly.
2133         * It will be called automatically when File::Save() was called.
2134         *
2135         * @throws gig::Exception if samples cannot be dereferenced
2136         */
2137        void Region::UpdateChunks() {
2138            // first update base class's chunks
2139            DLS::Region::UpdateChunks();
2140    
2141            // update dimension region's chunks
2142            for (int i = 0; i < DimensionRegions; i++) {
2143                pDimensionRegions[i]->UpdateChunks();
2144            }
2145    
2146            File* pFile = (File*) GetParent()->GetParent();
2147            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2148            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2149    
2150            // make sure '3lnk' chunk exists
2151            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2152            if (!_3lnk) {
2153                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2154                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2155            }
2156    
2157            // update dimension definitions in '3lnk' chunk
2158            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2159            for (int i = 0; i < iMaxDimensions; i++) {
2160                pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;
2161                pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2162                // next 2 bytes unknown
2163                pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2164                // next 3 bytes unknown
2165            }
2166    
2167            // update wave pool table in '3lnk' chunk
2168            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2169            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2170                int iWaveIndex = -1;
2171                if (i < DimensionRegions) {
2172                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2173                    File::SampleList::iterator iter = pFile->pSamples->begin();
2174                    File::SampleList::iterator end  = pFile->pSamples->end();
2175                    for (int index = 0; iter != end; ++iter, ++index) {
2176                        if (*iter == pDimensionRegions[i]->pSample) {
2177                            iWaveIndex = index;
2178                            break;
2179                        }
2180                    }
2181                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2182                }
2183                memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2184            }
2185      }      }
2186    
2187      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1452  namespace gig { namespace { Line 2200  namespace gig { namespace {
2200          }          }
2201      }      }
2202    
2203      Region::~Region() {      void Region::UpdateVelocityTable() {
2204          for (uint i = 0; i < Dimensions; i++) {          // get velocity dimension's index
2205              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          int veldim = -1;
2206            for (int i = 0 ; i < Dimensions ; i++) {
2207                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2208                    veldim = i;
2209                    break;
2210                }
2211          }          }
2212            if (veldim == -1) return;
2213    
2214            int step = 1;
2215            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2216            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2217            int end = step * pDimensionDefinitions[veldim].zones;
2218    
2219            // loop through all dimension regions for all dimensions except the velocity dimension
2220            int dim[8] = { 0 };
2221            for (int i = 0 ; i < DimensionRegions ; i++) {
2222    
2223                if (pDimensionRegions[i]->VelocityUpperLimit) {
2224                    // create the velocity table
2225                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2226                    if (!table) {
2227                        table = new uint8_t[128];
2228                        pDimensionRegions[i]->VelocityTable = table;
2229                    }
2230                    int tableidx = 0;
2231                    int velocityZone = 0;
2232                    for (int k = i ; k < end ; k += step) {
2233                        DimensionRegion *d = pDimensionRegions[k];
2234                        for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2235                        velocityZone++;
2236                    }
2237                } else {
2238                    if (pDimensionRegions[i]->VelocityTable) {
2239                        delete[] pDimensionRegions[i]->VelocityTable;
2240                        pDimensionRegions[i]->VelocityTable = 0;
2241                    }
2242                }
2243    
2244                int j;
2245                int shift = 0;
2246                for (j = 0 ; j < Dimensions ; j++) {
2247                    if (j == veldim) i += skipveldim; // skip velocity dimension
2248                    else {
2249                        dim[j]++;
2250                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2251                        else {
2252                            // skip unused dimension regions
2253                            dim[j] = 0;
2254                            i += ((1 << pDimensionDefinitions[j].bits) -
2255                                  pDimensionDefinitions[j].zones) << shift;
2256                        }
2257                    }
2258                    shift += pDimensionDefinitions[j].bits;
2259                }
2260                if (j == Dimensions) break;
2261            }
2262        }
2263    
2264        /** @brief Einstein would have dreamed of it - create a new dimension.
2265         *
2266         * Creates a new dimension with the dimension definition given by
2267         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2268         * There is a hard limit of dimensions and total amount of "bits" all
2269         * dimensions can have. This limit is dependant to what gig file format
2270         * version this file refers to. The gig v2 (and lower) format has a
2271         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2272         * format has a limit of 8.
2273         *
2274         * @param pDimDef - defintion of the new dimension
2275         * @throws gig::Exception if dimension of the same type exists already
2276         * @throws gig::Exception if amount of dimensions or total amount of
2277         *                        dimension bits limit is violated
2278         */
2279        void Region::AddDimension(dimension_def_t* pDimDef) {
2280            // check if max. amount of dimensions reached
2281            File* file = (File*) GetParent()->GetParent();
2282            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2283            if (Dimensions >= iMaxDimensions)
2284                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2285            // check if max. amount of dimension bits reached
2286            int iCurrentBits = 0;
2287            for (int i = 0; i < Dimensions; i++)
2288                iCurrentBits += pDimensionDefinitions[i].bits;
2289            if (iCurrentBits >= iMaxDimensions)
2290                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2291            const int iNewBits = iCurrentBits + pDimDef->bits;
2292            if (iNewBits > iMaxDimensions)
2293                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2294            // check if there's already a dimensions of the same type
2295            for (int i = 0; i < Dimensions; i++)
2296                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2297                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2298    
2299            // assign definition of new dimension
2300            pDimensionDefinitions[Dimensions] = *pDimDef;
2301    
2302            // create new dimension region(s) for this new dimension
2303            for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2304                //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2305                RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2306                pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2307                DimensionRegions++;
2308            }
2309    
2310            Dimensions++;
2311    
2312            // if this is a layer dimension, update 'Layers' attribute
2313            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2314    
2315            UpdateVelocityTable();
2316        }
2317    
2318        /** @brief Delete an existing dimension.
2319         *
2320         * Deletes the dimension given by \a pDimDef and deletes all respective
2321         * dimension regions, that is all dimension regions where the dimension's
2322         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2323         * for example this would delete all dimension regions for the case(s)
2324         * where the sustain pedal is pressed down.
2325         *
2326         * @param pDimDef - dimension to delete
2327         * @throws gig::Exception if given dimension cannot be found
2328         */
2329        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2330            // get dimension's index
2331            int iDimensionNr = -1;
2332            for (int i = 0; i < Dimensions; i++) {
2333                if (&pDimensionDefinitions[i] == pDimDef) {
2334                    iDimensionNr = i;
2335                    break;
2336                }
2337            }
2338            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2339    
2340            // get amount of bits below the dimension to delete
2341            int iLowerBits = 0;
2342            for (int i = 0; i < iDimensionNr; i++)
2343                iLowerBits += pDimensionDefinitions[i].bits;
2344    
2345            // get amount ot bits above the dimension to delete
2346            int iUpperBits = 0;
2347            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2348                iUpperBits += pDimensionDefinitions[i].bits;
2349    
2350            // delete dimension regions which belong to the given dimension
2351            // (that is where the dimension's bit > 0)
2352            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2353                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2354                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2355                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2356                                        iObsoleteBit << iLowerBits |
2357                                        iLowerBit;
2358                        delete pDimensionRegions[iToDelete];
2359                        pDimensionRegions[iToDelete] = NULL;
2360                        DimensionRegions--;
2361                    }
2362                }
2363            }
2364    
2365            // defrag pDimensionRegions array
2366            // (that is remove the NULL spaces within the pDimensionRegions array)
2367            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2368                if (!pDimensionRegions[iTo]) {
2369                    if (iFrom <= iTo) iFrom = iTo + 1;
2370                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2371                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2372                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2373                        pDimensionRegions[iFrom] = NULL;
2374                    }
2375                }
2376            }
2377    
2378            // 'remove' dimension definition
2379            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2380                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2381            }
2382            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2383            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2384            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2385    
2386            Dimensions--;
2387    
2388            // if this was a layer dimension, update 'Layers' attribute
2389            if (pDimDef->dimension == dimension_layer) Layers = 1;
2390        }
2391    
2392        Region::~Region() {
2393          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2394              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2395          }          }
# Line 1480  namespace gig { namespace { Line 2414  namespace gig { namespace {
2414       * @see             Dimensions       * @see             Dimensions
2415       */       */
2416      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2417          uint8_t bits[8] = { 0 };          uint8_t bits;
2418            int veldim = -1;
2419            int velbitpos;
2420            int bitpos = 0;
2421            int dimregidx = 0;
2422          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2423              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2424              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2425                  case split_type_normal:                  veldim = i;
2426                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
2427                      break;              } else {
2428                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2429                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2430                      break;                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2431                  case split_type_bit: // the value is already the sought dimension bit number                          break;
2432                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                      case split_type_bit: // the value is already the sought dimension bit number
2433                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2434                      break;                          bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2435              }                          break;
2436                    }
2437                    dimregidx |= bits << bitpos;
2438                }
2439                bitpos += pDimensionDefinitions[i].bits;
2440            }
2441            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2442            if (veldim != -1) {
2443                // (dimreg is now the dimension region for the lowest velocity)
2444                if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2445                    bits = dimreg->VelocityTable[DimValues[veldim]];
2446                else // normal split type
2447                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2448    
2449                dimregidx |= bits << velbitpos;
2450                dimreg = pDimensionRegions[dimregidx];
2451          }          }
2452          return GetDimensionRegionByBit(bits);          return dimreg;
2453      }      }
2454    
2455      /**      /**
# Line 1533  namespace gig { namespace { Line 2486  namespace gig { namespace {
2486          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2487      }      }
2488    
2489      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2490          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2491          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2492          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2493          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2494            Sample* sample = file->GetFirstSample(pProgress);
2495          while (sample) {          while (sample) {
2496              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2497                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
2498              sample = file->GetNextSample();              sample = file->GetNextSample();
2499          }          }
2500          return NULL;          return NULL;
# Line 1550  namespace gig { namespace { Line 2505  namespace gig { namespace {
2505  // *************** Instrument ***************  // *************** Instrument ***************
2506  // *  // *
2507    
2508      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) {
2509          // Initialization          // Initialization
2510          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2511    
2512          // Loading          // Loading
2513          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1569  namespace gig { namespace { Line 2523  namespace gig { namespace {
2523                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2524                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2525              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2526          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2527    
2528            if (!pRegions) pRegions = new RegionList;
2529          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2530          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2531          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2532          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              while (rgn) {
2533          RIFF::List* rgn = lrgn->GetFirstSubList();                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2534          unsigned int iRegion = 0;                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2535          while (rgn) {                      pRegions->push_back(new Region(this, rgn));
2536              if (rgn->GetListType() == LIST_TYPE_RGN) {                  }
2537                  pRegions[iRegion] = new Region(this, rgn);                  rgn = lrgn->GetNextSubList();
                 iRegion++;  
             }  
             rgn = lrgn->GetNextSubList();  
         }  
   
         // 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];  
2538              }              }
2539                // Creating Region Key Table for fast lookup
2540                UpdateRegionKeyTable();
2541          }          }
2542    
2543            __notify_progress(pProgress, 1.0f); // notify done
2544      }      }
2545    
2546      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2547          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2548              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2549                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2550                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2551                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2552                    RegionKeyTable[iKey] = pRegion;
2553              }              }
2554          }          }
2555          if (pRegions) delete[] pRegions;      }
2556    
2557        Instrument::~Instrument() {
2558        }
2559    
2560        /**
2561         * Apply Instrument with all its Regions to the respective RIFF chunks.
2562         * You have to call File::Save() to make changes persistent.
2563         *
2564         * Usually there is absolutely no need to call this method explicitly.
2565         * It will be called automatically when File::Save() was called.
2566         *
2567         * @throws gig::Exception if samples cannot be dereferenced
2568         */
2569        void Instrument::UpdateChunks() {
2570            // first update base classes' chunks
2571            DLS::Instrument::UpdateChunks();
2572    
2573            // update Regions' chunks
2574            {
2575                RegionList::iterator iter = pRegions->begin();
2576                RegionList::iterator end  = pRegions->end();
2577                for (; iter != end; ++iter)
2578                    (*iter)->UpdateChunks();
2579            }
2580    
2581            // make sure 'lart' RIFF list chunk exists
2582            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2583            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2584            // make sure '3ewg' RIFF chunk exists
2585            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2586            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2587            // update '3ewg' RIFF chunk
2588            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2589            memcpy(&pData[0], &EffectSend, 2);
2590            memcpy(&pData[2], &Attenuation, 4);
2591            memcpy(&pData[6], &FineTune, 2);
2592            memcpy(&pData[8], &PitchbendRange, 2);
2593            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2594                                        DimensionKeyRange.low << 1;
2595            memcpy(&pData[10], &dimkeystart, 1);
2596            memcpy(&pData[11], &DimensionKeyRange.high, 1);
2597      }      }
2598    
2599      /**      /**
# Line 1612  namespace gig { namespace { Line 2604  namespace gig { namespace {
2604       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2605       */       */
2606      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2607          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2608          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2609    
2610          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2611              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2612                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1629  namespace gig { namespace { Line 2622  namespace gig { namespace {
2622       * @see      GetNextRegion()       * @see      GetNextRegion()
2623       */       */
2624      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2625          if (!Regions) return NULL;          if (!pRegions) return NULL;
2626          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2627          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2628      }      }
2629    
2630      /**      /**
# Line 1643  namespace gig { namespace { Line 2636  namespace gig { namespace {
2636       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2637       */       */
2638      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2639          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2640          return pRegions[RegionIndex++];          RegionsIterator++;
2641            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2642        }
2643    
2644        Region* Instrument::AddRegion() {
2645            // create new Region object (and its RIFF chunks)
2646            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2647            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2648            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2649            Region* pNewRegion = new Region(this, rgn);
2650            pRegions->push_back(pNewRegion);
2651            Regions = pRegions->size();
2652            // update Region key table for fast lookup
2653            UpdateRegionKeyTable();
2654            // done
2655            return pNewRegion;
2656        }
2657    
2658        void Instrument::DeleteRegion(Region* pRegion) {
2659            if (!pRegions) return;
2660            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2661            // update Region key table for fast lookup
2662            UpdateRegionKeyTable();
2663      }      }
2664    
2665    
# Line 1652  namespace gig { namespace { Line 2667  namespace gig { namespace {
2667  // *************** File ***************  // *************** File ***************
2668  // *  // *
2669    
2670      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File() : DLS::File() {
         pSamples     = NULL;  
         pInstruments = NULL;  
2671      }      }
2672    
2673      File::~File() {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
         // free samples  
         if (pSamples) {  
             SamplesIterator = pSamples->begin();  
             while (SamplesIterator != pSamples->end() ) {  
                 delete (*SamplesIterator);  
                 SamplesIterator++;  
             }  
             pSamples->clear();  
             delete pSamples;  
   
         }  
         // free instruments  
         if (pInstruments) {  
             InstrumentsIterator = pInstruments->begin();  
             while (InstrumentsIterator != pInstruments->end() ) {  
                 delete (*InstrumentsIterator);  
                 InstrumentsIterator++;  
             }  
             pInstruments->clear();  
             delete pInstruments;  
         }  
2674      }      }
2675    
2676      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
2677          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
2678          if (!pSamples) return NULL;          if (!pSamples) return NULL;
2679          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
2680          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1694  namespace gig { namespace { Line 2686  namespace gig { namespace {
2686          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2687      }      }
2688    
2689        /** @brief Add a new sample.
2690         *
2691         * This will create a new Sample object for the gig file. You have to
2692         * call Save() to make this persistent to the file.
2693         *
2694         * @returns pointer to new Sample object
2695         */
2696        Sample* File::AddSample() {
2697           if (!pSamples) LoadSamples();
2698           __ensureMandatoryChunksExist();
2699           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2700           // create new Sample object and its respective 'wave' list chunk
2701           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2702           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2703           pSamples->push_back(pSample);
2704           return pSample;
2705        }
2706    
2707        /** @brief Delete a sample.
2708         *
2709         * This will delete the given Sample object from the gig file. You have
2710         * to call Save() to make this persistent to the file.
2711         *
2712         * @param pSample - sample to delete
2713         * @throws gig::Exception if given sample could not be found
2714         */
2715        void File::DeleteSample(Sample* pSample) {
2716            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2717            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2718            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2719            pSamples->erase(iter);
2720            delete pSample;
2721        }
2722    
2723      void File::LoadSamples() {      void File::LoadSamples() {
2724          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          LoadSamples(NULL);
2725          if (wvpl) {      }
2726              unsigned long wvplFileOffset = wvpl->GetFilePos();  
2727              RIFF::List* wave = wvpl->GetFirstSubList();      void File::LoadSamples(progress_t* pProgress) {
2728              while (wave) {          if (!pSamples) pSamples = new SampleList;
2729                  if (wave->GetListType() == LIST_TYPE_WAVE) {  
2730                      if (!pSamples) pSamples = new SampleList;          RIFF::File* file = pRIFF;
2731                      unsigned long waveFileOffset = wave->GetFilePos();  
2732                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));          // just for progress calculation
2733            int iSampleIndex  = 0;
2734            int iTotalSamples = WavePoolCount;
2735    
2736            // check if samples should be loaded from extension files
2737            int lastFileNo = 0;
2738            for (int i = 0 ; i < WavePoolCount ; i++) {
2739                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2740            }
2741            String name(pRIFF->GetFileName());
2742            int nameLen = name.length();
2743            char suffix[6];
2744            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2745    
2746            for (int fileNo = 0 ; ; ) {
2747                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2748                if (wvpl) {
2749                    unsigned long wvplFileOffset = wvpl->GetFilePos();
2750                    RIFF::List* wave = wvpl->GetFirstSubList();
2751                    while (wave) {
2752                        if (wave->GetListType() == LIST_TYPE_WAVE) {
2753                            // notify current progress
2754                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2755                            __notify_progress(pProgress, subprogress);
2756    
2757                            unsigned long waveFileOffset = wave->GetFilePos();
2758                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2759    
2760                            iSampleIndex++;
2761                        }
2762                        wave = wvpl->GetNextSubList();
2763                  }                  }
2764                  wave = wvpl->GetNextSubList();  
2765              }                  if (fileNo == lastFileNo) break;
2766    
2767                    // open extension file (*.gx01, *.gx02, ...)
2768                    fileNo++;
2769                    sprintf(suffix, ".gx%02d", fileNo);
2770                    name.replace(nameLen, 5, suffix);
2771                    file = new RIFF::File(name);
2772                    ExtensionFiles.push_back(file);
2773                } else break;
2774          }          }
2775          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2776            __notify_progress(pProgress, 1.0); // notify done
2777      }      }
2778    
2779      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
2780          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2781          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2782          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2783          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2784      }      }
2785    
2786      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2787          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2788          InstrumentsIterator++;          InstrumentsIterator++;
2789          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2790      }      }
2791    
2792      /**      /**
2793       * Returns the instrument with the given index.       * Returns the instrument with the given index.
2794       *       *
2795         * @param index     - number of the sought instrument (0..n)
2796         * @param pProgress - optional: callback function for progress notification
2797       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
2798       */       */
2799      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
2800          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
2801                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
2802    
2803                // sample loading subtask
2804                progress_t subprogress;
2805                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
2806                __notify_progress(&subprogress, 0.0f);
2807                GetFirstSample(&subprogress); // now force all samples to be loaded
2808                __notify_progress(&subprogress, 1.0f);
2809    
2810                // instrument loading subtask
2811                if (pProgress && pProgress->callback) {
2812                    subprogress.__range_min = subprogress.__range_max;
2813                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
2814                }
2815                __notify_progress(&subprogress, 0.0f);
2816                LoadInstruments(&subprogress);
2817                __notify_progress(&subprogress, 1.0f);
2818            }
2819          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2820          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2821          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2822              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2823              InstrumentsIterator++;              InstrumentsIterator++;
2824          }          }
2825          return NULL;          return NULL;
2826      }      }
2827    
2828        /** @brief Add a new instrument definition.
2829         *
2830         * This will create a new Instrument object for the gig file. You have
2831         * to call Save() to make this persistent to the file.
2832         *
2833         * @returns pointer to new Instrument object
2834         */
2835        Instrument* File::AddInstrument() {
2836           if (!pInstruments) LoadInstruments();
2837           __ensureMandatoryChunksExist();
2838           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2839           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2840           Instrument* pInstrument = new Instrument(this, lstInstr);
2841           pInstruments->push_back(pInstrument);
2842           return pInstrument;
2843        }
2844    
2845        /** @brief Delete an instrument.
2846         *
2847         * This will delete the given Instrument object from the gig file. You
2848         * have to call Save() to make this persistent to the file.
2849         *
2850         * @param pInstrument - instrument to delete
2851         * @throws gig::Excption if given instrument could not be found
2852         */
2853        void File::DeleteInstrument(Instrument* pInstrument) {
2854            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2855            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2856            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2857            pInstruments->erase(iter);
2858            delete pInstrument;
2859        }
2860    
2861      void File::LoadInstruments() {      void File::LoadInstruments() {
2862            LoadInstruments(NULL);
2863        }
2864    
2865        void File::LoadInstruments(progress_t* pProgress) {
2866            if (!pInstruments) pInstruments = new InstrumentList;
2867          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2868          if (lstInstruments) {          if (lstInstruments) {
2869                int iInstrumentIndex = 0;
2870              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
2871              while (lstInstr) {              while (lstInstr) {
2872                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
2873                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
2874                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
2875                        __notify_progress(pProgress, localProgress);
2876    
2877                        // divide local progress into subprogress for loading current Instrument
2878                        progress_t subprogress;
2879                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2880    
2881                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2882    
2883                        iInstrumentIndex++;
2884                  }                  }
2885                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
2886              }              }
2887                __notify_progress(pProgress, 1.0); // notify done
2888          }          }
         else throw gig::Exception("Mandatory <lins> list chunk not found.");  
2889      }      }
2890    
2891    
# Line 1767  namespace gig { namespace { Line 2900  namespace gig { namespace {
2900          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
2901      }      }
2902    
2903    
2904    // *************** functions ***************
2905    // *
2906    
2907        /**
2908         * Returns the name of this C++ library. This is usually "libgig" of
2909         * course. This call is equivalent to RIFF::libraryName() and
2910         * DLS::libraryName().
2911         */
2912        String libraryName() {
2913            return PACKAGE;
2914        }
2915    
2916        /**
2917         * Returns version of this C++ library. This call is equivalent to
2918         * RIFF::libraryVersion() and DLS::libraryVersion().
2919         */
2920        String libraryVersion() {
2921            return VERSION;
2922        }
2923    
2924  } // namespace gig  } // namespace gig

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

  ViewVC Help
Powered by ViewVC