/[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 516 by schoenebeck, Sat May 7 21:24:04 2005 UTC revision 834 by persson, Mon Feb 6 17:58:21 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    /// 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 {  namespace gig {
53    
54    // *************** dimension_def_t ***************
55    // *
56    
57        dimension_def_t& dimension_def_t::operator=(const dimension_def_t& arg) {
58            dimension  = arg.dimension;
59            bits       = arg.bits;
60            zones      = arg.zones;
61            split_type = arg.split_type;
62            ranges     = arg.ranges;
63            zone_size  = arg.zone_size;
64            if (ranges) {
65                ranges = new range_t[zones];
66                for (int i = 0; i < zones; i++)
67                    ranges[i] = arg.ranges[i];
68            }
69            return *this;
70        }
71    
72    
73    
74  // *************** progress_t ***************  // *************** progress_t ***************
75  // *  // *
76    
# Line 59  namespace gig { Line 103  namespace gig {
103      }      }
104    
105    
106  // *************** Internal functions for sample decopmression ***************  // *************** Internal functions for sample decompression ***************
107  // *  // *
108    
109  namespace {  namespace {
# Line 132  namespace { Line 176  namespace {
176      {      {
177          // Note: The 24 bits are truncated to 16 bits for now.          // Note: The 24 bits are truncated to 16 bits for now.
178    
179          // Note: The calculation of the initial value of y is strange          int y, dy, ddy, dddy;
         // and not 100% correct. What should the first two parameters  
         // really be used for? Why are they two? The correct value for  
         // y seems to lie somewhere between the values of the first  
         // two parameters.  
         //  
         // Strange thing #2: The formula in SKIP_ONE gives values for  
         // y that are twice as high as they should be. That's why  
         // COPY_ONE shifts an extra step, and also why y is  
         // initialized with a sum instead of a mean value.  
   
         int y, dy, ddy;  
   
180          const int shift = 8 - truncatedBits;          const int shift = 8 - truncatedBits;
         const int shift1 = shift + 1;  
181    
182  #define GET_PARAMS(params)                              \  #define GET_PARAMS(params)                      \
183          y = (get24(params) + get24((params) + 3));      \          y    = get24(params);                   \
184          dy  = get24((params) + 6);                      \          dy   = y - get24((params) + 3);         \
185          ddy = get24((params) + 9)          ddy  = get24((params) + 6);             \
186            dddy = get24((params) + 9)
187    
188  #define SKIP_ONE(x)                             \  #define SKIP_ONE(x)                             \
189          ddy -= (x);                             \          dddy -= (x);                            \
190          dy -= ddy;                              \          ddy  -= dddy;                           \
191          y -= dy          dy   =  -dy - ddy;                      \
192            y    += dy
193    
194  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
195          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
196          *pDst = y >> shift1;                    \          *pDst = y >> shift;                     \
197          pDst += dstStep          pDst += dstStep
198    
199          switch (compressionmode) {          switch (compressionmode) {
# Line 243  namespace { Line 276  namespace {
276      unsigned int Sample::Instances = 0;      unsigned int Sample::Instances = 0;
277      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
278    
279      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
280         *
281         * Load an existing sample or create a new one. A 'wave' list chunk must
282         * be given to this constructor. In case the given 'wave' list chunk
283         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
284         * format and sample data will be loaded from there, otherwise default
285         * values will be used and those chunks will be created when
286         * File::Save() will be called later on.
287         *
288         * @param pFile          - pointer to gig::File where this sample is
289         *                         located (or will be located)
290         * @param waveList       - pointer to 'wave' list chunk which is (or
291         *                         will be) associated with this sample
292         * @param WavePoolOffset - offset of this sample data from wave pool
293         *                         ('wvpl') list chunk
294         * @param fileNo         - number of an extension file where this sample
295         *                         is located, 0 otherwise
296         */
297        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
298          Instances++;          Instances++;
299            FileNo = fileNo;
300    
301          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
302          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
303          SampleGroup = _3gix->ReadInt16();              SampleGroup = pCk3gix->ReadInt16();
304            } else { // '3gix' chunk missing
305          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              // use default value(s)
306          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              SampleGroup = 0;
307          Manufacturer      = smpl->ReadInt32();          }
308          Product           = smpl->ReadInt32();  
309          SamplePeriod      = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
310          MIDIUnityNote     = smpl->ReadInt32();          if (pCkSmpl) {
311          FineTune          = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
312          smpl->Read(&SMPTEFormat, 1, 4);              Product       = pCkSmpl->ReadInt32();
313          SMPTEOffset       = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
314          Loops             = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
315          smpl->ReadInt32(); // manufByt              FineTune      = pCkSmpl->ReadInt32();
316          LoopID            = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
317          smpl->Read(&LoopType, 1, 4);              SMPTEOffset   = pCkSmpl->ReadInt32();
318          LoopStart         = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
319          LoopEnd           = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
320          LoopFraction      = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
321          LoopPlayCount     = smpl->ReadInt32();              pCkSmpl->Read(&LoopType, 1, 4);
322                LoopStart     = pCkSmpl->ReadInt32();
323                LoopEnd       = pCkSmpl->ReadInt32();
324                LoopFraction  = pCkSmpl->ReadInt32();
325                LoopPlayCount = pCkSmpl->ReadInt32();
326            } else { // 'smpl' chunk missing
327                // use default values
328                Manufacturer  = 0;
329                Product       = 0;
330                SamplePeriod  = 1 / SamplesPerSecond;
331                MIDIUnityNote = 64;
332                FineTune      = 0;
333                SMPTEOffset   = 0;
334                Loops         = 0;
335                LoopID        = 0;
336                LoopStart     = 0;
337                LoopEnd       = 0;
338                LoopFraction  = 0;
339                LoopPlayCount = 0;
340            }
341    
342          FrameTable                 = NULL;          FrameTable                 = NULL;
343          SamplePos                  = 0;          SamplePos                  = 0;
# Line 300  namespace { Line 371  namespace {
371          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart;
372      }      }
373    
374        /**
375         * Apply sample and its settings to the respective RIFF chunks. You have
376         * to call File::Save() to make changes persistent.
377         *
378         * Usually there is absolutely no need to call this method explicitly.
379         * It will be called automatically when File::Save() was called.
380         *
381         * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
382         *                        was provided yet
383         * @throws gig::Exception if there is any invalid sample setting
384         */
385        void Sample::UpdateChunks() {
386            // first update base class's chunks
387            DLS::Sample::UpdateChunks();
388    
389            // make sure 'smpl' chunk exists
390            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
391            if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
392            // update 'smpl' chunk
393            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
394            SamplePeriod = 1 / SamplesPerSecond;
395            memcpy(&pData[0], &Manufacturer, 4);
396            memcpy(&pData[4], &Product, 4);
397            memcpy(&pData[8], &SamplePeriod, 4);
398            memcpy(&pData[12], &MIDIUnityNote, 4);
399            memcpy(&pData[16], &FineTune, 4);
400            memcpy(&pData[20], &SMPTEFormat, 4);
401            memcpy(&pData[24], &SMPTEOffset, 4);
402            memcpy(&pData[28], &Loops, 4);
403    
404            // we skip 'manufByt' for now (4 bytes)
405    
406            memcpy(&pData[36], &LoopID, 4);
407            memcpy(&pData[40], &LoopType, 4);
408            memcpy(&pData[44], &LoopStart, 4);
409            memcpy(&pData[48], &LoopEnd, 4);
410            memcpy(&pData[52], &LoopFraction, 4);
411            memcpy(&pData[56], &LoopPlayCount, 4);
412    
413            // make sure '3gix' chunk exists
414            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
415            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
416            // update '3gix' chunk
417            pData = (uint8_t*) pCk3gix->LoadChunkData();
418            memcpy(&pData[0], &SampleGroup, 2);
419        }
420    
421      /// 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).
422      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
423          //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 500  namespace { Line 618  namespace {
618          RAMCache.Size   = 0;          RAMCache.Size   = 0;
619      }      }
620    
621        /** @brief Resize sample.
622         *
623         * Resizes the sample's wave form data, that is the actual size of
624         * sample wave data possible to be written for this sample. This call
625         * will return immediately and just schedule the resize operation. You
626         * should call File::Save() to actually perform the resize operation(s)
627         * "physically" to the file. As this can take a while on large files, it
628         * is recommended to call Resize() first on all samples which have to be
629         * resized and finally to call File::Save() to perform all those resize
630         * operations in one rush.
631         *
632         * The actual size (in bytes) is dependant to the current FrameSize
633         * value. You may want to set FrameSize before calling Resize().
634         *
635         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
636         * enlarged samples before calling File::Save() as this might exceed the
637         * current sample's boundary!
638         *
639         * Also note: only WAVE_FORMAT_PCM is currently supported, that is
640         * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
641         * other formats will fail!
642         *
643         * @param iNewSize - new sample wave data size in sample points (must be
644         *                   greater than zero)
645         * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM
646         *                         or if \a iNewSize is less than 1
647         * @throws gig::Exception if existing sample is compressed
648         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
649         *      DLS::Sample::FormatTag, File::Save()
650         */
651        void Sample::Resize(int iNewSize) {
652            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
653            DLS::Sample::Resize(iNewSize);
654        }
655    
656      /**      /**
657       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
658       * 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 943  namespace { Line 1096  namespace {
1096          }          }
1097      }      }
1098    
1099        /** @brief Write sample wave data.
1100         *
1101         * Writes \a SampleCount number of sample points from the buffer pointed
1102         * by \a pBuffer and increments the position within the sample. Use this
1103         * method to directly write the sample data to disk, i.e. if you don't
1104         * want or cannot load the whole sample data into RAM.
1105         *
1106         * You have to Resize() the sample to the desired size and call
1107         * File::Save() <b>before</b> using Write().
1108         *
1109         * Note: there is currently no support for writing compressed samples.
1110         *
1111         * @param pBuffer     - source buffer
1112         * @param SampleCount - number of sample points to write
1113         * @throws DLS::Exception if current sample size is too small
1114         * @throws gig::Exception if sample is compressed
1115         * @see DLS::LoadSampleData()
1116         */
1117        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1118            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1119            return DLS::Sample::Write(pBuffer, SampleCount);
1120        }
1121    
1122      /**      /**
1123       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1124       * 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 1007  namespace { Line 1183  namespace {
1183      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1184          Instances++;          Instances++;
1185    
1186            pSample = NULL;
1187    
1188          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1189          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1190    
1191          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1192          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1193          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1194          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1195          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1196          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1197          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1198          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1199          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1200          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1201          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1202          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1203          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1204          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1205          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1206          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1207          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1208          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1209          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1210          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1211          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1212          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1213          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1214          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1215          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1216          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1217          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1218          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1219          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1220          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1221          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1222          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1223          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1224          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1225          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1226          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1227          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1228          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1229          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1230          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1231          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1232          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1233          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1234          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1235          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1236          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1237          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1238          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1239          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1240          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1241          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1242          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1243              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1244              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1245          }                  VelocityResponseDepth = velocityresponse;
1246          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1247              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1248              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1249          }              } else if (velocityresponse < 15) {
1250          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1251              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1252              VelocityResponseDepth = velocityresponse - 10;              } else {
1253                    VelocityResponseCurve = curve_type_unknown;
1254                    VelocityResponseDepth = 0;
1255                }
1256                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1257                if (releasevelocityresponse < 5) {
1258                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1259                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1260                } else if (releasevelocityresponse < 10) {
1261                    ReleaseVelocityResponseCurve = curve_type_linear;
1262                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1263                } else if (releasevelocityresponse < 15) {
1264                    ReleaseVelocityResponseCurve = curve_type_special;
1265                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1266                } else {
1267                    ReleaseVelocityResponseCurve = curve_type_unknown;
1268                    ReleaseVelocityResponseDepth = 0;
1269                }
1270                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1271                AttenuationControllerThreshold = _3ewa->ReadInt8();
1272                _3ewa->ReadInt32(); // unknown
1273                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1274                _3ewa->ReadInt16(); // unknown
1275                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1276                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1277                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1278                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1279                else                                       DimensionBypass = dim_bypass_ctrl_none;
1280                uint8_t pan = _3ewa->ReadUint8();
1281                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1282                SelfMask = _3ewa->ReadInt8() & 0x01;
1283                _3ewa->ReadInt8(); // unknown
1284                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1285                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1286                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1287                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1288                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1289                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1290                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1291                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1292                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1293                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1294                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1295                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1296                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1297                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1298                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1299                                                            : vcf_res_ctrl_none;
1300                uint16_t eg3depth = _3ewa->ReadUint16();
1301                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1302                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1303                _3ewa->ReadInt16(); // unknown
1304                ChannelOffset = _3ewa->ReadUint8() / 4;
1305                uint8_t regoptions = _3ewa->ReadUint8();
1306                MSDecode           = regoptions & 0x01; // bit 0
1307                SustainDefeat      = regoptions & 0x02; // bit 1
1308                _3ewa->ReadInt16(); // unknown
1309                VelocityUpperLimit = _3ewa->ReadInt8();
1310                _3ewa->ReadInt8(); // unknown
1311                _3ewa->ReadInt16(); // unknown
1312                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1313                _3ewa->ReadInt8(); // unknown
1314                _3ewa->ReadInt8(); // unknown
1315                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1316                uint8_t vcfcutoff = _3ewa->ReadUint8();
1317                VCFEnabled = vcfcutoff & 0x80; // bit 7
1318                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1319                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1320                uint8_t vcfvelscale = _3ewa->ReadUint8();
1321                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1322                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1323                _3ewa->ReadInt8(); // unknown
1324                uint8_t vcfresonance = _3ewa->ReadUint8();
1325                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1326                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1327                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1328                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1329                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1330                uint8_t vcfvelocity = _3ewa->ReadUint8();
1331                VCFVelocityDynamicRange = vcfvelocity % 5;
1332                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1333                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1334                if (VCFType == vcf_type_lowpass) {
1335                    if (lfo3ctrl & 0x40) // bit 6
1336                        VCFType = vcf_type_lowpassturbo;
1337                }
1338            } else { // '3ewa' chunk does not exist yet
1339                // use default values
1340                LFO3Frequency                   = 1.0;
1341                EG3Attack                       = 0.0;
1342                LFO1InternalDepth               = 0;
1343                LFO3InternalDepth               = 0;
1344                LFO1ControlDepth                = 0;
1345                LFO3ControlDepth                = 0;
1346                EG1Attack                       = 0.0;
1347                EG1Decay1                       = 0.0;
1348                EG1Sustain                      = 0;
1349                EG1Release                      = 0.0;
1350                EG1Controller.type              = eg1_ctrl_t::type_none;
1351                EG1Controller.controller_number = 0;
1352                EG1ControllerInvert             = false;
1353                EG1ControllerAttackInfluence    = 0;
1354                EG1ControllerDecayInfluence     = 0;
1355                EG1ControllerReleaseInfluence   = 0;
1356                EG2Controller.type              = eg2_ctrl_t::type_none;
1357                EG2Controller.controller_number = 0;
1358                EG2ControllerInvert             = false;
1359                EG2ControllerAttackInfluence    = 0;
1360                EG2ControllerDecayInfluence     = 0;
1361                EG2ControllerReleaseInfluence   = 0;
1362                LFO1Frequency                   = 1.0;
1363                EG2Attack                       = 0.0;
1364                EG2Decay1                       = 0.0;
1365                EG2Sustain                      = 0;
1366                EG2Release                      = 0.0;
1367                LFO2ControlDepth                = 0;
1368                LFO2Frequency                   = 1.0;
1369                LFO2InternalDepth               = 0;
1370                EG1Decay2                       = 0.0;
1371                EG1InfiniteSustain              = false;
1372                EG1PreAttack                    = 1000;
1373                EG2Decay2                       = 0.0;
1374                EG2InfiniteSustain              = false;
1375                EG2PreAttack                    = 1000;
1376                VelocityResponseCurve           = curve_type_nonlinear;
1377                VelocityResponseDepth           = 3;
1378                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1379                ReleaseVelocityResponseDepth    = 3;
1380                VelocityResponseCurveScaling    = 32;
1381                AttenuationControllerThreshold  = 0;
1382                SampleStartOffset               = 0;
1383                PitchTrack                      = true;
1384                DimensionBypass                 = dim_bypass_ctrl_none;
1385                Pan                             = 0;
1386                SelfMask                        = true;
1387                LFO3Controller                  = lfo3_ctrl_modwheel;
1388                LFO3Sync                        = false;
1389                InvertAttenuationController     = false;
1390                AttenuationController.type      = attenuation_ctrl_t::type_none;
1391                AttenuationController.controller_number = 0;
1392                LFO2Controller                  = lfo2_ctrl_internal;
1393                LFO2FlipPhase                   = false;
1394                LFO2Sync                        = false;
1395                LFO1Controller                  = lfo1_ctrl_internal;
1396                LFO1FlipPhase                   = false;
1397                LFO1Sync                        = false;
1398                VCFResonanceController          = vcf_res_ctrl_none;
1399                EG3Depth                        = 0;
1400                ChannelOffset                   = 0;
1401                MSDecode                        = false;
1402                SustainDefeat                   = false;
1403                VelocityUpperLimit              = 0;
1404                ReleaseTriggerDecay             = 0;
1405                EG1Hold                         = false;
1406                VCFEnabled                      = false;
1407                VCFCutoff                       = 0;
1408                VCFCutoffController             = vcf_cutoff_ctrl_none;
1409                VCFCutoffControllerInvert       = false;
1410                VCFVelocityScale                = 0;
1411                VCFResonance                    = 0;
1412                VCFResonanceDynamic             = false;
1413                VCFKeyboardTracking             = false;
1414                VCFKeyboardTrackingBreakpoint   = 0;
1415                VCFVelocityDynamicRange         = 0x04;
1416                VCFVelocityCurve                = curve_type_linear;
1417                VCFType                         = vcf_type_lowpass;
1418            }
1419    
1420            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1421                                                         VelocityResponseDepth,
1422                                                         VelocityResponseCurveScaling);
1423    
1424            curve_type_t curveType = ReleaseVelocityResponseCurve;
1425            uint8_t depth = ReleaseVelocityResponseDepth;
1426    
1427            // this models a strange behaviour or bug in GSt: two of the
1428            // velocity response curves for release time are not used even
1429            // if specified, instead another curve is chosen.
1430            if ((curveType == curve_type_nonlinear && depth == 0) ||
1431                (curveType == curve_type_special   && depth == 4)) {
1432                curveType = curve_type_nonlinear;
1433                depth = 3;
1434            }
1435            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1436    
1437            curveType = VCFVelocityCurve;
1438            depth = VCFVelocityDynamicRange;
1439    
1440            // even stranger GSt: two of the velocity response curves for
1441            // filter cutoff are not used, instead another special curve
1442            // is chosen. This curve is not used anywhere else.
1443            if ((curveType == curve_type_nonlinear && depth == 0) ||
1444                (curveType == curve_type_special   && depth == 4)) {
1445                curveType = curve_type_special;
1446                depth = 5;
1447          }          }
1448          else {          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1449              VelocityResponseCurve = curve_type_unknown;                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1450              VelocityResponseDepth = 0;  
1451            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1452        }
1453    
1454        /**
1455         * Apply dimension region settings to the respective RIFF chunks. You
1456         * have to call File::Save() to make changes persistent.
1457         *
1458         * Usually there is absolutely no need to call this method explicitly.
1459         * It will be called automatically when File::Save() was called.
1460         */
1461        void DimensionRegion::UpdateChunks() {
1462            // first update base class's chunk
1463            DLS::Sampler::UpdateChunks();
1464    
1465            // make sure '3ewa' chunk exists
1466            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1467            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1468            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1469    
1470            // update '3ewa' chunk with DimensionRegion's current settings
1471    
1472            const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1473            memcpy(&pData[0], &unknown, 4);
1474    
1475            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1476            memcpy(&pData[4], &lfo3freq, 4);
1477    
1478            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1479            memcpy(&pData[4], &eg3attack, 4);
1480    
1481            // next 2 bytes unknown
1482    
1483            memcpy(&pData[10], &LFO1InternalDepth, 2);
1484    
1485            // next 2 bytes unknown
1486    
1487            memcpy(&pData[14], &LFO3InternalDepth, 2);
1488    
1489            // next 2 bytes unknown
1490    
1491            memcpy(&pData[18], &LFO1ControlDepth, 2);
1492    
1493            // next 2 bytes unknown
1494    
1495            memcpy(&pData[22], &LFO3ControlDepth, 2);
1496    
1497            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1498            memcpy(&pData[24], &eg1attack, 4);
1499    
1500            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1501            memcpy(&pData[28], &eg1decay1, 4);
1502    
1503            // next 2 bytes unknown
1504    
1505            memcpy(&pData[34], &EG1Sustain, 2);
1506    
1507            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1508            memcpy(&pData[36], &eg1release, 4);
1509    
1510            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1511            memcpy(&pData[40], &eg1ctl, 1);
1512    
1513            const uint8_t eg1ctrloptions =
1514                (EG1ControllerInvert) ? 0x01 : 0x00 |
1515                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1516                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1517                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1518            memcpy(&pData[41], &eg1ctrloptions, 1);
1519    
1520            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1521            memcpy(&pData[42], &eg2ctl, 1);
1522    
1523            const uint8_t eg2ctrloptions =
1524                (EG2ControllerInvert) ? 0x01 : 0x00 |
1525                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1526                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1527                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1528            memcpy(&pData[43], &eg2ctrloptions, 1);
1529    
1530            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1531            memcpy(&pData[44], &lfo1freq, 4);
1532    
1533            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1534            memcpy(&pData[48], &eg2attack, 4);
1535    
1536            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1537            memcpy(&pData[52], &eg2decay1, 4);
1538    
1539            // next 2 bytes unknown
1540    
1541            memcpy(&pData[58], &EG2Sustain, 2);
1542    
1543            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1544            memcpy(&pData[60], &eg2release, 4);
1545    
1546            // next 2 bytes unknown
1547    
1548            memcpy(&pData[66], &LFO2ControlDepth, 2);
1549    
1550            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1551            memcpy(&pData[68], &lfo2freq, 4);
1552    
1553            // next 2 bytes unknown
1554    
1555            memcpy(&pData[72], &LFO2InternalDepth, 2);
1556    
1557            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1558            memcpy(&pData[74], &eg1decay2, 4);
1559    
1560            // next 2 bytes unknown
1561    
1562            memcpy(&pData[80], &EG1PreAttack, 2);
1563    
1564            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1565            memcpy(&pData[82], &eg2decay2, 4);
1566    
1567            // next 2 bytes unknown
1568    
1569            memcpy(&pData[88], &EG2PreAttack, 2);
1570    
1571            {
1572                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1573                uint8_t velocityresponse = VelocityResponseDepth;
1574                switch (VelocityResponseCurve) {
1575                    case curve_type_nonlinear:
1576                        break;
1577                    case curve_type_linear:
1578                        velocityresponse += 5;
1579                        break;
1580                    case curve_type_special:
1581                        velocityresponse += 10;
1582                        break;
1583                    case curve_type_unknown:
1584                    default:
1585                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1586                }
1587                memcpy(&pData[90], &velocityresponse, 1);
1588          }          }
1589          uint8_t releasevelocityresponse = _3ewa->ReadUint8();  
1590          if (releasevelocityresponse < 5) {          {
1591              ReleaseVelocityResponseCurve = curve_type_nonlinear;              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1592              ReleaseVelocityResponseDepth = releasevelocityresponse;              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1593          }              switch (ReleaseVelocityResponseCurve) {
1594          else if (releasevelocityresponse < 10) {                  case curve_type_nonlinear:
1595              ReleaseVelocityResponseCurve = curve_type_linear;                      break;
1596              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  case curve_type_linear:
1597          }                      releasevelocityresponse += 5;
1598          else if (releasevelocityresponse < 15) {                      break;
1599              ReleaseVelocityResponseCurve = curve_type_special;                  case curve_type_special:
1600              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;                      releasevelocityresponse += 10;
1601                        break;
1602                    case curve_type_unknown:
1603                    default:
1604                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1605                }
1606                memcpy(&pData[91], &releasevelocityresponse, 1);
1607          }          }
1608          else {  
1609              ReleaseVelocityResponseCurve = curve_type_unknown;          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1610              ReleaseVelocityResponseDepth = 0;  
1611            memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1612    
1613            // next 4 bytes unknown
1614    
1615            memcpy(&pData[98], &SampleStartOffset, 2);
1616    
1617            // next 2 bytes unknown
1618    
1619            {
1620                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1621                switch (DimensionBypass) {
1622                    case dim_bypass_ctrl_94:
1623                        pitchTrackDimensionBypass |= 0x10;
1624                        break;
1625                    case dim_bypass_ctrl_95:
1626                        pitchTrackDimensionBypass |= 0x20;
1627                        break;
1628                    case dim_bypass_ctrl_none:
1629                        //FIXME: should we set anything here?
1630                        break;
1631                    default:
1632                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1633                }
1634                memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1635          }          }
1636          VelocityResponseCurveScaling = _3ewa->ReadUint8();  
1637          AttenuationControllerThreshold = _3ewa->ReadInt8();          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1638          _3ewa->ReadInt32(); // unknown          memcpy(&pData[103], &pan, 1);
1639          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
1640          _3ewa->ReadInt16(); // unknown          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1641          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          memcpy(&pData[104], &selfmask, 1);
1642          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1643          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          // next byte unknown
1644          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
1645          else                                       DimensionBypass = dim_bypass_ctrl_none;          {
1646          uint8_t pan = _3ewa->ReadUint8();              uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1647          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1648          SelfMask = _3ewa->ReadInt8() & 0x01;              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1649          _3ewa->ReadInt8(); // unknown              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1650          uint8_t lfo3ctrl = _3ewa->ReadUint8();              memcpy(&pData[106], &lfo3ctrl, 1);
1651          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          }
1652          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
1653          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1654          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));          memcpy(&pData[107], &attenctl, 1);
1655          uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
1656          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits          {
1657          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1658          LFO2Sync               = lfo2ctrl & 0x20; // bit 5              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1659          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1660          uint8_t lfo1ctrl       = _3ewa->ReadUint8();              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1661          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits              memcpy(&pData[108], &lfo2ctrl, 1);
1662          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7          }
1663          LFO1Sync               = lfo1ctrl & 0x40; // bit 6  
1664          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))          {
1665                                                      : vcf_res_ctrl_none;              uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1666          uint16_t eg3depth = _3ewa->ReadUint16();              if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1667          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1668                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */              if (VCFResonanceController != vcf_res_ctrl_none)
1669          _3ewa->ReadInt16(); // unknown                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1670          ChannelOffset = _3ewa->ReadUint8() / 4;              memcpy(&pData[109], &lfo1ctrl, 1);
1671          uint8_t regoptions = _3ewa->ReadUint8();          }
1672          MSDecode           = regoptions & 0x01; // bit 0  
1673          SustainDefeat      = regoptions & 0x02; // bit 1          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1674          _3ewa->ReadInt16(); // unknown                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1675          VelocityUpperLimit = _3ewa->ReadInt8();          memcpy(&pData[110], &eg3depth, 1);
1676          _3ewa->ReadInt8(); // unknown  
1677          _3ewa->ReadInt16(); // unknown          // next 2 bytes unknown
1678          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay  
1679          _3ewa->ReadInt8(); // unknown          const uint8_t channeloffset = ChannelOffset * 4;
1680          _3ewa->ReadInt8(); // unknown          memcpy(&pData[113], &channeloffset, 1);
1681          EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
1682          uint8_t vcfcutoff = _3ewa->ReadUint8();          {
1683          VCFEnabled = vcfcutoff & 0x80; // bit 7              uint8_t regoptions = 0;
1684          VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits              if (MSDecode)      regoptions |= 0x01; // bit 0
1685          VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());              if (SustainDefeat) regoptions |= 0x02; // bit 1
1686          VCFVelocityScale = _3ewa->ReadUint8();              memcpy(&pData[114], &regoptions, 1);
         _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;  
1687          }          }
1688    
1689          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet          // next 2 bytes unknown
1690          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;  
1691            memcpy(&pData[117], &VelocityUpperLimit, 1);
1692    
1693            // next 3 bytes unknown
1694    
1695            memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1696    
1697            // next 2 bytes unknown
1698    
1699            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1700            memcpy(&pData[124], &eg1hold, 1);
1701    
1702            const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1703                                      (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */
1704            memcpy(&pData[125], &vcfcutoff, 1);
1705    
1706            memcpy(&pData[126], &VCFCutoffController, 1);
1707    
1708            const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1709                                        (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1710            memcpy(&pData[127], &vcfvelscale, 1);
1711    
1712            // next byte unknown
1713    
1714            const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1715                                         (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1716            memcpy(&pData[129], &vcfresonance, 1);
1717    
1718            const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1719                                          (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1720            memcpy(&pData[130], &vcfbreakpoint, 1);
1721    
1722            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1723                                        VCFVelocityCurve * 5;
1724            memcpy(&pData[131], &vcfvelocity, 1);
1725    
1726            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1727            memcpy(&pData[132], &vcftype, 1);
1728        }
1729    
1730        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1731        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1732        {
1733            double* table;
1734            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1735          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1736              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1737          }          }
1738          else {          else {
1739              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1740                  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  
1741          }          }
1742            return table;
         SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));  
1743      }      }
1744    
1745      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1295  namespace { Line 1860  namespace {
1860          return decodedcontroller;          return decodedcontroller;
1861      }      }
1862    
1863        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1864            _lev_ctrl_t encodedcontroller;
1865            switch (DecodedController.type) {
1866                // special controller
1867                case leverage_ctrl_t::type_none:
1868                    encodedcontroller = _lev_ctrl_none;
1869                    break;
1870                case leverage_ctrl_t::type_velocity:
1871                    encodedcontroller = _lev_ctrl_velocity;
1872                    break;
1873                case leverage_ctrl_t::type_channelaftertouch:
1874                    encodedcontroller = _lev_ctrl_channelaftertouch;
1875                    break;
1876    
1877                // ordinary MIDI control change controller
1878                case leverage_ctrl_t::type_controlchange:
1879                    switch (DecodedController.controller_number) {
1880                        case 1:
1881                            encodedcontroller = _lev_ctrl_modwheel;
1882                            break;
1883                        case 2:
1884                            encodedcontroller = _lev_ctrl_breath;
1885                            break;
1886                        case 4:
1887                            encodedcontroller = _lev_ctrl_foot;
1888                            break;
1889                        case 12:
1890                            encodedcontroller = _lev_ctrl_effect1;
1891                            break;
1892                        case 13:
1893                            encodedcontroller = _lev_ctrl_effect2;
1894                            break;
1895                        case 16:
1896                            encodedcontroller = _lev_ctrl_genpurpose1;
1897                            break;
1898                        case 17:
1899                            encodedcontroller = _lev_ctrl_genpurpose2;
1900                            break;
1901                        case 18:
1902                            encodedcontroller = _lev_ctrl_genpurpose3;
1903                            break;
1904                        case 19:
1905                            encodedcontroller = _lev_ctrl_genpurpose4;
1906                            break;
1907                        case 5:
1908                            encodedcontroller = _lev_ctrl_portamentotime;
1909                            break;
1910                        case 64:
1911                            encodedcontroller = _lev_ctrl_sustainpedal;
1912                            break;
1913                        case 65:
1914                            encodedcontroller = _lev_ctrl_portamento;
1915                            break;
1916                        case 66:
1917                            encodedcontroller = _lev_ctrl_sostenutopedal;
1918                            break;
1919                        case 67:
1920                            encodedcontroller = _lev_ctrl_softpedal;
1921                            break;
1922                        case 80:
1923                            encodedcontroller = _lev_ctrl_genpurpose5;
1924                            break;
1925                        case 81:
1926                            encodedcontroller = _lev_ctrl_genpurpose6;
1927                            break;
1928                        case 82:
1929                            encodedcontroller = _lev_ctrl_genpurpose7;
1930                            break;
1931                        case 83:
1932                            encodedcontroller = _lev_ctrl_genpurpose8;
1933                            break;
1934                        case 91:
1935                            encodedcontroller = _lev_ctrl_effect1depth;
1936                            break;
1937                        case 92:
1938                            encodedcontroller = _lev_ctrl_effect2depth;
1939                            break;
1940                        case 93:
1941                            encodedcontroller = _lev_ctrl_effect3depth;
1942                            break;
1943                        case 94:
1944                            encodedcontroller = _lev_ctrl_effect4depth;
1945                            break;
1946                        case 95:
1947                            encodedcontroller = _lev_ctrl_effect5depth;
1948                            break;
1949                        default:
1950                            throw gig::Exception("leverage controller number is not supported by the gig format");
1951                    }
1952                default:
1953                    throw gig::Exception("Unknown leverage controller type.");
1954            }
1955            return encodedcontroller;
1956        }
1957    
1958      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
1959          Instances--;          Instances--;
1960          if (!Instances) {          if (!Instances) {
# Line 1325  namespace { Line 1985  namespace {
1985          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1986      }      }
1987    
1988        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1989            return pVelocityReleaseTable[MIDIKeyVelocity];
1990        }
1991    
1992        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1993            return pVelocityCutoffTable[MIDIKeyVelocity];
1994        }
1995    
1996      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) {
1997    
1998          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1358  namespace { Line 2026  namespace {
2026          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,
2027                               127, 127 };                               127, 127 };
2028    
2029            // this is only used by the VCF velocity curve
2030            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2031                                 91, 127, 127, 127 };
2032    
2033          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2034                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2035                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2036    
2037          double* const table = new double[128];          double* const table = new double[128];
2038    
# Line 1412  namespace { Line 2084  namespace {
2084              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2085                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2086                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2087                    _3lnk->ReadUint8(); // probably the position of the dimension
2088                    _3lnk->ReadUint8(); // unknown
2089                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2090                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2091                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2092                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
# Line 1423  namespace { Line 2098  namespace {
2098                  else { // active dimension                  else { // active dimension
2099                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2100                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2101                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2102                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2103                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2104                                                             dimension == dimension_releasetrigger ||                                                             dimension == dimension_releasetrigger ||
# Line 1432  namespace { Line 2107  namespace {
2107                                                                                            : split_type_normal;                                                                                            : split_type_normal;
2108                      pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point                      pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point
2109                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2110                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2111                                                                                     : 0;                                                                                     : 0;
2112                      Dimensions++;                      Dimensions++;
2113    
2114                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2115                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2116                  }                  }
2117                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2118              }              }
2119                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2120    
2121              // check velocity dimension (if there is one) for custom defined zone ranges              // check velocity dimension (if there is one) for custom defined zone ranges
2122              for (uint i = 0; i < Dimensions; i++) {              for (uint i = 0; i < Dimensions; i++) {
# Line 1454  namespace { Line 2130  namespace {
2130                      else { // custom defined ranges                      else { // custom defined ranges
2131                          pDimDef->split_type = split_type_customvelocity;                          pDimDef->split_type = split_type_customvelocity;
2132                          pDimDef->ranges     = new range_t[pDimDef->zones];                          pDimDef->ranges     = new range_t[pDimDef->zones];
2133                          uint8_t bits[8] = { 0 };                          UpdateVelocityTable(pDimDef);
                         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;  
                             }  
                         }  
2134                      }                      }
2135                  }                  }
2136              }              }
# Line 1485  namespace { Line 2148  namespace {
2148                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2149              }              }
2150          }          }
2151          else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2152            // make sure there is at least one dimension region
2153            if (!DimensionRegions) {
2154                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2155                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2156                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2157                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2158                DimensionRegions = 1;
2159            }
2160        }
2161    
2162        /**
2163         * Apply Region settings and all its DimensionRegions to the respective
2164         * RIFF chunks. You have to call File::Save() to make changes persistent.
2165         *
2166         * Usually there is absolutely no need to call this method explicitly.
2167         * It will be called automatically when File::Save() was called.
2168         *
2169         * @throws gig::Exception if samples cannot be dereferenced
2170         */
2171        void Region::UpdateChunks() {
2172            // first update base class's chunks
2173            DLS::Region::UpdateChunks();
2174    
2175            // update dimension region's chunks
2176            for (int i = 0; i < DimensionRegions; i++) {
2177                pDimensionRegions[i]->UpdateChunks();
2178            }
2179    
2180            File* pFile = (File*) GetParent()->GetParent();
2181            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2182            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2183    
2184            // make sure '3lnk' chunk exists
2185            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2186            if (!_3lnk) {
2187                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2188                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2189            }
2190    
2191            // update dimension definitions in '3lnk' chunk
2192            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2193            for (int i = 0; i < iMaxDimensions; i++) {
2194                pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;
2195                pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2196                // next 2 bytes unknown
2197                pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2198                // next 3 bytes unknown
2199            }
2200    
2201            // update wave pool table in '3lnk' chunk
2202            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2203            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2204                int iWaveIndex = -1;
2205                if (i < DimensionRegions) {
2206                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2207                    File::SampleList::iterator iter = pFile->pSamples->begin();
2208                    File::SampleList::iterator end  = pFile->pSamples->end();
2209                    for (int index = 0; iter != end; ++iter, ++index) {
2210                        if (*iter == pDimensionRegions[i]->pSample) {
2211                            iWaveIndex = index;
2212                            break;
2213                        }
2214                    }
2215                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2216                }
2217                memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2218            }
2219      }      }
2220    
2221      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1504  namespace { Line 2234  namespace {
2234          }          }
2235      }      }
2236    
2237        void Region::UpdateVelocityTable(dimension_def_t* pDimDef) {
2238            // get dimension's index
2239            int iDimensionNr = -1;
2240            for (int i = 0; i < Dimensions; i++) {
2241                if (&pDimensionDefinitions[i] == pDimDef) {
2242                    iDimensionNr = i;
2243                    break;
2244                }
2245            }
2246            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2247    
2248            uint8_t bits[8] = { 0 };
2249            int previousUpperLimit = -1;
2250            for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {
2251                bits[iDimensionNr] = velocityZone;
2252                DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);
2253    
2254                pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;
2255                pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;
2256                previousUpperLimit = pDimDef->ranges[velocityZone].high;
2257                // fill velocity table
2258                for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {
2259                    VelocityTable[i] = velocityZone;
2260                }
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            // if this is velocity dimension and got custom defined ranges, update velocity table
2316            if (pDimDef->dimension  == dimension_velocity &&
2317                pDimDef->split_type == split_type_customvelocity) {
2318                UpdateVelocityTable(pDimDef);
2319            }
2320        }
2321    
2322        /** @brief Delete an existing dimension.
2323         *
2324         * Deletes the dimension given by \a pDimDef and deletes all respective
2325         * dimension regions, that is all dimension regions where the dimension's
2326         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2327         * for example this would delete all dimension regions for the case(s)
2328         * where the sustain pedal is pressed down.
2329         *
2330         * @param pDimDef - dimension to delete
2331         * @throws gig::Exception if given dimension cannot be found
2332         */
2333        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2334            // get dimension's index
2335            int iDimensionNr = -1;
2336            for (int i = 0; i < Dimensions; i++) {
2337                if (&pDimensionDefinitions[i] == pDimDef) {
2338                    iDimensionNr = i;
2339                    break;
2340                }
2341            }
2342            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2343    
2344            // get amount of bits below the dimension to delete
2345            int iLowerBits = 0;
2346            for (int i = 0; i < iDimensionNr; i++)
2347                iLowerBits += pDimensionDefinitions[i].bits;
2348    
2349            // get amount ot bits above the dimension to delete
2350            int iUpperBits = 0;
2351            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2352                iUpperBits += pDimensionDefinitions[i].bits;
2353    
2354            // delete dimension regions which belong to the given dimension
2355            // (that is where the dimension's bit > 0)
2356            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2357                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2358                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2359                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2360                                        iObsoleteBit << iLowerBits |
2361                                        iLowerBit;
2362                        delete pDimensionRegions[iToDelete];
2363                        pDimensionRegions[iToDelete] = NULL;
2364                        DimensionRegions--;
2365                    }
2366                }
2367            }
2368    
2369            // defrag pDimensionRegions array
2370            // (that is remove the NULL spaces within the pDimensionRegions array)
2371            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2372                if (!pDimensionRegions[iTo]) {
2373                    if (iFrom <= iTo) iFrom = iTo + 1;
2374                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2375                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2376                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2377                        pDimensionRegions[iFrom] = NULL;
2378                    }
2379                }
2380            }
2381    
2382            // 'remove' dimension definition
2383            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2384                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2385            }
2386            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2387            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2388            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2389            if (pDimensionDefinitions[Dimensions - 1].ranges) {
2390                delete[] pDimensionDefinitions[Dimensions - 1].ranges;
2391                pDimensionDefinitions[Dimensions - 1].ranges = NULL;
2392            }
2393    
2394            Dimensions--;
2395    
2396            // if this was a layer dimension, update 'Layers' attribute
2397            if (pDimDef->dimension == dimension_layer) Layers = 1;
2398        }
2399    
2400      Region::~Region() {      Region::~Region() {
2401          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2402              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;
# Line 1537  namespace { Line 2430  namespace {
2430              bits[i] = DimValues[i];              bits[i] = DimValues[i];
2431              switch (pDimensionDefinitions[i].split_type) {              switch (pDimensionDefinitions[i].split_type) {
2432                  case split_type_normal:                  case split_type_normal:
2433                      bits[i] /= pDimensionDefinitions[i].zone_size;                      bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size);
2434                      break;                      break;
2435                  case split_type_customvelocity:                  case split_type_customvelocity:
2436                      bits[i] = VelocityTable[bits[i]];                      bits[i] = VelocityTable[bits[i]];
# Line 1589  namespace { Line 2482  namespace {
2482          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2483          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2484          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2485            unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2486          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
2487          while (sample) {          while (sample) {
2488              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2489                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
2490              sample = file->GetNextSample();              sample = file->GetNextSample();
2491          }          }
2492          return NULL;          return NULL;
# Line 1605  namespace { Line 2500  namespace {
2500      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2501          // Initialization          // Initialization
2502          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2503    
2504          // Loading          // Loading
2505          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1621  namespace { Line 2515  namespace {
2515                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2516                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2517              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2518          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2519    
2520            if (!pRegions) pRegions = new RegionList;
2521          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2522          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2523          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2524          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              while (rgn) {
2525          RIFF::List* rgn = lrgn->GetFirstSubList();                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2526          unsigned int iRegion = 0;                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2527          while (rgn) {                      pRegions->push_back(new Region(this, rgn));
2528              if (rgn->GetListType() == LIST_TYPE_RGN) {                  }
2529                  __notify_progress(pProgress, (float) iRegion / (float) Regions);                  rgn = lrgn->GetNextSubList();
                 pRegions[iRegion] = new Region(this, rgn);  
                 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];  
2530              }              }
2531                // Creating Region Key Table for fast lookup
2532                UpdateRegionKeyTable();
2533          }          }
2534    
2535          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
2536      }      }
2537    
2538      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2539          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2540              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2541                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2542                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2543                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2544                    RegionKeyTable[iKey] = pRegion;
2545              }              }
2546          }          }
2547          if (pRegions) delete[] pRegions;      }
2548    
2549        Instrument::~Instrument() {
2550        }
2551    
2552        /**
2553         * Apply Instrument with all its Regions to the respective RIFF chunks.
2554         * You have to call File::Save() to make changes persistent.
2555         *
2556         * Usually there is absolutely no need to call this method explicitly.
2557         * It will be called automatically when File::Save() was called.
2558         *
2559         * @throws gig::Exception if samples cannot be dereferenced
2560         */
2561        void Instrument::UpdateChunks() {
2562            // first update base classes' chunks
2563            DLS::Instrument::UpdateChunks();
2564    
2565            // update Regions' chunks
2566            {
2567                RegionList::iterator iter = pRegions->begin();
2568                RegionList::iterator end  = pRegions->end();
2569                for (; iter != end; ++iter)
2570                    (*iter)->UpdateChunks();
2571            }
2572    
2573            // make sure 'lart' RIFF list chunk exists
2574            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2575            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2576            // make sure '3ewg' RIFF chunk exists
2577            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2578            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2579            // update '3ewg' RIFF chunk
2580            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2581            memcpy(&pData[0], &EffectSend, 2);
2582            memcpy(&pData[2], &Attenuation, 4);
2583            memcpy(&pData[6], &FineTune, 2);
2584            memcpy(&pData[8], &PitchbendRange, 2);
2585            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2586                                        DimensionKeyRange.low << 1;
2587            memcpy(&pData[10], &dimkeystart, 1);
2588            memcpy(&pData[11], &DimensionKeyRange.high, 1);
2589      }      }
2590    
2591      /**      /**
# Line 1667  namespace { Line 2596  namespace {
2596       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2597       */       */
2598      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2599          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2600          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2601    
2602          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2603              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2604                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1684  namespace { Line 2614  namespace {
2614       * @see      GetNextRegion()       * @see      GetNextRegion()
2615       */       */
2616      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2617          if (!Regions) return NULL;          if (!pRegions) return NULL;
2618          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2619          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2620      }      }
2621    
2622      /**      /**
# Line 1698  namespace { Line 2628  namespace {
2628       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2629       */       */
2630      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2631          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2632          return pRegions[RegionIndex++];          RegionsIterator++;
2633            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2634        }
2635    
2636        Region* Instrument::AddRegion() {
2637            // create new Region object (and its RIFF chunks)
2638            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2639            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2640            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2641            Region* pNewRegion = new Region(this, rgn);
2642            pRegions->push_back(pNewRegion);
2643            Regions = pRegions->size();
2644            // update Region key table for fast lookup
2645            UpdateRegionKeyTable();
2646            // done
2647            return pNewRegion;
2648        }
2649    
2650        void Instrument::DeleteRegion(Region* pRegion) {
2651            if (!pRegions) return;
2652            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2653            // update Region key table for fast lookup
2654            UpdateRegionKeyTable();
2655      }      }
2656    
2657    
# Line 1707  namespace { Line 2659  namespace {
2659  // *************** File ***************  // *************** File ***************
2660  // *  // *
2661    
2662      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File() : DLS::File() {
         pSamples     = NULL;  
         pInstruments = NULL;  
2663      }      }
2664    
2665      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;  
         }  
2666      }      }
2667    
2668      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 1749  namespace { Line 2678  namespace {
2678          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2679      }      }
2680    
2681        /** @brief Add a new sample.
2682         *
2683         * This will create a new Sample object for the gig file. You have to
2684         * call Save() to make this persistent to the file.
2685         *
2686         * @returns pointer to new Sample object
2687         */
2688        Sample* File::AddSample() {
2689           if (!pSamples) LoadSamples();
2690           __ensureMandatoryChunksExist();
2691           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2692           // create new Sample object and its respective 'wave' list chunk
2693           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2694           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2695           pSamples->push_back(pSample);
2696           return pSample;
2697        }
2698    
2699        /** @brief Delete a sample.
2700         *
2701         * This will delete the given Sample object from the gig file. You have
2702         * to call Save() to make this persistent to the file.
2703         *
2704         * @param pSample - sample to delete
2705         * @throws gig::Exception if given sample could not be found
2706         */
2707        void File::DeleteSample(Sample* pSample) {
2708            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2709            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2710            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2711            pSamples->erase(iter);
2712            delete pSample;
2713        }
2714    
2715        void File::LoadSamples() {
2716            LoadSamples(NULL);
2717        }
2718    
2719      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
2720          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          if (!pSamples) pSamples = new SampleList;
2721          if (wvpl) {  
2722              // just for progress calculation          RIFF::File* file = pRIFF;
             int iSampleIndex  = 0;  
             int iTotalSamples = wvpl->CountSubLists(LIST_TYPE_WAVE);  
   
             unsigned long wvplFileOffset = wvpl->GetFilePos();  
             RIFF::List* wave = wvpl->GetFirstSubList();  
             while (wave) {  
                 if (wave->GetListType() == LIST_TYPE_WAVE) {  
                     // notify current progress  
                     const float subprogress = (float) iSampleIndex / (float) iTotalSamples;  
                     __notify_progress(pProgress, subprogress);  
2723    
2724                      if (!pSamples) pSamples = new SampleList;          // just for progress calculation
2725                      unsigned long waveFileOffset = wave->GetFilePos();          int iSampleIndex  = 0;
2726                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));          int iTotalSamples = WavePoolCount;
2727    
2728            // check if samples should be loaded from extension files
2729            int lastFileNo = 0;
2730            for (int i = 0 ; i < WavePoolCount ; i++) {
2731                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2732            }
2733            String name(pRIFF->GetFileName());
2734            int nameLen = name.length();
2735            char suffix[6];
2736            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2737    
2738            for (int fileNo = 0 ; ; ) {
2739                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2740                if (wvpl) {
2741                    unsigned long wvplFileOffset = wvpl->GetFilePos();
2742                    RIFF::List* wave = wvpl->GetFirstSubList();
2743                    while (wave) {
2744                        if (wave->GetListType() == LIST_TYPE_WAVE) {
2745                            // notify current progress
2746                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2747                            __notify_progress(pProgress, subprogress);
2748    
2749                      iSampleIndex++;                          unsigned long waveFileOffset = wave->GetFilePos();
2750                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2751    
2752                            iSampleIndex++;
2753                        }
2754                        wave = wvpl->GetNextSubList();
2755                  }                  }
2756                  wave = wvpl->GetNextSubList();  
2757              }                  if (fileNo == lastFileNo) break;
2758              __notify_progress(pProgress, 1.0); // notify done  
2759                    // open extension file (*.gx01, *.gx02, ...)
2760                    fileNo++;
2761                    sprintf(suffix, ".gx%02d", fileNo);
2762                    name.replace(nameLen, 5, suffix);
2763                    file = new RIFF::File(name);
2764                    ExtensionFiles.push_back(file);
2765                } else break;
2766          }          }
2767          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2768            __notify_progress(pProgress, 1.0); // notify done
2769      }      }
2770    
2771      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
2772          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2773          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2774          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2775          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2776      }      }
2777    
2778      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2779          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2780          InstrumentsIterator++;          InstrumentsIterator++;
2781          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2782      }      }
2783    
2784      /**      /**
# Line 1820  namespace { Line 2811  namespace {
2811          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2812          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2813          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2814              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2815              InstrumentsIterator++;              InstrumentsIterator++;
2816          }          }
2817          return NULL;          return NULL;
2818      }      }
2819    
2820        /** @brief Add a new instrument definition.
2821         *
2822         * This will create a new Instrument object for the gig file. You have
2823         * to call Save() to make this persistent to the file.
2824         *
2825         * @returns pointer to new Instrument object
2826         */
2827        Instrument* File::AddInstrument() {
2828           if (!pInstruments) LoadInstruments();
2829           __ensureMandatoryChunksExist();
2830           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2831           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2832           Instrument* pInstrument = new Instrument(this, lstInstr);
2833           pInstruments->push_back(pInstrument);
2834           return pInstrument;
2835        }
2836    
2837        /** @brief Delete an instrument.
2838         *
2839         * This will delete the given Instrument object from the gig file. You
2840         * have to call Save() to make this persistent to the file.
2841         *
2842         * @param pInstrument - instrument to delete
2843         * @throws gig::Excption if given instrument could not be found
2844         */
2845        void File::DeleteInstrument(Instrument* pInstrument) {
2846            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2847            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2848            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2849            pInstruments->erase(iter);
2850            delete pInstrument;
2851        }
2852    
2853        void File::LoadInstruments() {
2854            LoadInstruments(NULL);
2855        }
2856    
2857      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
2858            if (!pInstruments) pInstruments = new InstrumentList;
2859          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2860          if (lstInstruments) {          if (lstInstruments) {
2861              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 1841  namespace { Line 2870  namespace {
2870                      progress_t subprogress;                      progress_t subprogress;
2871                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2872    
                     if (!pInstruments) pInstruments = new InstrumentList;  
2873                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2874    
2875                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 1850  namespace { Line 2878  namespace {
2878              }              }
2879              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
2880          }          }
         else throw gig::Exception("Mandatory <lins> list chunk not found.");  
2881      }      }
2882    
2883    
# Line 1865  namespace { Line 2892  namespace {
2892          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
2893      }      }
2894    
2895    
2896    // *************** functions ***************
2897    // *
2898    
2899        /**
2900         * Returns the name of this C++ library. This is usually "libgig" of
2901         * course. This call is equivalent to RIFF::libraryName() and
2902         * DLS::libraryName().
2903         */
2904        String libraryName() {
2905            return PACKAGE;
2906        }
2907    
2908        /**
2909         * Returns version of this C++ library. This call is equivalent to
2910         * RIFF::libraryVersion() and DLS::libraryVersion().
2911         */
2912        String libraryVersion() {
2913            return VERSION;
2914        }
2915    
2916  } // namespace gig  } // namespace gig

Legend:
Removed from v.516  
changed lines
  Added in v.834

  ViewVC Help
Powered by ViewVC