/[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 365 by persson, Thu Feb 10 19:16:31 2005 UTC revision 864 by persson, Sun May 14 07:15:38 2006 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file loader library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003, 2004 by Christian Schoenebeck                     *   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *
6   *                               <cuse@users.sourceforge.net>              *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26  namespace gig { namespace {  #include "helper.h"
27    
28  // *************** Internal functions for sample decopmression ***************  #include <math.h>
29    #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 {
53    
54    // *************** progress_t ***************
55  // *  // *
56    
57        progress_t::progress_t() {
58            callback    = NULL;
59            custom      = NULL;
60            __range_min = 0.0f;
61            __range_max = 1.0f;
62        }
63    
64        // private helper function to convert progress of a subprocess into the global progress
65        static void __notify_progress(progress_t* pProgress, float subprogress) {
66            if (pProgress && pProgress->callback) {
67                const float totalrange    = pProgress->__range_max - pProgress->__range_min;
68                const float totalprogress = pProgress->__range_min + subprogress * totalrange;
69                pProgress->factor         = totalprogress;
70                pProgress->callback(pProgress); // now actually notify about the progress
71            }
72        }
73    
74        // private helper function to divide a progress into subprogresses
75        static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {
76            if (pParentProgress && pParentProgress->callback) {
77                const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;
78                pSubProgress->callback    = pParentProgress->callback;
79                pSubProgress->custom      = pParentProgress->custom;
80                pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;
81                pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;
82            }
83        }
84    
85    
86    // *************** Internal functions for sample decompression ***************
87    // *
88    
89    namespace {
90    
91      inline int get12lo(const unsigned char* pSrc)      inline int get12lo(const unsigned char* pSrc)
92      {      {
93          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;          const int x = pSrc[0] | (pSrc[1] & 0x0f) << 8;
# Line 52  namespace gig { namespace { Line 112  namespace gig { namespace {
112      }      }
113    
114      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
115                        int srcStep, const unsigned char* pSrc, int16_t* pDst,                        int srcStep, int dstStep,
116                          const unsigned char* pSrc, int16_t* pDst,
117                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
118                        unsigned long copysamples)                        unsigned long copysamples)
119      {      {
# Line 61  namespace gig { namespace { Line 122  namespace gig { namespace {
122                  pSrc += currentframeoffset * srcStep;                  pSrc += currentframeoffset * srcStep;
123                  while (copysamples) {                  while (copysamples) {
124                      *pDst = get16(pSrc);                      *pDst = get16(pSrc);
125                      pDst += 2;                      pDst += dstStep;
126                      pSrc += srcStep;                      pSrc += srcStep;
127                      copysamples--;                      copysamples--;
128                  }                  }
# Line 80  namespace gig { namespace { Line 141  namespace gig { namespace {
141                      dy -= int8_t(*pSrc);                      dy -= int8_t(*pSrc);
142                      y  -= dy;                      y  -= dy;
143                      *pDst = y;                      *pDst = y;
144                      pDst += 2;                      pDst += dstStep;
145                      pSrc += srcStep;                      pSrc += srcStep;
146                      copysamples--;                      copysamples--;
147                  }                  }
# Line 89  namespace gig { namespace { Line 150  namespace gig { namespace {
150      }      }
151    
152      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
153                        const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, int16_t* pDst,
154                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
155                        unsigned long copysamples)                        unsigned long copysamples, int truncatedBits)
156      {      {
157          // Note: The 24 bits are truncated to 16 bits for now.          // Note: The 24 bits are truncated to 16 bits for now.
158    
159          // Note: The calculation of the initial value of y is strange          int y, dy, ddy, dddy;
160          // and not 100% correct. What should the first two parameters          const int shift = 8 - truncatedBits;
161          // really be used for? Why are they two? The correct value for  
162          // y seems to lie somewhere between the values of the first  #define GET_PARAMS(params)                      \
163          // two parameters.          y    = get24(params);                   \
164          //          dy   = y - get24((params) + 3);         \
165          // Strange thing #2: The formula in SKIP_ONE gives values for          ddy  = get24((params) + 6);             \
166          // y that are twice as high as they should be. That's why          dddy = get24((params) + 9)
         // COPY_ONE shifts 9 steps instead of 8, and also why y is  
         // initialized with a sum instead of a mean value.  
   
         int y, dy, ddy;  
   
 #define GET_PARAMS(params)                              \  
         y = (get24(params) + get24((params) + 3));      \  
         dy  = get24((params) + 6);                      \  
         ddy = get24((params) + 9)  
167    
168  #define SKIP_ONE(x)                             \  #define SKIP_ONE(x)                             \
169          ddy -= (x);                             \          dddy -= (x);                            \
170          dy -= ddy;                              \          ddy  -= dddy;                           \
171          y -= dy          dy   =  -dy - ddy;                      \
172            y    += dy
173    
174  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
175          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
176          *pDst = y >> 9;                         \          *pDst = y >> shift;                     \
177          pDst += 2          pDst += dstStep
178    
179          switch (compressionmode) {          switch (compressionmode) {
180              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
181                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
182                  while (copysamples) {                  while (copysamples) {
183                      *pDst = get24(pSrc) >> 8;                      *pDst = get24(pSrc) >> shift;
184                      pDst += 2;                      pDst += dstStep;
185                      pSrc += 3;                      pSrc += 3;
186                      copysamples--;                      copysamples--;
187                  }                  }
# Line 200  namespace gig { namespace { Line 253  namespace gig { namespace {
253  // *************** Sample ***************  // *************** Sample ***************
254  // *  // *
255    
256      unsigned int  Sample::Instances               = 0;      unsigned int Sample::Instances = 0;
257      unsigned char* Sample::pDecompressionBuffer    = NULL;      buffer_t     Sample::InternalDecompressionBuffer;
     unsigned long Sample::DecompressionBufferSize = 0;  
258    
259      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
260         *
261         * Load an existing sample or create a new one. A 'wave' list chunk must
262         * be given to this constructor. In case the given 'wave' list chunk
263         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
264         * format and sample data will be loaded from there, otherwise default
265         * values will be used and those chunks will be created when
266         * File::Save() will be called later on.
267         *
268         * @param pFile          - pointer to gig::File where this sample is
269         *                         located (or will be located)
270         * @param waveList       - pointer to 'wave' list chunk which is (or
271         *                         will be) associated with this sample
272         * @param WavePoolOffset - offset of this sample data from wave pool
273         *                         ('wvpl') list chunk
274         * @param fileNo         - number of an extension file where this sample
275         *                         is located, 0 otherwise
276         */
277        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
278          Instances++;          Instances++;
279            FileNo = fileNo;
280    
281          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
282          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
283          SampleGroup = _3gix->ReadInt16();              SampleGroup = pCk3gix->ReadInt16();
284            } else { // '3gix' chunk missing
285          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              // use default value(s)
286          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              SampleGroup = 0;
287          Manufacturer      = smpl->ReadInt32();          }
288          Product           = smpl->ReadInt32();  
289          SamplePeriod      = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
290          MIDIUnityNote     = smpl->ReadInt32();          if (pCkSmpl) {
291          FineTune          = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
292          smpl->Read(&SMPTEFormat, 1, 4);              Product       = pCkSmpl->ReadInt32();
293          SMPTEOffset       = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
294          Loops             = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
295          smpl->ReadInt32(); // manufByt              FineTune      = pCkSmpl->ReadInt32();
296          LoopID            = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
297          smpl->Read(&LoopType, 1, 4);              SMPTEOffset   = pCkSmpl->ReadInt32();
298          LoopStart         = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
299          LoopEnd           = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
300          LoopFraction      = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
301          LoopPlayCount     = smpl->ReadInt32();              pCkSmpl->Read(&LoopType, 1, 4);
302                LoopStart     = pCkSmpl->ReadInt32();
303                LoopEnd       = pCkSmpl->ReadInt32();
304                LoopFraction  = pCkSmpl->ReadInt32();
305                LoopPlayCount = pCkSmpl->ReadInt32();
306            } else { // 'smpl' chunk missing
307                // use default values
308                Manufacturer  = 0;
309                Product       = 0;
310                SamplePeriod  = 1 / SamplesPerSecond;
311                MIDIUnityNote = 64;
312                FineTune      = 0;
313                SMPTEOffset   = 0;
314                Loops         = 0;
315                LoopID        = 0;
316                LoopStart     = 0;
317                LoopEnd       = 0;
318                LoopFraction  = 0;
319                LoopPlayCount = 0;
320            }
321    
322          FrameTable                 = NULL;          FrameTable                 = NULL;
323          SamplePos                  = 0;          SamplePos                  = 0;
# Line 237  namespace gig { namespace { Line 327  namespace gig { namespace {
327    
328          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");          if (BitDepth > 24) throw gig::Exception("Only samples up to 24 bit supported");
329    
330          Compressed = (waveList->GetSubChunk(CHUNK_ID_EWAV));          RIFF::Chunk* ewav = waveList->GetSubChunk(CHUNK_ID_EWAV);
331            Compressed        = ewav;
332            Dithered          = false;
333            TruncatedBits     = 0;
334          if (Compressed) {          if (Compressed) {
335                uint32_t version = ewav->ReadInt32();
336                if (version == 3 && BitDepth == 24) {
337                    Dithered = ewav->ReadInt32();
338                    ewav->SetPos(Channels == 2 ? 84 : 64);
339                    TruncatedBits = ewav->ReadInt32();
340                }
341              ScanCompressedSample();              ScanCompressedSample();
342          }          }
343    
344          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit          // we use a buffer for decompression and for truncating 24 bit samples to 16 bit
345          if ((Compressed || BitDepth == 24) && !pDecompressionBuffer) {          if ((Compressed || BitDepth == 24) && !InternalDecompressionBuffer.Size) {
346              pDecompressionBuffer    = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];              InternalDecompressionBuffer.pStart = new unsigned char[INITIAL_SAMPLE_BUFFER_SIZE];
347              DecompressionBufferSize = INITIAL_SAMPLE_BUFFER_SIZE;              InternalDecompressionBuffer.Size   = INITIAL_SAMPLE_BUFFER_SIZE;
348          }          }
349          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
350    
351          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
352        }
353    
354        /**
355         * Apply sample and its settings to the respective RIFF chunks. You have
356         * to call File::Save() to make changes persistent.
357         *
358         * Usually there is absolutely no need to call this method explicitly.
359         * It will be called automatically when File::Save() was called.
360         *
361         * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
362         *                        was provided yet
363         * @throws gig::Exception if there is any invalid sample setting
364         */
365        void Sample::UpdateChunks() {
366            // first update base class's chunks
367            DLS::Sample::UpdateChunks();
368    
369            // make sure 'smpl' chunk exists
370            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
371            if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
372            // update 'smpl' chunk
373            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
374            SamplePeriod = 1 / SamplesPerSecond;
375            memcpy(&pData[0], &Manufacturer, 4);
376            memcpy(&pData[4], &Product, 4);
377            memcpy(&pData[8], &SamplePeriod, 4);
378            memcpy(&pData[12], &MIDIUnityNote, 4);
379            memcpy(&pData[16], &FineTune, 4);
380            memcpy(&pData[20], &SMPTEFormat, 4);
381            memcpy(&pData[24], &SMPTEOffset, 4);
382            memcpy(&pData[28], &Loops, 4);
383    
384            // we skip 'manufByt' for now (4 bytes)
385    
386            memcpy(&pData[36], &LoopID, 4);
387            memcpy(&pData[40], &LoopType, 4);
388            memcpy(&pData[44], &LoopStart, 4);
389            memcpy(&pData[48], &LoopEnd, 4);
390            memcpy(&pData[52], &LoopFraction, 4);
391            memcpy(&pData[56], &LoopPlayCount, 4);
392    
393            // make sure '3gix' chunk exists
394            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
395            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
396            // update '3gix' chunk
397            pData = (uint8_t*) pCk3gix->LoadChunkData();
398            memcpy(&pData[0], &SampleGroup, 2);
399      }      }
400    
401      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).      /// Scans compressed samples for mandatory informations (e.g. actual number of total sample points).
# Line 259  namespace gig { namespace { Line 405  namespace gig { namespace {
405          std::list<unsigned long> frameOffsets;          std::list<unsigned long> frameOffsets;
406    
407          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
408          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels;          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
409    
410          // Scanning          // Scanning
411          pCkData->SetPos(0);          pCkData->SetPos(0);
# Line 340  namespace gig { namespace { Line 486  namespace gig { namespace {
486       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
487       * that the size is given in bytes! You get the number of actually cached       * that the size is given in bytes! You get the number of actually cached
488       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
489       *       * @code
490       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);       *  buffer_t buf       = pSample->LoadSampleData(acquired_samples);
491       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
492         * @endcode
493       *       *
494       * @param SampleCount - number of sample points to load into RAM       * @param SampleCount - number of sample points to load into RAM
495       * @returns             buffer_t structure with start address and size of       * @returns             buffer_t structure with start address and size of
# Line 388  namespace gig { namespace { Line 535  namespace gig { namespace {
535       * that will be returned to determine the actual cached samples, but note       * that will be returned to determine the actual cached samples, but note
536       * that the size is given in bytes! You get the number of actually cached       * that the size is given in bytes! You get the number of actually cached
537       * samples by dividing it by the frame size of the sample:       * samples by dividing it by the frame size of the sample:
538       *       * @code
539       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);       *  buffer_t buf       = pSample->LoadSampleDataWithNullSamplesExtension(acquired_samples, null_samples);
540       *  long cachedsamples = buf.Size / pSample->FrameSize;       *  long cachedsamples = buf.Size / pSample->FrameSize;
541       *       * @endcode
542       * The method will add \a NullSamplesCount silence samples past the       * The method will add \a NullSamplesCount silence samples past the
543       * official buffer end (this won't affect the 'Size' member of the       * official buffer end (this won't affect the 'Size' member of the
544       * buffer_t structure, that means 'Size' always reflects the size of the       * buffer_t structure, that means 'Size' always reflects the size of the
# Line 451  namespace gig { namespace { Line 598  namespace gig { namespace {
598          RAMCache.Size   = 0;          RAMCache.Size   = 0;
599      }      }
600    
601        /** @brief Resize sample.
602         *
603         * Resizes the sample's wave form data, that is the actual size of
604         * sample wave data possible to be written for this sample. This call
605         * will return immediately and just schedule the resize operation. You
606         * should call File::Save() to actually perform the resize operation(s)
607         * "physically" to the file. As this can take a while on large files, it
608         * is recommended to call Resize() first on all samples which have to be
609         * resized and finally to call File::Save() to perform all those resize
610         * operations in one rush.
611         *
612         * The actual size (in bytes) is dependant to the current FrameSize
613         * value. You may want to set FrameSize before calling Resize().
614         *
615         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
616         * enlarged samples before calling File::Save() as this might exceed the
617         * current sample's boundary!
618         *
619         * Also note: only WAVE_FORMAT_PCM is currently supported, that is
620         * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
621         * other formats will fail!
622         *
623         * @param iNewSize - new sample wave data size in sample points (must be
624         *                   greater than zero)
625         * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM
626         *                         or if \a iNewSize is less than 1
627         * @throws gig::Exception if existing sample is compressed
628         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
629         *      DLS::Sample::FormatTag, File::Save()
630         */
631        void Sample::Resize(int iNewSize) {
632            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
633            DLS::Sample::Resize(iNewSize);
634        }
635    
636      /**      /**
637       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
638       * bytes). Use this method and <i>Read()</i> if you don't want to load       * bytes). Use this method and <i>Read()</i> if you don't want to load
# Line 522  namespace gig { namespace { Line 704  namespace gig { namespace {
704       * for the next time you call this method is stored in \a pPlaybackState.       * for the next time you call this method is stored in \a pPlaybackState.
705       * You have to allocate and initialize the playback_state_t structure by       * You have to allocate and initialize the playback_state_t structure by
706       * yourself before you use it to stream a sample:       * yourself before you use it to stream a sample:
707       *       * @code
708       * <i>       * gig::playback_state_t playbackstate;
709       * gig::playback_state_t playbackstate;                           <br>       * playbackstate.position         = 0;
710       * playbackstate.position         = 0;                            <br>       * playbackstate.reverse          = false;
711       * playbackstate.reverse          = false;                        <br>       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;
712       * playbackstate.loop_cycles_left = pSample->LoopPlayCount;       <br>       * @endcode
      * </i>  
      *  
713       * You don't have to take care of things like if there is actually a loop       * You don't have to take care of things like if there is actually a loop
714       * defined or if the current read position is located within a loop area.       * defined or if the current read position is located within a loop area.
715       * The method already handles such cases by itself.       * The method already handles such cases by itself.
716       *       *
717         * <b>Caution:</b> If you are using more than one streaming thread, you
718         * have to use an external decompression buffer for <b>EACH</b>
719         * streaming thread to avoid race conditions and crashes!
720         *
721       * @param pBuffer          destination buffer       * @param pBuffer          destination buffer
722       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
723       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
724       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
725         * @param pDimRgn          dimension region with looping information
726         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
727       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
728         * @see                    CreateDecompressionBuffer()
729       */       */
730      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
731                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
732          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
733          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
734    
735          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
736    
737          if (this->Loops && GetPos() <= this->LoopEnd) { // honor looping if there are loop points defined          if (pDimRgn->SampleLoops) { // honor looping if there are loop points defined
738    
739              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
740                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
741    
742                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
743                      do {                  switch (loop.LoopType) {
                         // if not endless loop check if max. number of loop cycles have been passed  
                         if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;  
   
                         if (!pPlaybackState->reverse) { // forward playback  
                             do {  
                                 samplestoloopend  = this->LoopEnd - GetPos();  
                                 readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));  
                                 samplestoread    -= readsamples;  
                                 totalreadsamples += readsamples;  
                                 if (readsamples == samplestoloopend) {  
                                     pPlaybackState->reverse = true;  
                                     break;  
                                 }  
                             } while (samplestoread && readsamples);  
                         }  
                         else { // backward playback  
744    
745                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
746                              // determine the end position within the loop first,                          do {
747                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
748                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
749                              // backward playback  
750                                if (!pPlaybackState->reverse) { // forward playback
751                              unsigned long swapareastart       = totalreadsamples;                                  do {
752                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
753                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
754                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
755                                        totalreadsamples += readsamples;
756                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
757                                            pPlaybackState->reverse = true;
758                              // read samples for backward playback                                          break;
759                              do {                                      }
760                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop);                                  } while (samplestoread && readsamples);
761                                  samplestoreadinloop -= readsamples;                              }
762                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
763    
764                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
765                                    // determine the end position within the loop first,
766                                    // read forward from that 'end' and finally after
767                                    // reading, swap all sample frames so it reflects
768                                    // backward playback
769    
770                                    unsigned long swapareastart       = totalreadsamples;
771                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
772                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
773                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
774    
775                                    SetPos(reverseplaybackend);
776    
777                                    // read samples for backward playback
778                                    do {
779                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
780                                        samplestoreadinloop -= readsamples;
781                                        samplestoread       -= readsamples;
782                                        totalreadsamples    += readsamples;
783                                    } while (samplestoreadinloop && readsamples);
784    
785                                    SetPos(reverseplaybackend); // pretend we really read backwards
786    
787                                    if (reverseplaybackend == loop.LoopStart) {
788                                        pPlaybackState->loop_cycles_left--;
789                                        pPlaybackState->reverse = false;
790                                    }
791    
792                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
793                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
794                              }                              }
795                            } while (samplestoread && readsamples);
796                            break;
797                        }
798    
799                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
800                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
801                          }                          if (!pPlaybackState->reverse) do {
802                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
803                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
804                  }                              samplestoread    -= readsamples;
805                                totalreadsamples += readsamples;
806                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
807                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
808                      if (!pPlaybackState->reverse) do {                                  break;
809                          samplestoloopend  = this->LoopEnd - GetPos();                              }
810                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                          } while (samplestoread && readsamples);
                         samplestoread    -= readsamples;  
                         totalreadsamples += readsamples;  
                         if (readsamples == samplestoloopend) {  
                             pPlaybackState->reverse = true;  
                             break;  
                         }  
                     } while (samplestoread && readsamples);  
811    
812                      if (!samplestoread) break;                          if (!samplestoread) break;
813    
814                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
815                      // determine the end position within the loop first,                          // determine the end position within the loop first,
816                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
817                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
818                      // backward playback                          // backward playback
819    
820                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
821                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
822                      unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * LoopSize - loopoffset)                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
823                                                                                : samplestoread;                                                                                    : samplestoread;
824                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
825    
826                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
827    
828                      // read samples for backward playback                          // read samples for backward playback
829                      do {                          do {
830                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
831                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
832                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
833                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend));                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
834                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
835                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
836                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
837                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
838                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
839                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
840                          }                              }
841                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
842    
843                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
844    
845                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
846                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
847                      break;                          break;
848                  }                      }
849    
850                  default: case loop_type_normal: {                      default: case loop_type_normal: {
851                      do {                          do {
852                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
853                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
854                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
855                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend));                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
856                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
857                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
858                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
859                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
860                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
861                          }                              }
862                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
863                      break;                          break;
864                        }
865                  }                  }
866              }              }
867          }          }
868    
869          // read on without looping          // read on without looping
870          if (samplestoread) do {          if (samplestoread) do {
871              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread);              readsamples = Read(&pDst[totalreadsamples * this->FrameSize], samplestoread, pExternalDecompressionBuffer);
872              samplestoread    -= readsamples;              samplestoread    -= readsamples;
873              totalreadsamples += readsamples;              totalreadsamples += readsamples;
874          } while (readsamples && samplestoread);          } while (readsamples && samplestoread);
# Line 694  namespace gig { namespace { Line 887  namespace gig { namespace {
887       * and <i>SetPos()</i> if you don't want to load the sample into RAM,       * and <i>SetPos()</i> if you don't want to load the sample into RAM,
888       * thus for disk streaming.       * thus for disk streaming.
889       *       *
890         * <b>Caution:</b> If you are using more than one streaming thread, you
891         * have to use an external decompression buffer for <b>EACH</b>
892         * streaming thread to avoid race conditions and crashes!
893         *
894       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
895       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
896         * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
897       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
898       * @see                SetPos()       * @see                SetPos(), CreateDecompressionBuffer()
899       */       */
900      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount) {      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {
901          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
902          if (!Compressed) {          if (!Compressed) {
903              if (BitDepth == 24) {              if (BitDepth == 24) {
904                  // 24 bit sample. For now just truncate to 16 bit.                  // 24 bit sample. For now just truncate to 16 bit.
905                  unsigned char* pSrc = this->pDecompressionBuffer;                  unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);
906                  int16_t* pDst = static_cast<int16_t*>(pBuffer);                  int16_t* pDst = static_cast<int16_t*>(pBuffer);
907                  if (Channels == 2) { // Stereo                  if (Channels == 2) { // Stereo
908                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);                      unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);
# Line 741  namespace gig { namespace { Line 939  namespace gig { namespace {
939                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()                            currentframeoffset = this->FrameOffset;  // offset in current sample frame since last Read()
940              this->FrameOffset = 0;              this->FrameOffset = 0;
941    
942              if (assumedsize > this->DecompressionBufferSize) {              buffer_t* pDecompressionBuffer = (pExternalDecompressionBuffer) ? pExternalDecompressionBuffer : &InternalDecompressionBuffer;
943                  // local buffer reallocation - hope this won't happen  
944                  if (this->pDecompressionBuffer) delete[] this->pDecompressionBuffer;              // if decompression buffer too small, then reduce amount of samples to read
945                  this->pDecompressionBuffer    = new unsigned char[assumedsize << 1]; // double of current needed size              if (pDecompressionBuffer->Size < assumedsize) {
946                  this->DecompressionBufferSize = assumedsize << 1;                  std::cerr << "gig::Read(): WARNING - decompression buffer size too small!" << std::endl;
947                    SampleCount      = WorstCaseMaxSamples(pDecompressionBuffer);
948                    remainingsamples = SampleCount;
949                    assumedsize      = GuessSize(SampleCount);
950              }              }
951    
952              unsigned char* pSrc = this->pDecompressionBuffer;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
953              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
954              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
955    
# Line 831  namespace gig { namespace { Line 1032  namespace gig { namespace {
1032                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1033                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1034    
1035                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 2, pSrc, pDst,
1036                              Decompress24(mode_r, param_r, pSrc + rightChannelOffset, pDst + 1,                                           skipsamples, copysamples, TruncatedBits);
1037                                           skipsamples, copysamples);                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,
1038                                             skipsamples, copysamples, TruncatedBits);
1039                              pDst += copysamples << 1;                              pDst += copysamples << 1;
1040                          }                          }
1041                          else { // Mono                          else { // Mono
1042                              Decompress24(mode_l, param_l, pSrc, pDst, skipsamples, copysamples);                              Decompress24(mode_l, param_l, 1, pSrc, pDst,
1043                                             skipsamples, copysamples, TruncatedBits);
1044                              pDst += copysamples;                              pDst += copysamples;
1045                          }                          }
1046                      }                      }
# Line 850  namespace gig { namespace { Line 1053  namespace gig { namespace {
1053                              if (mode_r) pSrc += 4;                              if (mode_r) pSrc += 4;
1054    
1055                              step = (2 - mode_l) + (2 - mode_r);                              step = (2 - mode_l) + (2 - mode_r);
1056                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 2, pSrc, pDst, skipsamples, copysamples);
1057                              Decompress16(mode_r, param_r, step, pSrc + (2 - mode_l), pDst + 1,                              Decompress16(mode_r, param_r, step, 2, pSrc + (2 - mode_l), pDst + 1,
1058                                           skipsamples, copysamples);                                           skipsamples, copysamples);
1059                              pDst += copysamples << 1;                              pDst += copysamples << 1;
1060                          }                          }
1061                          else { // Mono                          else { // Mono
1062                              step = 2 - mode_l;                              step = 2 - mode_l;
1063                              Decompress16(mode_l, param_l, step, pSrc, pDst, skipsamples, copysamples);                              Decompress16(mode_l, param_l, step, 1, pSrc, pDst, skipsamples, copysamples);
1064                              pDst += copysamples;                              pDst += copysamples;
1065                          }                          }
1066                      }                      }
# Line 869  namespace gig { namespace { Line 1072  namespace gig { namespace {
1072                      assumedsize    = GuessSize(remainingsamples);                      assumedsize    = GuessSize(remainingsamples);
1073                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);                      pCkData->SetPos(remainingbytes, RIFF::stream_backward);
1074                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();                      if (pCkData->RemainingBytes() < assumedsize) assumedsize = pCkData->RemainingBytes();
1075                      remainingbytes = pCkData->Read(this->pDecompressionBuffer, assumedsize, 1);                      remainingbytes = pCkData->Read(pDecompressionBuffer->pStart, assumedsize, 1);
1076                      pSrc = this->pDecompressionBuffer;                      pSrc = (unsigned char*) pDecompressionBuffer->pStart;
1077                  }                  }
1078              } // while              } // while
1079    
# Line 880  namespace gig { namespace { Line 1083  namespace gig { namespace {
1083          }          }
1084      }      }
1085    
1086        /** @brief Write sample wave data.
1087         *
1088         * Writes \a SampleCount number of sample points from the buffer pointed
1089         * by \a pBuffer and increments the position within the sample. Use this
1090         * method to directly write the sample data to disk, i.e. if you don't
1091         * want or cannot load the whole sample data into RAM.
1092         *
1093         * You have to Resize() the sample to the desired size and call
1094         * File::Save() <b>before</b> using Write().
1095         *
1096         * Note: there is currently no support for writing compressed samples.
1097         *
1098         * @param pBuffer     - source buffer
1099         * @param SampleCount - number of sample points to write
1100         * @throws DLS::Exception if current sample size is too small
1101         * @throws gig::Exception if sample is compressed
1102         * @see DLS::LoadSampleData()
1103         */
1104        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1105            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1106            return DLS::Sample::Write(pBuffer, SampleCount);
1107        }
1108    
1109        /**
1110         * Allocates a decompression buffer for streaming (compressed) samples
1111         * with Sample::Read(). If you are using more than one streaming thread
1112         * in your application you <b>HAVE</b> to create a decompression buffer
1113         * for <b>EACH</b> of your streaming threads and provide it with the
1114         * Sample::Read() call in order to avoid race conditions and crashes.
1115         *
1116         * You should free the memory occupied by the allocated buffer(s) once
1117         * you don't need one of your streaming threads anymore by calling
1118         * DestroyDecompressionBuffer().
1119         *
1120         * @param MaxReadSize - the maximum size (in sample points) you ever
1121         *                      expect to read with one Read() call
1122         * @returns allocated decompression buffer
1123         * @see DestroyDecompressionBuffer()
1124         */
1125        buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {
1126            buffer_t result;
1127            const double worstCaseHeaderOverhead =
1128                    (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1129            result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1130            result.pStart            = new int8_t[result.Size];
1131            result.NullExtensionSize = 0;
1132            return result;
1133        }
1134    
1135        /**
1136         * Free decompression buffer, previously created with
1137         * CreateDecompressionBuffer().
1138         *
1139         * @param DecompressionBuffer - previously allocated decompression
1140         *                              buffer to free
1141         */
1142        void Sample::DestroyDecompressionBuffer(buffer_t& DecompressionBuffer) {
1143            if (DecompressionBuffer.Size && DecompressionBuffer.pStart) {
1144                delete[] (int8_t*) DecompressionBuffer.pStart;
1145                DecompressionBuffer.pStart = NULL;
1146                DecompressionBuffer.Size   = 0;
1147                DecompressionBuffer.NullExtensionSize = 0;
1148            }
1149        }
1150    
1151      Sample::~Sample() {      Sample::~Sample() {
1152          Instances--;          Instances--;
1153          if (!Instances && pDecompressionBuffer) {          if (!Instances && InternalDecompressionBuffer.Size) {
1154              delete[] pDecompressionBuffer;              delete[] (unsigned char*) InternalDecompressionBuffer.pStart;
1155              pDecompressionBuffer = NULL;              InternalDecompressionBuffer.pStart = NULL;
1156                InternalDecompressionBuffer.Size   = 0;
1157          }          }
1158          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
1159          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
# Line 901  namespace gig { namespace { Line 1170  namespace gig { namespace {
1170      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1171          Instances++;          Instances++;
1172    
1173            pSample = NULL;
1174    
1175          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1176          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1177    
1178          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1179          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1180          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1181          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1182          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1183          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1184          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1185          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1186          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1187          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1188          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1189          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1190          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1191          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1192          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1193          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1194          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1195          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1196          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1197          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1198          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1199          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1200          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1201          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1202          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1203          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1204          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1205          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1206          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1207          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1208          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1209          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1210          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1211          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1212          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1213          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1214          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1215          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1216          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1217          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1218          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1219          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1220          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1221          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1222          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1223          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1224          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1225          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1226          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1227          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1228          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1229          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1230              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1231              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1232          }                  VelocityResponseDepth = velocityresponse;
1233          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1234              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1235              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1236          }              } else if (velocityresponse < 15) {
1237          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1238              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1239              VelocityResponseDepth = velocityresponse - 10;              } else {
1240                    VelocityResponseCurve = curve_type_unknown;
1241                    VelocityResponseDepth = 0;
1242                }
1243                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1244                if (releasevelocityresponse < 5) {
1245                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1246                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1247                } else if (releasevelocityresponse < 10) {
1248                    ReleaseVelocityResponseCurve = curve_type_linear;
1249                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1250                } else if (releasevelocityresponse < 15) {
1251                    ReleaseVelocityResponseCurve = curve_type_special;
1252                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1253                } else {
1254                    ReleaseVelocityResponseCurve = curve_type_unknown;
1255                    ReleaseVelocityResponseDepth = 0;
1256                }
1257                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1258                AttenuationControllerThreshold = _3ewa->ReadInt8();
1259                _3ewa->ReadInt32(); // unknown
1260                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1261                _3ewa->ReadInt16(); // unknown
1262                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1263                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1264                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1265                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1266                else                                       DimensionBypass = dim_bypass_ctrl_none;
1267                uint8_t pan = _3ewa->ReadUint8();
1268                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1269                SelfMask = _3ewa->ReadInt8() & 0x01;
1270                _3ewa->ReadInt8(); // unknown
1271                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1272                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1273                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1274                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1275                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1276                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1277                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1278                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1279                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1280                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1281                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1282                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1283                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1284                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1285                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1286                                                            : vcf_res_ctrl_none;
1287                uint16_t eg3depth = _3ewa->ReadUint16();
1288                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1289                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1290                _3ewa->ReadInt16(); // unknown
1291                ChannelOffset = _3ewa->ReadUint8() / 4;
1292                uint8_t regoptions = _3ewa->ReadUint8();
1293                MSDecode           = regoptions & 0x01; // bit 0
1294                SustainDefeat      = regoptions & 0x02; // bit 1
1295                _3ewa->ReadInt16(); // unknown
1296                VelocityUpperLimit = _3ewa->ReadInt8();
1297                _3ewa->ReadInt8(); // unknown
1298                _3ewa->ReadInt16(); // unknown
1299                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1300                _3ewa->ReadInt8(); // unknown
1301                _3ewa->ReadInt8(); // unknown
1302                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1303                uint8_t vcfcutoff = _3ewa->ReadUint8();
1304                VCFEnabled = vcfcutoff & 0x80; // bit 7
1305                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1306                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1307                uint8_t vcfvelscale = _3ewa->ReadUint8();
1308                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1309                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1310                _3ewa->ReadInt8(); // unknown
1311                uint8_t vcfresonance = _3ewa->ReadUint8();
1312                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1313                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1314                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1315                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1316                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1317                uint8_t vcfvelocity = _3ewa->ReadUint8();
1318                VCFVelocityDynamicRange = vcfvelocity % 5;
1319                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1320                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1321                if (VCFType == vcf_type_lowpass) {
1322                    if (lfo3ctrl & 0x40) // bit 6
1323                        VCFType = vcf_type_lowpassturbo;
1324                }
1325            } else { // '3ewa' chunk does not exist yet
1326                // use default values
1327                LFO3Frequency                   = 1.0;
1328                EG3Attack                       = 0.0;
1329                LFO1InternalDepth               = 0;
1330                LFO3InternalDepth               = 0;
1331                LFO1ControlDepth                = 0;
1332                LFO3ControlDepth                = 0;
1333                EG1Attack                       = 0.0;
1334                EG1Decay1                       = 0.0;
1335                EG1Sustain                      = 0;
1336                EG1Release                      = 0.0;
1337                EG1Controller.type              = eg1_ctrl_t::type_none;
1338                EG1Controller.controller_number = 0;
1339                EG1ControllerInvert             = false;
1340                EG1ControllerAttackInfluence    = 0;
1341                EG1ControllerDecayInfluence     = 0;
1342                EG1ControllerReleaseInfluence   = 0;
1343                EG2Controller.type              = eg2_ctrl_t::type_none;
1344                EG2Controller.controller_number = 0;
1345                EG2ControllerInvert             = false;
1346                EG2ControllerAttackInfluence    = 0;
1347                EG2ControllerDecayInfluence     = 0;
1348                EG2ControllerReleaseInfluence   = 0;
1349                LFO1Frequency                   = 1.0;
1350                EG2Attack                       = 0.0;
1351                EG2Decay1                       = 0.0;
1352                EG2Sustain                      = 0;
1353                EG2Release                      = 0.0;
1354                LFO2ControlDepth                = 0;
1355                LFO2Frequency                   = 1.0;
1356                LFO2InternalDepth               = 0;
1357                EG1Decay2                       = 0.0;
1358                EG1InfiniteSustain              = false;
1359                EG1PreAttack                    = 1000;
1360                EG2Decay2                       = 0.0;
1361                EG2InfiniteSustain              = false;
1362                EG2PreAttack                    = 1000;
1363                VelocityResponseCurve           = curve_type_nonlinear;
1364                VelocityResponseDepth           = 3;
1365                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1366                ReleaseVelocityResponseDepth    = 3;
1367                VelocityResponseCurveScaling    = 32;
1368                AttenuationControllerThreshold  = 0;
1369                SampleStartOffset               = 0;
1370                PitchTrack                      = true;
1371                DimensionBypass                 = dim_bypass_ctrl_none;
1372                Pan                             = 0;
1373                SelfMask                        = true;
1374                LFO3Controller                  = lfo3_ctrl_modwheel;
1375                LFO3Sync                        = false;
1376                InvertAttenuationController     = false;
1377                AttenuationController.type      = attenuation_ctrl_t::type_none;
1378                AttenuationController.controller_number = 0;
1379                LFO2Controller                  = lfo2_ctrl_internal;
1380                LFO2FlipPhase                   = false;
1381                LFO2Sync                        = false;
1382                LFO1Controller                  = lfo1_ctrl_internal;
1383                LFO1FlipPhase                   = false;
1384                LFO1Sync                        = false;
1385                VCFResonanceController          = vcf_res_ctrl_none;
1386                EG3Depth                        = 0;
1387                ChannelOffset                   = 0;
1388                MSDecode                        = false;
1389                SustainDefeat                   = false;
1390                VelocityUpperLimit              = 0;
1391                ReleaseTriggerDecay             = 0;
1392                EG1Hold                         = false;
1393                VCFEnabled                      = false;
1394                VCFCutoff                       = 0;
1395                VCFCutoffController             = vcf_cutoff_ctrl_none;
1396                VCFCutoffControllerInvert       = false;
1397                VCFVelocityScale                = 0;
1398                VCFResonance                    = 0;
1399                VCFResonanceDynamic             = false;
1400                VCFKeyboardTracking             = false;
1401                VCFKeyboardTrackingBreakpoint   = 0;
1402                VCFVelocityDynamicRange         = 0x04;
1403                VCFVelocityCurve                = curve_type_linear;
1404                VCFType                         = vcf_type_lowpass;
1405            }
1406    
1407            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1408                                                         VelocityResponseDepth,
1409                                                         VelocityResponseCurveScaling);
1410    
1411            curve_type_t curveType = ReleaseVelocityResponseCurve;
1412            uint8_t depth = ReleaseVelocityResponseDepth;
1413    
1414            // this models a strange behaviour or bug in GSt: two of the
1415            // velocity response curves for release time are not used even
1416            // if specified, instead another curve is chosen.
1417            if ((curveType == curve_type_nonlinear && depth == 0) ||
1418                (curveType == curve_type_special   && depth == 4)) {
1419                curveType = curve_type_nonlinear;
1420                depth = 3;
1421            }
1422            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1423    
1424            curveType = VCFVelocityCurve;
1425            depth = VCFVelocityDynamicRange;
1426    
1427            // even stranger GSt: two of the velocity response curves for
1428            // filter cutoff are not used, instead another special curve
1429            // is chosen. This curve is not used anywhere else.
1430            if ((curveType == curve_type_nonlinear && depth == 0) ||
1431                (curveType == curve_type_special   && depth == 4)) {
1432                curveType = curve_type_special;
1433                depth = 5;
1434          }          }
1435          else {          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1436              VelocityResponseCurve = curve_type_unknown;                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1437              VelocityResponseDepth = 0;  
1438            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1439            VelocityTable = 0;
1440        }
1441    
1442        /**
1443         * Apply dimension region settings to the respective RIFF chunks. You
1444         * have to call File::Save() to make changes persistent.
1445         *
1446         * Usually there is absolutely no need to call this method explicitly.
1447         * It will be called automatically when File::Save() was called.
1448         */
1449        void DimensionRegion::UpdateChunks() {
1450            // first update base class's chunk
1451            DLS::Sampler::UpdateChunks();
1452    
1453            // make sure '3ewa' chunk exists
1454            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1455            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1456            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1457    
1458            // update '3ewa' chunk with DimensionRegion's current settings
1459    
1460            const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1461            memcpy(&pData[0], &unknown, 4);
1462    
1463            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1464            memcpy(&pData[4], &lfo3freq, 4);
1465    
1466            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1467            memcpy(&pData[4], &eg3attack, 4);
1468    
1469            // next 2 bytes unknown
1470    
1471            memcpy(&pData[10], &LFO1InternalDepth, 2);
1472    
1473            // next 2 bytes unknown
1474    
1475            memcpy(&pData[14], &LFO3InternalDepth, 2);
1476    
1477            // next 2 bytes unknown
1478    
1479            memcpy(&pData[18], &LFO1ControlDepth, 2);
1480    
1481            // next 2 bytes unknown
1482    
1483            memcpy(&pData[22], &LFO3ControlDepth, 2);
1484    
1485            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1486            memcpy(&pData[24], &eg1attack, 4);
1487    
1488            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1489            memcpy(&pData[28], &eg1decay1, 4);
1490    
1491            // next 2 bytes unknown
1492    
1493            memcpy(&pData[34], &EG1Sustain, 2);
1494    
1495            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1496            memcpy(&pData[36], &eg1release, 4);
1497    
1498            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1499            memcpy(&pData[40], &eg1ctl, 1);
1500    
1501            const uint8_t eg1ctrloptions =
1502                (EG1ControllerInvert) ? 0x01 : 0x00 |
1503                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1504                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1505                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1506            memcpy(&pData[41], &eg1ctrloptions, 1);
1507    
1508            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1509            memcpy(&pData[42], &eg2ctl, 1);
1510    
1511            const uint8_t eg2ctrloptions =
1512                (EG2ControllerInvert) ? 0x01 : 0x00 |
1513                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1514                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1515                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1516            memcpy(&pData[43], &eg2ctrloptions, 1);
1517    
1518            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1519            memcpy(&pData[44], &lfo1freq, 4);
1520    
1521            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1522            memcpy(&pData[48], &eg2attack, 4);
1523    
1524            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1525            memcpy(&pData[52], &eg2decay1, 4);
1526    
1527            // next 2 bytes unknown
1528    
1529            memcpy(&pData[58], &EG2Sustain, 2);
1530    
1531            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1532            memcpy(&pData[60], &eg2release, 4);
1533    
1534            // next 2 bytes unknown
1535    
1536            memcpy(&pData[66], &LFO2ControlDepth, 2);
1537    
1538            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1539            memcpy(&pData[68], &lfo2freq, 4);
1540    
1541            // next 2 bytes unknown
1542    
1543            memcpy(&pData[72], &LFO2InternalDepth, 2);
1544    
1545            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1546            memcpy(&pData[74], &eg1decay2, 4);
1547    
1548            // next 2 bytes unknown
1549    
1550            memcpy(&pData[80], &EG1PreAttack, 2);
1551    
1552            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1553            memcpy(&pData[82], &eg2decay2, 4);
1554    
1555            // next 2 bytes unknown
1556    
1557            memcpy(&pData[88], &EG2PreAttack, 2);
1558    
1559            {
1560                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1561                uint8_t velocityresponse = VelocityResponseDepth;
1562                switch (VelocityResponseCurve) {
1563                    case curve_type_nonlinear:
1564                        break;
1565                    case curve_type_linear:
1566                        velocityresponse += 5;
1567                        break;
1568                    case curve_type_special:
1569                        velocityresponse += 10;
1570                        break;
1571                    case curve_type_unknown:
1572                    default:
1573                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1574                }
1575                memcpy(&pData[90], &velocityresponse, 1);
1576          }          }
1577          uint8_t releasevelocityresponse = _3ewa->ReadUint8();  
1578          if (releasevelocityresponse < 5) {          {
1579              ReleaseVelocityResponseCurve = curve_type_nonlinear;              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1580              ReleaseVelocityResponseDepth = releasevelocityresponse;              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1581          }              switch (ReleaseVelocityResponseCurve) {
1582          else if (releasevelocityresponse < 10) {                  case curve_type_nonlinear:
1583              ReleaseVelocityResponseCurve = curve_type_linear;                      break;
1584              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  case curve_type_linear:
1585          }                      releasevelocityresponse += 5;
1586          else if (releasevelocityresponse < 15) {                      break;
1587              ReleaseVelocityResponseCurve = curve_type_special;                  case curve_type_special:
1588              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;                      releasevelocityresponse += 10;
1589                        break;
1590                    case curve_type_unknown:
1591                    default:
1592                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1593                }
1594                memcpy(&pData[91], &releasevelocityresponse, 1);
1595          }          }
1596          else {  
1597              ReleaseVelocityResponseCurve = curve_type_unknown;          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1598              ReleaseVelocityResponseDepth = 0;  
1599            memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1600    
1601            // next 4 bytes unknown
1602    
1603            memcpy(&pData[98], &SampleStartOffset, 2);
1604    
1605            // next 2 bytes unknown
1606    
1607            {
1608                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1609                switch (DimensionBypass) {
1610                    case dim_bypass_ctrl_94:
1611                        pitchTrackDimensionBypass |= 0x10;
1612                        break;
1613                    case dim_bypass_ctrl_95:
1614                        pitchTrackDimensionBypass |= 0x20;
1615                        break;
1616                    case dim_bypass_ctrl_none:
1617                        //FIXME: should we set anything here?
1618                        break;
1619                    default:
1620                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1621                }
1622                memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1623            }
1624    
1625            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1626            memcpy(&pData[103], &pan, 1);
1627    
1628            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1629            memcpy(&pData[104], &selfmask, 1);
1630    
1631            // next byte unknown
1632    
1633            {
1634                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1635                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1636                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1637                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1638                memcpy(&pData[106], &lfo3ctrl, 1);
1639            }
1640    
1641            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1642            memcpy(&pData[107], &attenctl, 1);
1643    
1644            {
1645                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1646                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1647                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1648                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1649                memcpy(&pData[108], &lfo2ctrl, 1);
1650            }
1651    
1652            {
1653                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1654                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1655                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1656                if (VCFResonanceController != vcf_res_ctrl_none)
1657                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1658                memcpy(&pData[109], &lfo1ctrl, 1);
1659          }          }
1660          VelocityResponseCurveScaling = _3ewa->ReadUint8();  
1661          AttenuationControllerThreshold = _3ewa->ReadInt8();          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1662          _3ewa->ReadInt32(); // unknown                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1663          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();          memcpy(&pData[110], &eg3depth, 1);
1664          _3ewa->ReadInt16(); // unknown  
1665          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          // next 2 bytes unknown
1666          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1667          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          const uint8_t channeloffset = ChannelOffset * 4;
1668          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;          memcpy(&pData[113], &channeloffset, 1);
1669          else                                       DimensionBypass = dim_bypass_ctrl_none;  
1670          uint8_t pan = _3ewa->ReadUint8();          {
1671          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit              uint8_t regoptions = 0;
1672          SelfMask = _3ewa->ReadInt8() & 0x01;              if (MSDecode)      regoptions |= 0x01; // bit 0
1673          _3ewa->ReadInt8(); // unknown              if (SustainDefeat) regoptions |= 0x02; // bit 1
1674          uint8_t lfo3ctrl = _3ewa->ReadUint8();              memcpy(&pData[114], &regoptions, 1);
         LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits  
         LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
         InvertAttenuationController = lfo3ctrl & 0x80; // bit 7  
         AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));  
         uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
         LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits  
         LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7  
         LFO2Sync               = lfo2ctrl & 0x20; // bit 5  
         bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6  
         uint8_t lfo1ctrl       = _3ewa->ReadUint8();  
         LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits  
         LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7  
         LFO1Sync               = lfo1ctrl & 0x40; // bit 6  
         VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))  
                                                     : vcf_res_ctrl_none;  
         uint16_t eg3depth = _3ewa->ReadUint16();  
         EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */  
                                       : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */  
         _3ewa->ReadInt16(); // unknown  
         ChannelOffset = _3ewa->ReadUint8() / 4;  
         uint8_t regoptions = _3ewa->ReadUint8();  
         MSDecode           = regoptions & 0x01; // bit 0  
         SustainDefeat      = regoptions & 0x02; // bit 1  
         _3ewa->ReadInt16(); // unknown  
         VelocityUpperLimit = _3ewa->ReadInt8();  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt16(); // unknown  
         ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay  
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt8(); // unknown  
         EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
         uint8_t vcfcutoff = _3ewa->ReadUint8();  
         VCFEnabled = vcfcutoff & 0x80; // bit 7  
         VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits  
         VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());  
         VCFVelocityScale = _3ewa->ReadUint8();  
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
1675          }          }
1676    
1677          // 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
1678          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;  
1679            memcpy(&pData[117], &VelocityUpperLimit, 1);
1680    
1681            // next 3 bytes unknown
1682    
1683            memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1684    
1685            // next 2 bytes unknown
1686    
1687            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1688            memcpy(&pData[124], &eg1hold, 1);
1689    
1690            const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1691                                      (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */
1692            memcpy(&pData[125], &vcfcutoff, 1);
1693    
1694            memcpy(&pData[126], &VCFCutoffController, 1);
1695    
1696            const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1697                                        (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1698            memcpy(&pData[127], &vcfvelscale, 1);
1699    
1700            // next byte unknown
1701    
1702            const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1703                                         (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1704            memcpy(&pData[129], &vcfresonance, 1);
1705    
1706            const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1707                                          (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1708            memcpy(&pData[130], &vcfbreakpoint, 1);
1709    
1710            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1711                                        VCFVelocityCurve * 5;
1712            memcpy(&pData[131], &vcfvelocity, 1);
1713    
1714            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1715            memcpy(&pData[132], &vcftype, 1);
1716        }
1717    
1718        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1719        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1720        {
1721            double* table;
1722            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1723          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1724              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1725          }          }
1726          else {          else {
1727              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1728                  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  
1729          }          }
1730            return table;
1731      }      }
1732    
1733      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1187  namespace gig { namespace { Line 1848  namespace gig { namespace {
1848          return decodedcontroller;          return decodedcontroller;
1849      }      }
1850    
1851        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1852            _lev_ctrl_t encodedcontroller;
1853            switch (DecodedController.type) {
1854                // special controller
1855                case leverage_ctrl_t::type_none:
1856                    encodedcontroller = _lev_ctrl_none;
1857                    break;
1858                case leverage_ctrl_t::type_velocity:
1859                    encodedcontroller = _lev_ctrl_velocity;
1860                    break;
1861                case leverage_ctrl_t::type_channelaftertouch:
1862                    encodedcontroller = _lev_ctrl_channelaftertouch;
1863                    break;
1864    
1865                // ordinary MIDI control change controller
1866                case leverage_ctrl_t::type_controlchange:
1867                    switch (DecodedController.controller_number) {
1868                        case 1:
1869                            encodedcontroller = _lev_ctrl_modwheel;
1870                            break;
1871                        case 2:
1872                            encodedcontroller = _lev_ctrl_breath;
1873                            break;
1874                        case 4:
1875                            encodedcontroller = _lev_ctrl_foot;
1876                            break;
1877                        case 12:
1878                            encodedcontroller = _lev_ctrl_effect1;
1879                            break;
1880                        case 13:
1881                            encodedcontroller = _lev_ctrl_effect2;
1882                            break;
1883                        case 16:
1884                            encodedcontroller = _lev_ctrl_genpurpose1;
1885                            break;
1886                        case 17:
1887                            encodedcontroller = _lev_ctrl_genpurpose2;
1888                            break;
1889                        case 18:
1890                            encodedcontroller = _lev_ctrl_genpurpose3;
1891                            break;
1892                        case 19:
1893                            encodedcontroller = _lev_ctrl_genpurpose4;
1894                            break;
1895                        case 5:
1896                            encodedcontroller = _lev_ctrl_portamentotime;
1897                            break;
1898                        case 64:
1899                            encodedcontroller = _lev_ctrl_sustainpedal;
1900                            break;
1901                        case 65:
1902                            encodedcontroller = _lev_ctrl_portamento;
1903                            break;
1904                        case 66:
1905                            encodedcontroller = _lev_ctrl_sostenutopedal;
1906                            break;
1907                        case 67:
1908                            encodedcontroller = _lev_ctrl_softpedal;
1909                            break;
1910                        case 80:
1911                            encodedcontroller = _lev_ctrl_genpurpose5;
1912                            break;
1913                        case 81:
1914                            encodedcontroller = _lev_ctrl_genpurpose6;
1915                            break;
1916                        case 82:
1917                            encodedcontroller = _lev_ctrl_genpurpose7;
1918                            break;
1919                        case 83:
1920                            encodedcontroller = _lev_ctrl_genpurpose8;
1921                            break;
1922                        case 91:
1923                            encodedcontroller = _lev_ctrl_effect1depth;
1924                            break;
1925                        case 92:
1926                            encodedcontroller = _lev_ctrl_effect2depth;
1927                            break;
1928                        case 93:
1929                            encodedcontroller = _lev_ctrl_effect3depth;
1930                            break;
1931                        case 94:
1932                            encodedcontroller = _lev_ctrl_effect4depth;
1933                            break;
1934                        case 95:
1935                            encodedcontroller = _lev_ctrl_effect5depth;
1936                            break;
1937                        default:
1938                            throw gig::Exception("leverage controller number is not supported by the gig format");
1939                    }
1940                default:
1941                    throw gig::Exception("Unknown leverage controller type.");
1942            }
1943            return encodedcontroller;
1944        }
1945    
1946      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
1947          Instances--;          Instances--;
1948          if (!Instances) {          if (!Instances) {
# Line 1200  namespace gig { namespace { Line 1956  namespace gig { namespace {
1956              delete pVelocityTables;              delete pVelocityTables;
1957              pVelocityTables = NULL;              pVelocityTables = NULL;
1958          }          }
1959            if (VelocityTable) delete[] VelocityTable;
1960      }      }
1961    
1962      /**      /**
# Line 1217  namespace gig { namespace { Line 1974  namespace gig { namespace {
1974          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1975      }      }
1976    
1977        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1978            return pVelocityReleaseTable[MIDIKeyVelocity];
1979        }
1980    
1981        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1982            return pVelocityCutoffTable[MIDIKeyVelocity];
1983        }
1984    
1985      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) {
1986    
1987          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1250  namespace gig { namespace { Line 2015  namespace gig { namespace {
2015          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,
2016                               127, 127 };                               127, 127 };
2017    
2018            // this is only used by the VCF velocity curve
2019            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2020                                 91, 127, 127, 127 };
2021    
2022          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2023                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2024                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2025    
2026          double* const table = new double[128];          double* const table = new double[128];
2027    
# Line 1304  namespace gig { namespace { Line 2073  namespace gig { namespace {
2073              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2074                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2075                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2076                    _3lnk->ReadUint8(); // probably the position of the dimension
2077                    _3lnk->ReadUint8(); // unknown
2078                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2079                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2080                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2081                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2082                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2083                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2084                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2085                  }                  }
2086                  else { // active dimension                  else { // active dimension
2087                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2088                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2089                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2090                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2091                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2092                                                             dimension == dimension_releasetrigger) ? split_type_bit                                                             dimension == dimension_releasetrigger ||
2093                                                                                                    : split_type_normal;                                                             dimension == dimension_keyboard ||
2094                      pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point                                                             dimension == dimension_roundrobin ||
2095                                                               dimension == dimension_random) ? split_type_bit
2096                                                                                              : split_type_normal;
2097                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2098                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2099                                                                                     : 0;                                                                                     : 0;
2100                      Dimensions++;                      Dimensions++;
2101    
2102                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2103                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2104                  }                  }
2105                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2106              }              }
2107                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2108    
2109              // check velocity dimension (if there is one) for custom defined zone ranges              // if there's a velocity dimension and custom velocity zone splits are used,
2110              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2111                  dimension_def_t* pDimDef = pDimensionDefinitions + i;              UpdateVelocityTable();
                 if (pDimDef->dimension == dimension_velocity) {  
                     if (pDimensionRegions[0]->VelocityUpperLimit == 0) {  
                         // no custom defined ranges  
                         pDimDef->split_type = split_type_normal;  
                         pDimDef->ranges     = NULL;  
                     }  
                     else { // custom defined ranges  
                         pDimDef->split_type = split_type_customvelocity;  
                         pDimDef->ranges     = new range_t[pDimDef->zones];  
                         uint8_t bits[8] = { 0 };  
                         int previousUpperLimit = -1;  
                         for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {  
                             bits[i] = velocityZone;  
                             DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);  
   
                             pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;  
                             pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;  
                             previousUpperLimit = pDimDef->ranges[velocityZone].high;  
                             // fill velocity table  
                             for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {  
                                 VelocityTable[i] = velocityZone;  
                             }  
                         }  
                     }  
                 }  
             }  
2112    
2113              // jump to start of the wave pool indices (if not already there)              // jump to start of the wave pool indices (if not already there)
             File* file = (File*) GetParent()->GetParent();  
2114              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2115                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2116              else              else
# Line 1375  namespace gig { namespace { Line 2122  namespace gig { namespace {
2122                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2123              }              }
2124          }          }
2125          else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2126            // make sure there is at least one dimension region
2127            if (!DimensionRegions) {
2128                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2129                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2130                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2131                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2132                DimensionRegions = 1;
2133            }
2134        }
2135    
2136        /**
2137         * Apply Region settings and all its DimensionRegions to the respective
2138         * RIFF chunks. You have to call File::Save() to make changes persistent.
2139         *
2140         * Usually there is absolutely no need to call this method explicitly.
2141         * It will be called automatically when File::Save() was called.
2142         *
2143         * @throws gig::Exception if samples cannot be dereferenced
2144         */
2145        void Region::UpdateChunks() {
2146            // first update base class's chunks
2147            DLS::Region::UpdateChunks();
2148    
2149            // update dimension region's chunks
2150            for (int i = 0; i < DimensionRegions; i++) {
2151                pDimensionRegions[i]->UpdateChunks();
2152            }
2153    
2154            File* pFile = (File*) GetParent()->GetParent();
2155            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2156            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2157    
2158            // make sure '3lnk' chunk exists
2159            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2160            if (!_3lnk) {
2161                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2162                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2163            }
2164    
2165            // update dimension definitions in '3lnk' chunk
2166            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2167            for (int i = 0; i < iMaxDimensions; i++) {
2168                pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;
2169                pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2170                // next 2 bytes unknown
2171                pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2172                // next 3 bytes unknown
2173            }
2174    
2175            // update wave pool table in '3lnk' chunk
2176            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2177            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2178                int iWaveIndex = -1;
2179                if (i < DimensionRegions) {
2180                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2181                    File::SampleList::iterator iter = pFile->pSamples->begin();
2182                    File::SampleList::iterator end  = pFile->pSamples->end();
2183                    for (int index = 0; iter != end; ++iter, ++index) {
2184                        if (*iter == pDimensionRegions[i]->pSample) {
2185                            iWaveIndex = index;
2186                            break;
2187                        }
2188                    }
2189                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2190                }
2191                memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2192            }
2193      }      }
2194    
2195      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1394  namespace gig { namespace { Line 2208  namespace gig { namespace {
2208          }          }
2209      }      }
2210    
2211      Region::~Region() {      void Region::UpdateVelocityTable() {
2212          for (uint i = 0; i < Dimensions; i++) {          // get velocity dimension's index
2213              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          int veldim = -1;
2214            for (int i = 0 ; i < Dimensions ; i++) {
2215                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2216                    veldim = i;
2217                    break;
2218                }
2219            }
2220            if (veldim == -1) return;
2221    
2222            int step = 1;
2223            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2224            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2225            int end = step * pDimensionDefinitions[veldim].zones;
2226    
2227            // loop through all dimension regions for all dimensions except the velocity dimension
2228            int dim[8] = { 0 };
2229            for (int i = 0 ; i < DimensionRegions ; i++) {
2230    
2231                if (pDimensionRegions[i]->VelocityUpperLimit) {
2232                    // create the velocity table
2233                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2234                    if (!table) {
2235                        table = new uint8_t[128];
2236                        pDimensionRegions[i]->VelocityTable = table;
2237                    }
2238                    int tableidx = 0;
2239                    int velocityZone = 0;
2240                    for (int k = i ; k < end ; k += step) {
2241                        DimensionRegion *d = pDimensionRegions[k];
2242                        for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2243                        velocityZone++;
2244                    }
2245                } else {
2246                    if (pDimensionRegions[i]->VelocityTable) {
2247                        delete[] pDimensionRegions[i]->VelocityTable;
2248                        pDimensionRegions[i]->VelocityTable = 0;
2249                    }
2250                }
2251    
2252                int j;
2253                int shift = 0;
2254                for (j = 0 ; j < Dimensions ; j++) {
2255                    if (j == veldim) i += skipveldim; // skip velocity dimension
2256                    else {
2257                        dim[j]++;
2258                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2259                        else {
2260                            // skip unused dimension regions
2261                            dim[j] = 0;
2262                            i += ((1 << pDimensionDefinitions[j].bits) -
2263                                  pDimensionDefinitions[j].zones) << shift;
2264                        }
2265                    }
2266                    shift += pDimensionDefinitions[j].bits;
2267                }
2268                if (j == Dimensions) break;
2269            }
2270        }
2271    
2272        /** @brief Einstein would have dreamed of it - create a new dimension.
2273         *
2274         * Creates a new dimension with the dimension definition given by
2275         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2276         * There is a hard limit of dimensions and total amount of "bits" all
2277         * dimensions can have. This limit is dependant to what gig file format
2278         * version this file refers to. The gig v2 (and lower) format has a
2279         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2280         * format has a limit of 8.
2281         *
2282         * @param pDimDef - defintion of the new dimension
2283         * @throws gig::Exception if dimension of the same type exists already
2284         * @throws gig::Exception if amount of dimensions or total amount of
2285         *                        dimension bits limit is violated
2286         */
2287        void Region::AddDimension(dimension_def_t* pDimDef) {
2288            // check if max. amount of dimensions reached
2289            File* file = (File*) GetParent()->GetParent();
2290            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2291            if (Dimensions >= iMaxDimensions)
2292                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2293            // check if max. amount of dimension bits reached
2294            int iCurrentBits = 0;
2295            for (int i = 0; i < Dimensions; i++)
2296                iCurrentBits += pDimensionDefinitions[i].bits;
2297            if (iCurrentBits >= iMaxDimensions)
2298                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2299            const int iNewBits = iCurrentBits + pDimDef->bits;
2300            if (iNewBits > iMaxDimensions)
2301                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2302            // check if there's already a dimensions of the same type
2303            for (int i = 0; i < Dimensions; i++)
2304                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2305                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2306    
2307            // assign definition of new dimension
2308            pDimensionDefinitions[Dimensions] = *pDimDef;
2309    
2310            // create new dimension region(s) for this new dimension
2311            for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2312                //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2313                RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2314                pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2315                DimensionRegions++;
2316            }
2317    
2318            Dimensions++;
2319    
2320            // if this is a layer dimension, update 'Layers' attribute
2321            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2322    
2323            UpdateVelocityTable();
2324        }
2325    
2326        /** @brief Delete an existing dimension.
2327         *
2328         * Deletes the dimension given by \a pDimDef and deletes all respective
2329         * dimension regions, that is all dimension regions where the dimension's
2330         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2331         * for example this would delete all dimension regions for the case(s)
2332         * where the sustain pedal is pressed down.
2333         *
2334         * @param pDimDef - dimension to delete
2335         * @throws gig::Exception if given dimension cannot be found
2336         */
2337        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2338            // get dimension's index
2339            int iDimensionNr = -1;
2340            for (int i = 0; i < Dimensions; i++) {
2341                if (&pDimensionDefinitions[i] == pDimDef) {
2342                    iDimensionNr = i;
2343                    break;
2344                }
2345            }
2346            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2347    
2348            // get amount of bits below the dimension to delete
2349            int iLowerBits = 0;
2350            for (int i = 0; i < iDimensionNr; i++)
2351                iLowerBits += pDimensionDefinitions[i].bits;
2352    
2353            // get amount ot bits above the dimension to delete
2354            int iUpperBits = 0;
2355            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2356                iUpperBits += pDimensionDefinitions[i].bits;
2357    
2358            // delete dimension regions which belong to the given dimension
2359            // (that is where the dimension's bit > 0)
2360            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2361                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2362                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2363                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2364                                        iObsoleteBit << iLowerBits |
2365                                        iLowerBit;
2366                        delete pDimensionRegions[iToDelete];
2367                        pDimensionRegions[iToDelete] = NULL;
2368                        DimensionRegions--;
2369                    }
2370                }
2371            }
2372    
2373            // defrag pDimensionRegions array
2374            // (that is remove the NULL spaces within the pDimensionRegions array)
2375            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2376                if (!pDimensionRegions[iTo]) {
2377                    if (iFrom <= iTo) iFrom = iTo + 1;
2378                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2379                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2380                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2381                        pDimensionRegions[iFrom] = NULL;
2382                    }
2383                }
2384            }
2385    
2386            // 'remove' dimension definition
2387            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2388                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2389          }          }
2390            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2391            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2392            pDimensionDefinitions[Dimensions - 1].zones     = 0;
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() {
2401          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2402              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2403          }          }
# Line 1422  namespace gig { namespace { Line 2422  namespace gig { namespace {
2422       * @see             Dimensions       * @see             Dimensions
2423       */       */
2424      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2425          uint8_t bits[8] = { 0 };          uint8_t bits;
2426            int veldim = -1;
2427            int velbitpos;
2428            int bitpos = 0;
2429            int dimregidx = 0;
2430          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2431              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2432              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2433                  case split_type_normal:                  veldim = i;
2434                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
2435                      break;              } else {
2436                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2437                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2438                      break;                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2439                  case split_type_bit: // the value is already the sought dimension bit number                          break;
2440                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                      case split_type_bit: // the value is already the sought dimension bit number
2441                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2442                      break;                          bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2443              }                          break;
2444                    }
2445                    dimregidx |= bits << bitpos;
2446                }
2447                bitpos += pDimensionDefinitions[i].bits;
2448            }
2449            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2450            if (veldim != -1) {
2451                // (dimreg is now the dimension region for the lowest velocity)
2452                if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2453                    bits = dimreg->VelocityTable[DimValues[veldim]];
2454                else // normal split type
2455                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2456    
2457                dimregidx |= bits << velbitpos;
2458                dimreg = pDimensionRegions[dimregidx];
2459          }          }
2460          return GetDimensionRegionByBit(bits);          return dimreg;
2461      }      }
2462    
2463      /**      /**
# Line 1475  namespace gig { namespace { Line 2494  namespace gig { namespace {
2494          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));          else         return static_cast<gig::Sample*>(pSample = GetSampleFromWavePool(WavePoolTableIndex));
2495      }      }
2496    
2497      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2498          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2499          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2500          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2501          Sample* sample = file->GetFirstSample();          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2502            Sample* sample = file->GetFirstSample(pProgress);
2503          while (sample) {          while (sample) {
2504              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2505                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);
2506              sample = file->GetNextSample();              sample = file->GetNextSample();
2507          }          }
2508          return NULL;          return NULL;
# Line 1492  namespace gig { namespace { Line 2513  namespace gig { namespace {
2513  // *************** Instrument ***************  // *************** Instrument ***************
2514  // *  // *
2515    
2516      Instrument::Instrument(File* pFile, RIFF::List* insList) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2517          // Initialization          // Initialization
2518          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2519    
2520          // Loading          // Loading
2521          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1511  namespace gig { namespace { Line 2531  namespace gig { namespace {
2531                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2532                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2533              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2534          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2535    
2536            if (!pRegions) pRegions = new RegionList;
2537          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2538          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2539          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2540          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              while (rgn) {
2541          RIFF::List* rgn = lrgn->GetFirstSubList();                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2542          unsigned int iRegion = 0;                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2543          while (rgn) {                      pRegions->push_back(new Region(this, rgn));
2544              if (rgn->GetListType() == LIST_TYPE_RGN) {                  }
2545                  pRegions[iRegion] = new Region(this, rgn);                  rgn = lrgn->GetNextSubList();
                 iRegion++;  
             }  
             rgn = lrgn->GetNextSubList();  
         }  
   
         // Creating Region Key Table for fast lookup  
         for (uint iReg = 0; iReg < Regions; iReg++) {  
             for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {  
                 RegionKeyTable[iKey] = pRegions[iReg];  
2546              }              }
2547                // Creating Region Key Table for fast lookup
2548                UpdateRegionKeyTable();
2549          }          }
2550    
2551            __notify_progress(pProgress, 1.0f); // notify done
2552      }      }
2553    
2554      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2555          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2556              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2557                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2558                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2559                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2560                    RegionKeyTable[iKey] = pRegion;
2561              }              }
2562          }          }
2563          if (pRegions) delete[] pRegions;      }
2564    
2565        Instrument::~Instrument() {
2566        }
2567    
2568        /**
2569         * Apply Instrument with all its Regions to the respective RIFF chunks.
2570         * You have to call File::Save() to make changes persistent.
2571         *
2572         * Usually there is absolutely no need to call this method explicitly.
2573         * It will be called automatically when File::Save() was called.
2574         *
2575         * @throws gig::Exception if samples cannot be dereferenced
2576         */
2577        void Instrument::UpdateChunks() {
2578            // first update base classes' chunks
2579            DLS::Instrument::UpdateChunks();
2580    
2581            // update Regions' chunks
2582            {
2583                RegionList::iterator iter = pRegions->begin();
2584                RegionList::iterator end  = pRegions->end();
2585                for (; iter != end; ++iter)
2586                    (*iter)->UpdateChunks();
2587            }
2588    
2589            // make sure 'lart' RIFF list chunk exists
2590            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2591            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2592            // make sure '3ewg' RIFF chunk exists
2593            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2594            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2595            // update '3ewg' RIFF chunk
2596            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2597            memcpy(&pData[0], &EffectSend, 2);
2598            memcpy(&pData[2], &Attenuation, 4);
2599            memcpy(&pData[6], &FineTune, 2);
2600            memcpy(&pData[8], &PitchbendRange, 2);
2601            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2602                                        DimensionKeyRange.low << 1;
2603            memcpy(&pData[10], &dimkeystart, 1);
2604            memcpy(&pData[11], &DimensionKeyRange.high, 1);
2605      }      }
2606    
2607      /**      /**
# Line 1554  namespace gig { namespace { Line 2612  namespace gig { namespace {
2612       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2613       */       */
2614      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2615          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2616          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2617    
2618          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2619              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2620                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1571  namespace gig { namespace { Line 2630  namespace gig { namespace {
2630       * @see      GetNextRegion()       * @see      GetNextRegion()
2631       */       */
2632      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2633          if (!Regions) return NULL;          if (!pRegions) return NULL;
2634          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2635          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2636      }      }
2637    
2638      /**      /**
# Line 1585  namespace gig { namespace { Line 2644  namespace gig { namespace {
2644       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2645       */       */
2646      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2647          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2648          return pRegions[RegionIndex++];          RegionsIterator++;
2649            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2650        }
2651    
2652        Region* Instrument::AddRegion() {
2653            // create new Region object (and its RIFF chunks)
2654            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2655            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2656            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2657            Region* pNewRegion = new Region(this, rgn);
2658            pRegions->push_back(pNewRegion);
2659            Regions = pRegions->size();
2660            // update Region key table for fast lookup
2661            UpdateRegionKeyTable();
2662            // done
2663            return pNewRegion;
2664        }
2665    
2666        void Instrument::DeleteRegion(Region* pRegion) {
2667            if (!pRegions) return;
2668            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2669            // update Region key table for fast lookup
2670            UpdateRegionKeyTable();
2671      }      }
2672    
2673    
# Line 1594  namespace gig { namespace { Line 2675  namespace gig { namespace {
2675  // *************** File ***************  // *************** File ***************
2676  // *  // *
2677    
2678      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File() : DLS::File() {
         pSamples     = NULL;  
         pInstruments = NULL;  
2679      }      }
2680    
2681      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;  
         }  
2682      }      }
2683    
2684      Sample* File::GetFirstSample() {      Sample* File::GetFirstSample(progress_t* pProgress) {
2685          if (!pSamples) LoadSamples();          if (!pSamples) LoadSamples(pProgress);
2686          if (!pSamples) return NULL;          if (!pSamples) return NULL;
2687          SamplesIterator = pSamples->begin();          SamplesIterator = pSamples->begin();
2688          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
# Line 1636  namespace gig { namespace { Line 2694  namespace gig { namespace {
2694          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2695      }      }
2696    
2697        /** @brief Add a new sample.
2698         *
2699         * This will create a new Sample object for the gig file. You have to
2700         * call Save() to make this persistent to the file.
2701         *
2702         * @returns pointer to new Sample object
2703         */
2704        Sample* File::AddSample() {
2705           if (!pSamples) LoadSamples();
2706           __ensureMandatoryChunksExist();
2707           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2708           // create new Sample object and its respective 'wave' list chunk
2709           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2710           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2711           pSamples->push_back(pSample);
2712           return pSample;
2713        }
2714    
2715        /** @brief Delete a sample.
2716         *
2717         * This will delete the given Sample object from the gig file. You have
2718         * to call Save() to make this persistent to the file.
2719         *
2720         * @param pSample - sample to delete
2721         * @throws gig::Exception if given sample could not be found
2722         */
2723        void File::DeleteSample(Sample* pSample) {
2724            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2725            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2726            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2727            pSamples->erase(iter);
2728            delete pSample;
2729        }
2730    
2731      void File::LoadSamples() {      void File::LoadSamples() {
2732          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          LoadSamples(NULL);
2733          if (wvpl) {      }
2734              unsigned long wvplFileOffset = wvpl->GetFilePos();  
2735              RIFF::List* wave = wvpl->GetFirstSubList();      void File::LoadSamples(progress_t* pProgress) {
2736              while (wave) {          if (!pSamples) pSamples = new SampleList;
2737                  if (wave->GetListType() == LIST_TYPE_WAVE) {  
2738                      if (!pSamples) pSamples = new SampleList;          RIFF::File* file = pRIFF;
2739                      unsigned long waveFileOffset = wave->GetFilePos();  
2740                      pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));          // just for progress calculation
2741            int iSampleIndex  = 0;
2742            int iTotalSamples = WavePoolCount;
2743    
2744            // check if samples should be loaded from extension files
2745            int lastFileNo = 0;
2746            for (int i = 0 ; i < WavePoolCount ; i++) {
2747                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2748            }
2749            String name(pRIFF->GetFileName());
2750            int nameLen = name.length();
2751            char suffix[6];
2752            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2753    
2754            for (int fileNo = 0 ; ; ) {
2755                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2756                if (wvpl) {
2757                    unsigned long wvplFileOffset = wvpl->GetFilePos();
2758                    RIFF::List* wave = wvpl->GetFirstSubList();
2759                    while (wave) {
2760                        if (wave->GetListType() == LIST_TYPE_WAVE) {
2761                            // notify current progress
2762                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2763                            __notify_progress(pProgress, subprogress);
2764    
2765                            unsigned long waveFileOffset = wave->GetFilePos();
2766                            pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2767    
2768                            iSampleIndex++;
2769                        }
2770                        wave = wvpl->GetNextSubList();
2771                  }                  }
2772                  wave = wvpl->GetNextSubList();  
2773              }                  if (fileNo == lastFileNo) break;
2774    
2775                    // open extension file (*.gx01, *.gx02, ...)
2776                    fileNo++;
2777                    sprintf(suffix, ".gx%02d", fileNo);
2778                    name.replace(nameLen, 5, suffix);
2779                    file = new RIFF::File(name);
2780                    ExtensionFiles.push_back(file);
2781                } else break;
2782          }          }
2783          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2784            __notify_progress(pProgress, 1.0); // notify done
2785      }      }
2786    
2787      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
2788          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2789          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2790          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2791          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2792      }      }
2793    
2794      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2795          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2796          InstrumentsIterator++;          InstrumentsIterator++;
2797          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2798      }      }
2799    
2800      /**      /**
2801       * Returns the instrument with the given index.       * Returns the instrument with the given index.
2802       *       *
2803         * @param index     - number of the sought instrument (0..n)
2804         * @param pProgress - optional: callback function for progress notification
2805       * @returns  sought instrument or NULL if there's no such instrument       * @returns  sought instrument or NULL if there's no such instrument
2806       */       */
2807      Instrument* File::GetInstrument(uint index) {      Instrument* File::GetInstrument(uint index, progress_t* pProgress) {
2808          if (!pInstruments) LoadInstruments();          if (!pInstruments) {
2809                // TODO: hack - we simply load ALL samples here, it would have been done in the Region constructor anyway (ATM)
2810    
2811                // sample loading subtask
2812                progress_t subprogress;
2813                __divide_progress(pProgress, &subprogress, 3.0f, 0.0f); // randomly schedule 33% for this subtask
2814                __notify_progress(&subprogress, 0.0f);
2815                GetFirstSample(&subprogress); // now force all samples to be loaded
2816                __notify_progress(&subprogress, 1.0f);
2817    
2818                // instrument loading subtask
2819                if (pProgress && pProgress->callback) {
2820                    subprogress.__range_min = subprogress.__range_max;
2821                    subprogress.__range_max = pProgress->__range_max; // schedule remaining percentage for this subtask
2822                }
2823                __notify_progress(&subprogress, 0.0f);
2824                LoadInstruments(&subprogress);
2825                __notify_progress(&subprogress, 1.0f);
2826            }
2827          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2828          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2829          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2830              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2831              InstrumentsIterator++;              InstrumentsIterator++;
2832          }          }
2833          return NULL;          return NULL;
2834      }      }
2835    
2836        /** @brief Add a new instrument definition.
2837         *
2838         * This will create a new Instrument object for the gig file. You have
2839         * to call Save() to make this persistent to the file.
2840         *
2841         * @returns pointer to new Instrument object
2842         */
2843        Instrument* File::AddInstrument() {
2844           if (!pInstruments) LoadInstruments();
2845           __ensureMandatoryChunksExist();
2846           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2847           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2848           Instrument* pInstrument = new Instrument(this, lstInstr);
2849           pInstruments->push_back(pInstrument);
2850           return pInstrument;
2851        }
2852    
2853        /** @brief Delete an instrument.
2854         *
2855         * This will delete the given Instrument object from the gig file. You
2856         * have to call Save() to make this persistent to the file.
2857         *
2858         * @param pInstrument - instrument to delete
2859         * @throws gig::Excption if given instrument could not be found
2860         */
2861        void File::DeleteInstrument(Instrument* pInstrument) {
2862            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2863            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2864            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2865            pInstruments->erase(iter);
2866            delete pInstrument;
2867        }
2868    
2869      void File::LoadInstruments() {      void File::LoadInstruments() {
2870            LoadInstruments(NULL);
2871        }
2872    
2873        void File::LoadInstruments(progress_t* pProgress) {
2874            if (!pInstruments) pInstruments = new InstrumentList;
2875          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2876          if (lstInstruments) {          if (lstInstruments) {
2877                int iInstrumentIndex = 0;
2878              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();              RIFF::List* lstInstr = lstInstruments->GetFirstSubList();
2879              while (lstInstr) {              while (lstInstr) {
2880                  if (lstInstr->GetListType() == LIST_TYPE_INS) {                  if (lstInstr->GetListType() == LIST_TYPE_INS) {
2881                      if (!pInstruments) pInstruments = new InstrumentList;                      // notify current progress
2882                      pInstruments->push_back(new Instrument(this, lstInstr));                      const float localProgress = (float) iInstrumentIndex / (float) Instruments;
2883                        __notify_progress(pProgress, localProgress);
2884    
2885                        // divide local progress into subprogress for loading current Instrument
2886                        progress_t subprogress;
2887                        __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2888    
2889                        pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2890    
2891                        iInstrumentIndex++;
2892                  }                  }
2893                  lstInstr = lstInstruments->GetNextSubList();                  lstInstr = lstInstruments->GetNextSubList();
2894              }              }
2895                __notify_progress(pProgress, 1.0); // notify done
2896          }          }
         else throw gig::Exception("Mandatory <lins> list chunk not found.");  
2897      }      }
2898    
2899    
# Line 1709  namespace gig { namespace { Line 2908  namespace gig { namespace {
2908          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
2909      }      }
2910    
2911    
2912    // *************** functions ***************
2913    // *
2914    
2915        /**
2916         * Returns the name of this C++ library. This is usually "libgig" of
2917         * course. This call is equivalent to RIFF::libraryName() and
2918         * DLS::libraryName().
2919         */
2920        String libraryName() {
2921            return PACKAGE;
2922        }
2923    
2924        /**
2925         * Returns version of this C++ library. This call is equivalent to
2926         * RIFF::libraryVersion() and DLS::libraryVersion().
2927         */
2928        String libraryVersion() {
2929            return VERSION;
2930        }
2931    
2932  } // namespace gig  } // namespace gig

Legend:
Removed from v.365  
changed lines
  Added in v.864

  ViewVC Help
Powered by ViewVC