/[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 518 by schoenebeck, Sun May 8 16:19:34 2005 UTC revision 1050 by schoenebeck, Fri Mar 2 01:04:45 2007 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26    #include "helper.h"
27    
28    #include <math.h>
29  #include <iostream>  #include <iostream>
30    
31    /// Initial size of the sample buffer which is used for decompression of
32    /// compressed sample wave streams - this value should always be bigger than
33    /// the biggest sample piece expected to be read by the sampler engine,
34    /// otherwise the buffer size will be raised at runtime and thus the buffer
35    /// reallocated which is time consuming and unefficient.
36    #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
37    
38    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
39    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
40    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
41    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
42    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
43    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
44    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
45    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
46    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
47    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
48    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
49    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
50    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
51    
52  namespace gig {  namespace gig {
53    
54  // *************** progress_t ***************  // *************** progress_t ***************
# Line 59  namespace gig { Line 83  namespace gig {
83      }      }
84    
85    
86  // *************** Internal functions for sample decopmression ***************  // *************** Internal functions for sample decompression ***************
87  // *  // *
88    
89  namespace {  namespace {
# Line 87  namespace { Line 111  namespace {
111          return x & 0x800000 ? x - 0x1000000 : x;          return x & 0x800000 ? x - 0x1000000 : x;
112      }      }
113    
114        inline void store24(unsigned char* pDst, int x)
115        {
116            pDst[0] = x;
117            pDst[1] = x >> 8;
118            pDst[2] = x >> 16;
119        }
120    
121      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
122                        int srcStep, int dstStep,                        int srcStep, int dstStep,
123                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
# Line 126  namespace { Line 157  namespace {
157      }      }
158    
159      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
160                        int dstStep, const unsigned char* pSrc, int16_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
161                        unsigned long currentframeoffset,                        unsigned long currentframeoffset,
162                        unsigned long copysamples, int truncatedBits)                        unsigned long copysamples, int truncatedBits)
163      {      {
164          // Note: The 24 bits are truncated to 16 bits for now.          int y, dy, ddy, dddy;
165    
166          // Note: The calculation of the initial value of y is strange  #define GET_PARAMS(params)                      \
167          // and not 100% correct. What should the first two parameters          y    = get24(params);                   \
168          // really be used for? Why are they two? The correct value for          dy   = y - get24((params) + 3);         \
169          // y seems to lie somewhere between the values of the first          ddy  = get24((params) + 6);             \
170          // two parameters.          dddy = get24((params) + 9)
         //  
         // Strange thing #2: The formula in SKIP_ONE gives values for  
         // y that are twice as high as they should be. That's why  
         // COPY_ONE shifts an extra step, and also why y is  
         // initialized with a sum instead of a mean value.  
   
         int y, dy, ddy;  
   
         const int shift = 8 - truncatedBits;  
         const int shift1 = shift + 1;  
   
 #define GET_PARAMS(params)                              \  
         y = (get24(params) + get24((params) + 3));      \  
         dy  = get24((params) + 6);                      \  
         ddy = get24((params) + 9)  
171    
172  #define SKIP_ONE(x)                             \  #define SKIP_ONE(x)                             \
173          ddy -= (x);                             \          dddy -= (x);                            \
174          dy -= ddy;                              \          ddy  -= dddy;                           \
175          y -= dy          dy   =  -dy - ddy;                      \
176            y    += dy
177    
178  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
179          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
180          *pDst = y >> shift1;                    \          store24(pDst, y << truncatedBits);      \
181          pDst += dstStep          pDst += dstStep
182    
183          switch (compressionmode) {          switch (compressionmode) {
184              case 2: // 24 bit uncompressed              case 2: // 24 bit uncompressed
185                  pSrc += currentframeoffset * 3;                  pSrc += currentframeoffset * 3;
186                  while (copysamples) {                  while (copysamples) {
187                      *pDst = get24(pSrc) >> shift;                      store24(pDst, get24(pSrc) << truncatedBits);
188                      pDst += dstStep;                      pDst += dstStep;
189                      pSrc += 3;                      pSrc += 3;
190                      copysamples--;                      copysamples--;
# Line 243  namespace { Line 260  namespace {
260      unsigned int Sample::Instances = 0;      unsigned int Sample::Instances = 0;
261      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
262    
263      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
264         *
265         * Load an existing sample or create a new one. A 'wave' list chunk must
266         * be given to this constructor. In case the given 'wave' list chunk
267         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
268         * format and sample data will be loaded from there, otherwise default
269         * values will be used and those chunks will be created when
270         * File::Save() will be called later on.
271         *
272         * @param pFile          - pointer to gig::File where this sample is
273         *                         located (or will be located)
274         * @param waveList       - pointer to 'wave' list chunk which is (or
275         *                         will be) associated with this sample
276         * @param WavePoolOffset - offset of this sample data from wave pool
277         *                         ('wvpl') list chunk
278         * @param fileNo         - number of an extension file where this sample
279         *                         is located, 0 otherwise
280         */
281        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
282            pInfo->UseFixedLengthStrings = true;
283          Instances++;          Instances++;
284            FileNo = fileNo;
285    
286          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
287          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
288          SampleGroup = _3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
289                pGroup = pFile->GetGroup(iSampleGroup);
290          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          } else { // '3gix' chunk missing
291          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              // by default assigned to that mandatory "Default Group"
292          Manufacturer      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
293          Product           = smpl->ReadInt32();          }
294          SamplePeriod      = smpl->ReadInt32();  
295          MIDIUnityNote     = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
296          FineTune          = smpl->ReadInt32();          if (pCkSmpl) {
297          smpl->Read(&SMPTEFormat, 1, 4);              Manufacturer  = pCkSmpl->ReadInt32();
298          SMPTEOffset       = smpl->ReadInt32();              Product       = pCkSmpl->ReadInt32();
299          Loops             = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
300          smpl->ReadInt32(); // manufByt              MIDIUnityNote = pCkSmpl->ReadInt32();
301          LoopID            = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
302          smpl->Read(&LoopType, 1, 4);              pCkSmpl->Read(&SMPTEFormat, 1, 4);
303          LoopStart         = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
304          LoopEnd           = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
305          LoopFraction      = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
306          LoopPlayCount     = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
307                pCkSmpl->Read(&LoopType, 1, 4);
308                LoopStart     = pCkSmpl->ReadInt32();
309                LoopEnd       = pCkSmpl->ReadInt32();
310                LoopFraction  = pCkSmpl->ReadInt32();
311                LoopPlayCount = pCkSmpl->ReadInt32();
312            } else { // 'smpl' chunk missing
313                // use default values
314                Manufacturer  = 0;
315                Product       = 0;
316                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
317                MIDIUnityNote = 64;
318                FineTune      = 0;
319                SMPTEOffset   = 0;
320                Loops         = 0;
321                LoopID        = 0;
322                LoopStart     = 0;
323                LoopEnd       = 0;
324                LoopFraction  = 0;
325                LoopPlayCount = 0;
326            }
327    
328          FrameTable                 = NULL;          FrameTable                 = NULL;
329          SamplePos                  = 0;          SamplePos                  = 0;
# Line 297  namespace { Line 354  namespace {
354          }          }
355          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
356    
357          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
358        }
359    
360        /**
361         * Apply sample and its settings to the respective RIFF chunks. You have
362         * to call File::Save() to make changes persistent.
363         *
364         * Usually there is absolutely no need to call this method explicitly.
365         * It will be called automatically when File::Save() was called.
366         *
367         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
368         *                        was provided yet
369         * @throws gig::Exception if there is any invalid sample setting
370         */
371        void Sample::UpdateChunks() {
372            // first update base class's chunks
373            DLS::Sample::UpdateChunks();
374    
375            // make sure 'smpl' chunk exists
376            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
377            if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
378            // update 'smpl' chunk
379            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
380            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
381            memcpy(&pData[0], &Manufacturer, 4);
382            memcpy(&pData[4], &Product, 4);
383            memcpy(&pData[8], &SamplePeriod, 4);
384            memcpy(&pData[12], &MIDIUnityNote, 4);
385            memcpy(&pData[16], &FineTune, 4);
386            memcpy(&pData[20], &SMPTEFormat, 4);
387            memcpy(&pData[24], &SMPTEOffset, 4);
388            memcpy(&pData[28], &Loops, 4);
389    
390            // we skip 'manufByt' for now (4 bytes)
391    
392            memcpy(&pData[36], &LoopID, 4);
393            memcpy(&pData[40], &LoopType, 4);
394            memcpy(&pData[44], &LoopStart, 4);
395            memcpy(&pData[48], &LoopEnd, 4);
396            memcpy(&pData[52], &LoopFraction, 4);
397            memcpy(&pData[56], &LoopPlayCount, 4);
398    
399            // make sure '3gix' chunk exists
400            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
401            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
402            // determine appropriate sample group index (to be stored in chunk)
403            uint16_t iSampleGroup = 0; // 0 refers to default sample group
404            File* pFile = static_cast<File*>(pParent);
405            if (pFile->pGroups) {
406                std::list<Group*>::iterator iter = pFile->pGroups->begin();
407                std::list<Group*>::iterator end  = pFile->pGroups->end();
408                for (int i = 0; iter != end; i++, iter++) {
409                    if (*iter == pGroup) {
410                        iSampleGroup = i;
411                        break; // found
412                    }
413                }
414            }
415            // update '3gix' chunk
416            pData = (uint8_t*) pCk3gix->LoadChunkData();
417            memcpy(&pData[0], &iSampleGroup, 2);
418      }      }
419    
420      /// 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 500  namespace { Line 617  namespace {
617          RAMCache.Size   = 0;          RAMCache.Size   = 0;
618      }      }
619    
620        /** @brief Resize sample.
621         *
622         * Resizes the sample's wave form data, that is the actual size of
623         * sample wave data possible to be written for this sample. This call
624         * will return immediately and just schedule the resize operation. You
625         * should call File::Save() to actually perform the resize operation(s)
626         * "physically" to the file. As this can take a while on large files, it
627         * is recommended to call Resize() first on all samples which have to be
628         * resized and finally to call File::Save() to perform all those resize
629         * operations in one rush.
630         *
631         * The actual size (in bytes) is dependant to the current FrameSize
632         * value. You may want to set FrameSize before calling Resize().
633         *
634         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
635         * enlarged samples before calling File::Save() as this might exceed the
636         * current sample's boundary!
637         *
638         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
639         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
640         * other formats will fail!
641         *
642         * @param iNewSize - new sample wave data size in sample points (must be
643         *                   greater than zero)
644         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
645         *                         or if \a iNewSize is less than 1
646         * @throws gig::Exception if existing sample is compressed
647         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
648         *      DLS::Sample::FormatTag, File::Save()
649         */
650        void Sample::Resize(int iNewSize) {
651            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
652            DLS::Sample::Resize(iNewSize);
653        }
654    
655      /**      /**
656       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
657       * 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 589  namespace { Line 741  namespace {
741       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
742       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
743       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
744         * @param pDimRgn          dimension region with looping information
745       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
746       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
747       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
748       */       */
749      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState, buffer_t* pExternalDecompressionBuffer) {      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,
750                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
751          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
752          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
753    
754          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
755    
756          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
757    
758              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
759                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
760    
761                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
762                      do {                  switch (loop.LoopType) {
                         // if not endless loop check if max. number of loop cycles have been passed  
                         if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;  
   
                         if (!pPlaybackState->reverse) { // forward playback  
                             do {  
                                 samplestoloopend  = this->LoopEnd - GetPos();  
                                 readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);  
                                 samplestoread    -= readsamples;  
                                 totalreadsamples += readsamples;  
                                 if (readsamples == samplestoloopend) {  
                                     pPlaybackState->reverse = true;  
                                     break;  
                                 }  
                             } while (samplestoread && readsamples);  
                         }  
                         else { // backward playback  
763    
764                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
765                              // determine the end position within the loop first,                          do {
766                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
767                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
768                              // backward playback  
769                                if (!pPlaybackState->reverse) { // forward playback
770                              unsigned long swapareastart       = totalreadsamples;                                  do {
771                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
772                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
773                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
774                                        totalreadsamples += readsamples;
775                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
776                                            pPlaybackState->reverse = true;
777                              // read samples for backward playback                                          break;
778                              do {                                      }
779                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
780                                  samplestoreadinloop -= readsamples;                              }
781                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
782    
783                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
784                                    // determine the end position within the loop first,
785                                    // read forward from that 'end' and finally after
786                                    // reading, swap all sample frames so it reflects
787                                    // backward playback
788    
789                                    unsigned long swapareastart       = totalreadsamples;
790                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
791                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
792                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
793    
794                                    SetPos(reverseplaybackend);
795    
796                                    // read samples for backward playback
797                                    do {
798                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
799                                        samplestoreadinloop -= readsamples;
800                                        samplestoread       -= readsamples;
801                                        totalreadsamples    += readsamples;
802                                    } while (samplestoreadinloop && readsamples);
803    
804                                    SetPos(reverseplaybackend); // pretend we really read backwards
805    
806                                    if (reverseplaybackend == loop.LoopStart) {
807                                        pPlaybackState->loop_cycles_left--;
808                                        pPlaybackState->reverse = false;
809                                    }
810    
811                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
812                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
813                              }                              }
814                            } while (samplestoread && readsamples);
815                            break;
816                        }
817    
818                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
819                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
820                          }                          if (!pPlaybackState->reverse) do {
821                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
822                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
823                  }                              samplestoread    -= readsamples;
824                                totalreadsamples += readsamples;
825                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
826                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
827                      if (!pPlaybackState->reverse) do {                                  break;
828                          samplestoloopend  = this->LoopEnd - GetPos();                              }
829                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                          } while (samplestoread && readsamples);
                         samplestoread    -= readsamples;  
                         totalreadsamples += readsamples;  
                         if (readsamples == samplestoloopend) {  
                             pPlaybackState->reverse = true;  
                             break;  
                         }  
                     } while (samplestoread && readsamples);  
830    
831                      if (!samplestoread) break;                          if (!samplestoread) break;
832    
833                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
834                      // determine the end position within the loop first,                          // determine the end position within the loop first,
835                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
836                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
837                      // backward playback                          // backward playback
838    
839                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
840                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
841                      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)
842                                                                                : samplestoread;                                                                                    : samplestoread;
843                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
844    
845                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
846    
847                      // read samples for backward playback                          // read samples for backward playback
848                      do {                          do {
849                          // 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
850                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
851                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
852                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
853                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
854                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
855                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
856                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
857                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
858                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
859                          }                              }
860                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
861    
862                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
863    
864                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
865                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
866                      break;                          break;
867                  }                      }
868    
869                  default: case loop_type_normal: {                      default: case loop_type_normal: {
870                      do {                          do {
871                          // 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
872                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
873                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
874                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
875                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
876                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
877                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
878                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
879                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
880                          }                              }
881                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
882                      break;                          break;
883                        }
884                  }                  }
885              }              }
886          }          }
# Line 751  namespace { Line 910  namespace {
910       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
911       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
912       *       *
913         * For 16 bit samples, the data in the buffer will be int16_t
914         * (using native endianness). For 24 bit, the buffer will
915         * contain three bytes per sample, little-endian.
916         *
917       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
918       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
919       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 761  namespace { Line 924  namespace {
924          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
925          if (!Compressed) {          if (!Compressed) {
926              if (BitDepth == 24) {              if (BitDepth == 24) {
927                  // 24 bit sample. For now just truncate to 16 bit.                  return pCkData->Read(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
                 unsigned char* pSrc = (unsigned char*) ((pExternalDecompressionBuffer) ? pExternalDecompressionBuffer->pStart : this->InternalDecompressionBuffer.pStart);  
                 int16_t* pDst = static_cast<int16_t*>(pBuffer);  
                 if (Channels == 2) { // Stereo  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 6, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return (pDst - static_cast<int16_t*>(pBuffer)) >> 1;  
                 }  
                 else { // Mono  
                     unsigned long readBytes = pCkData->Read(pSrc, SampleCount * 3, 1);  
                     pSrc++;  
                     for (unsigned long i = readBytes ; i > 0 ; i -= 3) {  
                         *pDst++ = get16(pSrc);  
                         pSrc += 3;  
                     }  
                     return pDst - static_cast<int16_t*>(pBuffer);  
                 }  
928              }              }
929              else { // 16 bit              else { // 16 bit
930                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 811  namespace { Line 954  namespace {
954    
955              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
956              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
957                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
958              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
959    
960              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 892  namespace { Line 1036  namespace {
1036                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1037                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1038    
1039                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1040                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1041                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1042                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1043                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1044                          }                          }
1045                          else { // Mono                          else { // Mono
1046                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1047                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1048                              pDst += copysamples;                              pDst24 += copysamples * 3;
1049                          }                          }
1050                      }                      }
1051                      else { // 16 bit                      else { // 16 bit
# Line 943  namespace { Line 1087  namespace {
1087          }          }
1088      }      }
1089    
1090        /** @brief Write sample wave data.
1091         *
1092         * Writes \a SampleCount number of sample points from the buffer pointed
1093         * by \a pBuffer and increments the position within the sample. Use this
1094         * method to directly write the sample data to disk, i.e. if you don't
1095         * want or cannot load the whole sample data into RAM.
1096         *
1097         * You have to Resize() the sample to the desired size and call
1098         * File::Save() <b>before</b> using Write().
1099         *
1100         * Note: there is currently no support for writing compressed samples.
1101         *
1102         * @param pBuffer     - source buffer
1103         * @param SampleCount - number of sample points to write
1104         * @throws DLS::Exception if current sample size is too small
1105         * @throws gig::Exception if sample is compressed
1106         * @see DLS::LoadSampleData()
1107         */
1108        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1109            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1110            return DLS::Sample::Write(pBuffer, SampleCount);
1111        }
1112    
1113      /**      /**
1114       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1115       * with Sample::Read(). If you are using more than one streaming thread       * with Sample::Read(). If you are using more than one streaming thread
# Line 985  namespace { Line 1152  namespace {
1152          }          }
1153      }      }
1154    
1155        /**
1156         * Returns pointer to the Group this Sample belongs to. In the .gig
1157         * format a sample always belongs to one group. If it wasn't explicitly
1158         * assigned to a certain group, it will be automatically assigned to a
1159         * default group.
1160         *
1161         * @returns Sample's Group (never NULL)
1162         */
1163        Group* Sample::GetGroup() const {
1164            return pGroup;
1165        }
1166    
1167      Sample::~Sample() {      Sample::~Sample() {
1168          Instances--;          Instances--;
1169          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1007  namespace { Line 1186  namespace {
1186      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1187          Instances++;          Instances++;
1188    
1189            pSample = NULL;
1190    
1191          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1192          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1193    
1194          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1195          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1196          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1197          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1198          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1199          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1200          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1201          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1202          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1203          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1204          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1205          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1206          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1207          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1208          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1209          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1210          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1211          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1212          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1213          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1214          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1215          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1216          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1217          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1218          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1219          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1220          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1221          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1222          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1223          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1224          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1225          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1226          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1227          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1228          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1229          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1230          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1231          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1232          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1233          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1234          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1235          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1236          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1237          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1238          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1239          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1240          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1241          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1242          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1243          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1244          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1245          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1246              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1247              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1248          }                  VelocityResponseDepth = velocityresponse;
1249          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1250              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1251              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1252          }              } else if (velocityresponse < 15) {
1253          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1254              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1255              VelocityResponseDepth = velocityresponse - 10;              } else {
1256                    VelocityResponseCurve = curve_type_unknown;
1257                    VelocityResponseDepth = 0;
1258                }
1259                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1260                if (releasevelocityresponse < 5) {
1261                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1262                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1263                } else if (releasevelocityresponse < 10) {
1264                    ReleaseVelocityResponseCurve = curve_type_linear;
1265                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1266                } else if (releasevelocityresponse < 15) {
1267                    ReleaseVelocityResponseCurve = curve_type_special;
1268                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1269                } else {
1270                    ReleaseVelocityResponseCurve = curve_type_unknown;
1271                    ReleaseVelocityResponseDepth = 0;
1272                }
1273                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1274                AttenuationControllerThreshold = _3ewa->ReadInt8();
1275                _3ewa->ReadInt32(); // unknown
1276                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1277                _3ewa->ReadInt16(); // unknown
1278                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1279                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1280                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1281                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1282                else                                       DimensionBypass = dim_bypass_ctrl_none;
1283                uint8_t pan = _3ewa->ReadUint8();
1284                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1285                SelfMask = _3ewa->ReadInt8() & 0x01;
1286                _3ewa->ReadInt8(); // unknown
1287                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1288                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1289                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1290                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1291                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1292                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1293                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1294                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1295                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1296                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1297                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1298                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1299                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1300                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1301                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1302                                                            : vcf_res_ctrl_none;
1303                uint16_t eg3depth = _3ewa->ReadUint16();
1304                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1305                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1306                _3ewa->ReadInt16(); // unknown
1307                ChannelOffset = _3ewa->ReadUint8() / 4;
1308                uint8_t regoptions = _3ewa->ReadUint8();
1309                MSDecode           = regoptions & 0x01; // bit 0
1310                SustainDefeat      = regoptions & 0x02; // bit 1
1311                _3ewa->ReadInt16(); // unknown
1312                VelocityUpperLimit = _3ewa->ReadInt8();
1313                _3ewa->ReadInt8(); // unknown
1314                _3ewa->ReadInt16(); // unknown
1315                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1316                _3ewa->ReadInt8(); // unknown
1317                _3ewa->ReadInt8(); // unknown
1318                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1319                uint8_t vcfcutoff = _3ewa->ReadUint8();
1320                VCFEnabled = vcfcutoff & 0x80; // bit 7
1321                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1322                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1323                uint8_t vcfvelscale = _3ewa->ReadUint8();
1324                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1325                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1326                _3ewa->ReadInt8(); // unknown
1327                uint8_t vcfresonance = _3ewa->ReadUint8();
1328                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1329                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1330                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1331                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1332                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1333                uint8_t vcfvelocity = _3ewa->ReadUint8();
1334                VCFVelocityDynamicRange = vcfvelocity % 5;
1335                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1336                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1337                if (VCFType == vcf_type_lowpass) {
1338                    if (lfo3ctrl & 0x40) // bit 6
1339                        VCFType = vcf_type_lowpassturbo;
1340                }
1341            } else { // '3ewa' chunk does not exist yet
1342                // use default values
1343                LFO3Frequency                   = 1.0;
1344                EG3Attack                       = 0.0;
1345                LFO1InternalDepth               = 0;
1346                LFO3InternalDepth               = 0;
1347                LFO1ControlDepth                = 0;
1348                LFO3ControlDepth                = 0;
1349                EG1Attack                       = 0.0;
1350                EG1Decay1                       = 0.0;
1351                EG1Sustain                      = 0;
1352                EG1Release                      = 0.0;
1353                EG1Controller.type              = eg1_ctrl_t::type_none;
1354                EG1Controller.controller_number = 0;
1355                EG1ControllerInvert             = false;
1356                EG1ControllerAttackInfluence    = 0;
1357                EG1ControllerDecayInfluence     = 0;
1358                EG1ControllerReleaseInfluence   = 0;
1359                EG2Controller.type              = eg2_ctrl_t::type_none;
1360                EG2Controller.controller_number = 0;
1361                EG2ControllerInvert             = false;
1362                EG2ControllerAttackInfluence    = 0;
1363                EG2ControllerDecayInfluence     = 0;
1364                EG2ControllerReleaseInfluence   = 0;
1365                LFO1Frequency                   = 1.0;
1366                EG2Attack                       = 0.0;
1367                EG2Decay1                       = 0.0;
1368                EG2Sustain                      = 0;
1369                EG2Release                      = 0.0;
1370                LFO2ControlDepth                = 0;
1371                LFO2Frequency                   = 1.0;
1372                LFO2InternalDepth               = 0;
1373                EG1Decay2                       = 0.0;
1374                EG1InfiniteSustain              = false;
1375                EG1PreAttack                    = 1000;
1376                EG2Decay2                       = 0.0;
1377                EG2InfiniteSustain              = false;
1378                EG2PreAttack                    = 1000;
1379                VelocityResponseCurve           = curve_type_nonlinear;
1380                VelocityResponseDepth           = 3;
1381                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1382                ReleaseVelocityResponseDepth    = 3;
1383                VelocityResponseCurveScaling    = 32;
1384                AttenuationControllerThreshold  = 0;
1385                SampleStartOffset               = 0;
1386                PitchTrack                      = true;
1387                DimensionBypass                 = dim_bypass_ctrl_none;
1388                Pan                             = 0;
1389                SelfMask                        = true;
1390                LFO3Controller                  = lfo3_ctrl_modwheel;
1391                LFO3Sync                        = false;
1392                InvertAttenuationController     = false;
1393                AttenuationController.type      = attenuation_ctrl_t::type_none;
1394                AttenuationController.controller_number = 0;
1395                LFO2Controller                  = lfo2_ctrl_internal;
1396                LFO2FlipPhase                   = false;
1397                LFO2Sync                        = false;
1398                LFO1Controller                  = lfo1_ctrl_internal;
1399                LFO1FlipPhase                   = false;
1400                LFO1Sync                        = false;
1401                VCFResonanceController          = vcf_res_ctrl_none;
1402                EG3Depth                        = 0;
1403                ChannelOffset                   = 0;
1404                MSDecode                        = false;
1405                SustainDefeat                   = false;
1406                VelocityUpperLimit              = 0;
1407                ReleaseTriggerDecay             = 0;
1408                EG1Hold                         = false;
1409                VCFEnabled                      = false;
1410                VCFCutoff                       = 0;
1411                VCFCutoffController             = vcf_cutoff_ctrl_none;
1412                VCFCutoffControllerInvert       = false;
1413                VCFVelocityScale                = 0;
1414                VCFResonance                    = 0;
1415                VCFResonanceDynamic             = false;
1416                VCFKeyboardTracking             = false;
1417                VCFKeyboardTrackingBreakpoint   = 0;
1418                VCFVelocityDynamicRange         = 0x04;
1419                VCFVelocityCurve                = curve_type_linear;
1420                VCFType                         = vcf_type_lowpass;
1421            }
1422    
1423            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1424                                                         VelocityResponseDepth,
1425                                                         VelocityResponseCurveScaling);
1426    
1427            curve_type_t curveType = ReleaseVelocityResponseCurve;
1428            uint8_t depth = ReleaseVelocityResponseDepth;
1429    
1430            // this models a strange behaviour or bug in GSt: two of the
1431            // velocity response curves for release time are not used even
1432            // if specified, instead another curve is chosen.
1433            if ((curveType == curve_type_nonlinear && depth == 0) ||
1434                (curveType == curve_type_special   && depth == 4)) {
1435                curveType = curve_type_nonlinear;
1436                depth = 3;
1437            }
1438            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1439    
1440            curveType = VCFVelocityCurve;
1441            depth = VCFVelocityDynamicRange;
1442    
1443            // even stranger GSt: two of the velocity response curves for
1444            // filter cutoff are not used, instead another special curve
1445            // is chosen. This curve is not used anywhere else.
1446            if ((curveType == curve_type_nonlinear && depth == 0) ||
1447                (curveType == curve_type_special   && depth == 4)) {
1448                curveType = curve_type_special;
1449                depth = 5;
1450          }          }
1451          else {          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1452              VelocityResponseCurve = curve_type_unknown;                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1453              VelocityResponseDepth = 0;  
1454            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1455            VelocityTable = 0;
1456        }
1457    
1458        /**
1459         * Apply dimension region settings to the respective RIFF chunks. You
1460         * have to call File::Save() to make changes persistent.
1461         *
1462         * Usually there is absolutely no need to call this method explicitly.
1463         * It will be called automatically when File::Save() was called.
1464         */
1465        void DimensionRegion::UpdateChunks() {
1466            // first update base class's chunk
1467            DLS::Sampler::UpdateChunks();
1468    
1469            // make sure '3ewa' chunk exists
1470            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1471            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1472            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1473    
1474            // update '3ewa' chunk with DimensionRegion's current settings
1475    
1476            const uint32_t unknown = _3ewa->GetSize(); // unknown, always chunk size ?
1477            memcpy(&pData[0], &unknown, 4);
1478    
1479            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1480            memcpy(&pData[4], &lfo3freq, 4);
1481    
1482            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1483            memcpy(&pData[8], &eg3attack, 4);
1484    
1485            // next 2 bytes unknown
1486    
1487            memcpy(&pData[14], &LFO1InternalDepth, 2);
1488    
1489            // next 2 bytes unknown
1490    
1491            memcpy(&pData[18], &LFO3InternalDepth, 2);
1492    
1493            // next 2 bytes unknown
1494    
1495            memcpy(&pData[22], &LFO1ControlDepth, 2);
1496    
1497            // next 2 bytes unknown
1498    
1499            memcpy(&pData[26], &LFO3ControlDepth, 2);
1500    
1501            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1502            memcpy(&pData[28], &eg1attack, 4);
1503    
1504            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1505            memcpy(&pData[32], &eg1decay1, 4);
1506    
1507            // next 2 bytes unknown
1508    
1509            memcpy(&pData[38], &EG1Sustain, 2);
1510    
1511            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1512            memcpy(&pData[40], &eg1release, 4);
1513    
1514            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1515            memcpy(&pData[44], &eg1ctl, 1);
1516    
1517            const uint8_t eg1ctrloptions =
1518                (EG1ControllerInvert) ? 0x01 : 0x00 |
1519                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1520                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1521                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1522            memcpy(&pData[45], &eg1ctrloptions, 1);
1523    
1524            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1525            memcpy(&pData[46], &eg2ctl, 1);
1526    
1527            const uint8_t eg2ctrloptions =
1528                (EG2ControllerInvert) ? 0x01 : 0x00 |
1529                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1530                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1531                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1532            memcpy(&pData[47], &eg2ctrloptions, 1);
1533    
1534            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1535            memcpy(&pData[48], &lfo1freq, 4);
1536    
1537            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1538            memcpy(&pData[52], &eg2attack, 4);
1539    
1540            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1541            memcpy(&pData[56], &eg2decay1, 4);
1542    
1543            // next 2 bytes unknown
1544    
1545            memcpy(&pData[62], &EG2Sustain, 2);
1546    
1547            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1548            memcpy(&pData[64], &eg2release, 4);
1549    
1550            // next 2 bytes unknown
1551    
1552            memcpy(&pData[70], &LFO2ControlDepth, 2);
1553    
1554            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1555            memcpy(&pData[72], &lfo2freq, 4);
1556    
1557            // next 2 bytes unknown
1558    
1559            memcpy(&pData[78], &LFO2InternalDepth, 2);
1560    
1561            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1562            memcpy(&pData[80], &eg1decay2, 4);
1563    
1564            // next 2 bytes unknown
1565    
1566            memcpy(&pData[86], &EG1PreAttack, 2);
1567    
1568            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1569            memcpy(&pData[88], &eg2decay2, 4);
1570    
1571            // next 2 bytes unknown
1572    
1573            memcpy(&pData[94], &EG2PreAttack, 2);
1574    
1575            {
1576                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1577                uint8_t velocityresponse = VelocityResponseDepth;
1578                switch (VelocityResponseCurve) {
1579                    case curve_type_nonlinear:
1580                        break;
1581                    case curve_type_linear:
1582                        velocityresponse += 5;
1583                        break;
1584                    case curve_type_special:
1585                        velocityresponse += 10;
1586                        break;
1587                    case curve_type_unknown:
1588                    default:
1589                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1590                }
1591                memcpy(&pData[96], &velocityresponse, 1);
1592          }          }
1593          uint8_t releasevelocityresponse = _3ewa->ReadUint8();  
1594          if (releasevelocityresponse < 5) {          {
1595              ReleaseVelocityResponseCurve = curve_type_nonlinear;              if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1596              ReleaseVelocityResponseDepth = releasevelocityresponse;              uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1597          }              switch (ReleaseVelocityResponseCurve) {
1598          else if (releasevelocityresponse < 10) {                  case curve_type_nonlinear:
1599              ReleaseVelocityResponseCurve = curve_type_linear;                      break;
1600              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  case curve_type_linear:
1601          }                      releasevelocityresponse += 5;
1602          else if (releasevelocityresponse < 15) {                      break;
1603              ReleaseVelocityResponseCurve = curve_type_special;                  case curve_type_special:
1604              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;                      releasevelocityresponse += 10;
1605                        break;
1606                    case curve_type_unknown:
1607                    default:
1608                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1609                }
1610                memcpy(&pData[97], &releasevelocityresponse, 1);
1611          }          }
1612          else {  
1613              ReleaseVelocityResponseCurve = curve_type_unknown;          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);
1614              ReleaseVelocityResponseDepth = 0;  
1615            memcpy(&pData[99], &AttenuationControllerThreshold, 1);
1616    
1617            // next 4 bytes unknown
1618    
1619            memcpy(&pData[104], &SampleStartOffset, 2);
1620    
1621            // next 2 bytes unknown
1622    
1623            {
1624                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1625                switch (DimensionBypass) {
1626                    case dim_bypass_ctrl_94:
1627                        pitchTrackDimensionBypass |= 0x10;
1628                        break;
1629                    case dim_bypass_ctrl_95:
1630                        pitchTrackDimensionBypass |= 0x20;
1631                        break;
1632                    case dim_bypass_ctrl_none:
1633                        //FIXME: should we set anything here?
1634                        break;
1635                    default:
1636                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1637                }
1638                memcpy(&pData[108], &pitchTrackDimensionBypass, 1);
1639          }          }
1640          VelocityResponseCurveScaling = _3ewa->ReadUint8();  
1641          AttenuationControllerThreshold = _3ewa->ReadInt8();          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1642          _3ewa->ReadInt32(); // unknown          memcpy(&pData[109], &pan, 1);
1643          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();  
1644          _3ewa->ReadInt16(); // unknown          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1645          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          memcpy(&pData[110], &selfmask, 1);
1646          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1647          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          // next byte unknown
1648          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
1649          else                                       DimensionBypass = dim_bypass_ctrl_none;          {
1650          uint8_t pan = _3ewa->ReadUint8();              uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1651          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1652          SelfMask = _3ewa->ReadInt8() & 0x01;              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1653          _3ewa->ReadInt8(); // unknown              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1654          uint8_t lfo3ctrl = _3ewa->ReadUint8();              memcpy(&pData[112], &lfo3ctrl, 1);
1655          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits          }
1656          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5  
1657          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1658          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));          memcpy(&pData[113], &attenctl, 1);
1659          uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
1660          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits          {
1661          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1662          LFO2Sync               = lfo2ctrl & 0x20; // bit 5              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1663          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1664          uint8_t lfo1ctrl       = _3ewa->ReadUint8();              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1665          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits              memcpy(&pData[114], &lfo2ctrl, 1);
1666          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7          }
1667          LFO1Sync               = lfo1ctrl & 0x40; // bit 6  
1668          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))          {
1669                                                      : vcf_res_ctrl_none;              uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1670          uint16_t eg3depth = _3ewa->ReadUint16();              if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1671          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1672                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */              if (VCFResonanceController != vcf_res_ctrl_none)
1673          _3ewa->ReadInt16(); // unknown                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1674          ChannelOffset = _3ewa->ReadUint8() / 4;              memcpy(&pData[115], &lfo1ctrl, 1);
1675          uint8_t regoptions = _3ewa->ReadUint8();          }
1676          MSDecode           = regoptions & 0x01; // bit 0  
1677          SustainDefeat      = regoptions & 0x02; // bit 1          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1678          _3ewa->ReadInt16(); // unknown                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1679          VelocityUpperLimit = _3ewa->ReadInt8();          memcpy(&pData[116], &eg3depth, 1);
1680          _3ewa->ReadInt8(); // unknown  
1681          _3ewa->ReadInt16(); // unknown          // next 2 bytes unknown
1682          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay  
1683          _3ewa->ReadInt8(); // unknown          const uint8_t channeloffset = ChannelOffset * 4;
1684          _3ewa->ReadInt8(); // unknown          memcpy(&pData[120], &channeloffset, 1);
1685          EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
1686          uint8_t vcfcutoff = _3ewa->ReadUint8();          {
1687          VCFEnabled = vcfcutoff & 0x80; // bit 7              uint8_t regoptions = 0;
1688          VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits              if (MSDecode)      regoptions |= 0x01; // bit 0
1689          VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());              if (SustainDefeat) regoptions |= 0x02; // bit 1
1690          VCFVelocityScale = _3ewa->ReadUint8();              memcpy(&pData[121], &regoptions, 1);
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
1691          }          }
1692    
1693          // 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
1694          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;  
1695            memcpy(&pData[124], &VelocityUpperLimit, 1);
1696    
1697            // next 3 bytes unknown
1698    
1699            memcpy(&pData[128], &ReleaseTriggerDecay, 1);
1700    
1701            // next 2 bytes unknown
1702    
1703            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1704            memcpy(&pData[131], &eg1hold, 1);
1705    
1706            const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1707                                      (VCFCutoff & 0x7f);   /* lower 7 bits */
1708            memcpy(&pData[132], &vcfcutoff, 1);
1709    
1710            memcpy(&pData[133], &VCFCutoffController, 1);
1711    
1712            const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1713                                        (VCFVelocityScale & 0x7f); /* lower 7 bits */
1714            memcpy(&pData[134], &vcfvelscale, 1);
1715    
1716            // next byte unknown
1717    
1718            const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1719                                         (VCFResonance & 0x7f); /* lower 7 bits */
1720            memcpy(&pData[136], &vcfresonance, 1);
1721    
1722            const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1723                                          (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1724            memcpy(&pData[137], &vcfbreakpoint, 1);
1725    
1726            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1727                                        VCFVelocityCurve * 5;
1728            memcpy(&pData[138], &vcfvelocity, 1);
1729    
1730            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1731            memcpy(&pData[139], &vcftype, 1);
1732        }
1733    
1734        // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1735        double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1736        {
1737            double* table;
1738            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1739          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1740              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1741          }          }
1742          else {          else {
1743              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1744                  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  
1745          }          }
1746            return table;
         SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));  
1747      }      }
1748    
1749      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1295  namespace { Line 1864  namespace {
1864          return decodedcontroller;          return decodedcontroller;
1865      }      }
1866    
1867        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1868            _lev_ctrl_t encodedcontroller;
1869            switch (DecodedController.type) {
1870                // special controller
1871                case leverage_ctrl_t::type_none:
1872                    encodedcontroller = _lev_ctrl_none;
1873                    break;
1874                case leverage_ctrl_t::type_velocity:
1875                    encodedcontroller = _lev_ctrl_velocity;
1876                    break;
1877                case leverage_ctrl_t::type_channelaftertouch:
1878                    encodedcontroller = _lev_ctrl_channelaftertouch;
1879                    break;
1880    
1881                // ordinary MIDI control change controller
1882                case leverage_ctrl_t::type_controlchange:
1883                    switch (DecodedController.controller_number) {
1884                        case 1:
1885                            encodedcontroller = _lev_ctrl_modwheel;
1886                            break;
1887                        case 2:
1888                            encodedcontroller = _lev_ctrl_breath;
1889                            break;
1890                        case 4:
1891                            encodedcontroller = _lev_ctrl_foot;
1892                            break;
1893                        case 12:
1894                            encodedcontroller = _lev_ctrl_effect1;
1895                            break;
1896                        case 13:
1897                            encodedcontroller = _lev_ctrl_effect2;
1898                            break;
1899                        case 16:
1900                            encodedcontroller = _lev_ctrl_genpurpose1;
1901                            break;
1902                        case 17:
1903                            encodedcontroller = _lev_ctrl_genpurpose2;
1904                            break;
1905                        case 18:
1906                            encodedcontroller = _lev_ctrl_genpurpose3;
1907                            break;
1908                        case 19:
1909                            encodedcontroller = _lev_ctrl_genpurpose4;
1910                            break;
1911                        case 5:
1912                            encodedcontroller = _lev_ctrl_portamentotime;
1913                            break;
1914                        case 64:
1915                            encodedcontroller = _lev_ctrl_sustainpedal;
1916                            break;
1917                        case 65:
1918                            encodedcontroller = _lev_ctrl_portamento;
1919                            break;
1920                        case 66:
1921                            encodedcontroller = _lev_ctrl_sostenutopedal;
1922                            break;
1923                        case 67:
1924                            encodedcontroller = _lev_ctrl_softpedal;
1925                            break;
1926                        case 80:
1927                            encodedcontroller = _lev_ctrl_genpurpose5;
1928                            break;
1929                        case 81:
1930                            encodedcontroller = _lev_ctrl_genpurpose6;
1931                            break;
1932                        case 82:
1933                            encodedcontroller = _lev_ctrl_genpurpose7;
1934                            break;
1935                        case 83:
1936                            encodedcontroller = _lev_ctrl_genpurpose8;
1937                            break;
1938                        case 91:
1939                            encodedcontroller = _lev_ctrl_effect1depth;
1940                            break;
1941                        case 92:
1942                            encodedcontroller = _lev_ctrl_effect2depth;
1943                            break;
1944                        case 93:
1945                            encodedcontroller = _lev_ctrl_effect3depth;
1946                            break;
1947                        case 94:
1948                            encodedcontroller = _lev_ctrl_effect4depth;
1949                            break;
1950                        case 95:
1951                            encodedcontroller = _lev_ctrl_effect5depth;
1952                            break;
1953                        default:
1954                            throw gig::Exception("leverage controller number is not supported by the gig format");
1955                    }
1956                default:
1957                    throw gig::Exception("Unknown leverage controller type.");
1958            }
1959            return encodedcontroller;
1960        }
1961    
1962      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
1963          Instances--;          Instances--;
1964          if (!Instances) {          if (!Instances) {
# Line 1308  namespace { Line 1972  namespace {
1972              delete pVelocityTables;              delete pVelocityTables;
1973              pVelocityTables = NULL;              pVelocityTables = NULL;
1974          }          }
1975            if (VelocityTable) delete[] VelocityTable;
1976      }      }
1977    
1978      /**      /**
# Line 1325  namespace { Line 1990  namespace {
1990          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
1991      }      }
1992    
1993        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
1994            return pVelocityReleaseTable[MIDIKeyVelocity];
1995        }
1996    
1997        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
1998            return pVelocityCutoffTable[MIDIKeyVelocity];
1999        }
2000    
2001      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) {
2002    
2003          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1358  namespace { Line 2031  namespace {
2031          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,
2032                               127, 127 };                               127, 127 };
2033    
2034            // this is only used by the VCF velocity curve
2035            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2036                                 91, 127, 127, 127 };
2037    
2038          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2039                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2040                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2041    
2042          double* const table = new double[128];          double* const table = new double[128];
2043    
# Line 1393  namespace { Line 2070  namespace {
2070  // *  // *
2071    
2072      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2073            pInfo->UseFixedLengthStrings = true;
2074    
2075          // Initialization          // Initialization
2076          Dimensions = 0;          Dimensions = 0;
2077          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 1412  namespace { Line 2091  namespace {
2091              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2092                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2093                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2094                    _3lnk->ReadUint8(); // probably the position of the dimension
2095                    _3lnk->ReadUint8(); // unknown
2096                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2097                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2098                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2099                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2100                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2101                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2102                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2103                  }                  }
2104                  else { // active dimension                  else { // active dimension
2105                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2106                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2107                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2108                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2109                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2110                                                             dimension == dimension_releasetrigger ||                                                             dimension == dimension_releasetrigger ||
2111                                                               dimension == dimension_keyboard ||
2112                                                             dimension == dimension_roundrobin ||                                                             dimension == dimension_roundrobin ||
2113                                                             dimension == dimension_random) ? split_type_bit                                                             dimension == dimension_random) ? split_type_bit
2114                                                                                            : split_type_normal;                                                                                            : split_type_normal;
                     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point  
2115                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2116                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2117                                                                                     : 0;                                                                                     : 0;
2118                      Dimensions++;                      Dimensions++;
2119    
2120                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2121                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2122                  }                  }
2123                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2124              }              }
2125                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2126    
2127              // 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,
2128              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2129                  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;  
                             }  
                         }  
                     }  
                 }  
             }  
2130    
2131              // 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();  
2132              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2133                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2134              else              else
# Line 1482  namespace { Line 2137  namespace {
2137              // load sample references              // load sample references
2138              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2139                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2140                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2141                }
2142                GetSample(); // load global region sample reference
2143            }
2144    
2145            // make sure there is at least one dimension region
2146            if (!DimensionRegions) {
2147                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2148                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2149                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2150                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2151                DimensionRegions = 1;
2152            }
2153        }
2154    
2155        /**
2156         * Apply Region settings and all its DimensionRegions to the respective
2157         * RIFF chunks. You have to call File::Save() to make changes persistent.
2158         *
2159         * Usually there is absolutely no need to call this method explicitly.
2160         * It will be called automatically when File::Save() was called.
2161         *
2162         * @throws gig::Exception if samples cannot be dereferenced
2163         */
2164        void Region::UpdateChunks() {
2165            // first update base class's chunks
2166            DLS::Region::UpdateChunks();
2167    
2168            // update dimension region's chunks
2169            for (int i = 0; i < DimensionRegions; i++) {
2170                pDimensionRegions[i]->UpdateChunks();
2171            }
2172    
2173            File* pFile = (File*) GetParent()->GetParent();
2174            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2175            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2176    
2177            // make sure '3lnk' chunk exists
2178            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2179            if (!_3lnk) {
2180                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2181                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2182            }
2183    
2184            // update dimension definitions in '3lnk' chunk
2185            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2186            memcpy(&pData[0], &DimensionRegions, 4);
2187            for (int i = 0; i < iMaxDimensions; i++) {
2188                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2189                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2190                // next 2 bytes unknown
2191                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2192                // next 3 bytes unknown
2193            }
2194    
2195            // update wave pool table in '3lnk' chunk
2196            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2197            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2198                int iWaveIndex = -1;
2199                if (i < DimensionRegions) {
2200                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2201                    File::SampleList::iterator iter = pFile->pSamples->begin();
2202                    File::SampleList::iterator end  = pFile->pSamples->end();
2203                    for (int index = 0; iter != end; ++iter, ++index) {
2204                        if (*iter == pDimensionRegions[i]->pSample) {
2205                            iWaveIndex = index;
2206                            break;
2207                        }
2208                    }
2209                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2210              }              }
2211                memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2212          }          }
         else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2213      }      }
2214    
2215      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1504  namespace { Line 2228  namespace {
2228          }          }
2229      }      }
2230    
2231      Region::~Region() {      void Region::UpdateVelocityTable() {
2232          for (uint i = 0; i < Dimensions; i++) {          // get velocity dimension's index
2233              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          int veldim = -1;
2234            for (int i = 0 ; i < Dimensions ; i++) {
2235                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2236                    veldim = i;
2237                    break;
2238                }
2239            }
2240            if (veldim == -1) return;
2241    
2242            int step = 1;
2243            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2244            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2245            int end = step * pDimensionDefinitions[veldim].zones;
2246    
2247            // loop through all dimension regions for all dimensions except the velocity dimension
2248            int dim[8] = { 0 };
2249            for (int i = 0 ; i < DimensionRegions ; i++) {
2250    
2251                if (pDimensionRegions[i]->VelocityUpperLimit) {
2252                    // create the velocity table
2253                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2254                    if (!table) {
2255                        table = new uint8_t[128];
2256                        pDimensionRegions[i]->VelocityTable = table;
2257                    }
2258                    int tableidx = 0;
2259                    int velocityZone = 0;
2260                    for (int k = i ; k < end ; k += step) {
2261                        DimensionRegion *d = pDimensionRegions[k];
2262                        for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2263                        velocityZone++;
2264                    }
2265                } else {
2266                    if (pDimensionRegions[i]->VelocityTable) {
2267                        delete[] pDimensionRegions[i]->VelocityTable;
2268                        pDimensionRegions[i]->VelocityTable = 0;
2269                    }
2270                }
2271    
2272                int j;
2273                int shift = 0;
2274                for (j = 0 ; j < Dimensions ; j++) {
2275                    if (j == veldim) i += skipveldim; // skip velocity dimension
2276                    else {
2277                        dim[j]++;
2278                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2279                        else {
2280                            // skip unused dimension regions
2281                            dim[j] = 0;
2282                            i += ((1 << pDimensionDefinitions[j].bits) -
2283                                  pDimensionDefinitions[j].zones) << shift;
2284                        }
2285                    }
2286                    shift += pDimensionDefinitions[j].bits;
2287                }
2288                if (j == Dimensions) break;
2289            }
2290        }
2291    
2292        /** @brief Einstein would have dreamed of it - create a new dimension.
2293         *
2294         * Creates a new dimension with the dimension definition given by
2295         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2296         * There is a hard limit of dimensions and total amount of "bits" all
2297         * dimensions can have. This limit is dependant to what gig file format
2298         * version this file refers to. The gig v2 (and lower) format has a
2299         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2300         * format has a limit of 8.
2301         *
2302         * @param pDimDef - defintion of the new dimension
2303         * @throws gig::Exception if dimension of the same type exists already
2304         * @throws gig::Exception if amount of dimensions or total amount of
2305         *                        dimension bits limit is violated
2306         */
2307        void Region::AddDimension(dimension_def_t* pDimDef) {
2308            // check if max. amount of dimensions reached
2309            File* file = (File*) GetParent()->GetParent();
2310            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2311            if (Dimensions >= iMaxDimensions)
2312                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2313            // check if max. amount of dimension bits reached
2314            int iCurrentBits = 0;
2315            for (int i = 0; i < Dimensions; i++)
2316                iCurrentBits += pDimensionDefinitions[i].bits;
2317            if (iCurrentBits >= iMaxDimensions)
2318                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2319            const int iNewBits = iCurrentBits + pDimDef->bits;
2320            if (iNewBits > iMaxDimensions)
2321                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2322            // check if there's already a dimensions of the same type
2323            for (int i = 0; i < Dimensions; i++)
2324                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2325                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2326    
2327            // assign definition of new dimension
2328            pDimensionDefinitions[Dimensions] = *pDimDef;
2329    
2330            // create new dimension region(s) for this new dimension
2331            for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2332                //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2333                RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2334                pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2335                DimensionRegions++;
2336            }
2337    
2338            Dimensions++;
2339    
2340            // if this is a layer dimension, update 'Layers' attribute
2341            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2342    
2343            UpdateVelocityTable();
2344        }
2345    
2346        /** @brief Delete an existing dimension.
2347         *
2348         * Deletes the dimension given by \a pDimDef and deletes all respective
2349         * dimension regions, that is all dimension regions where the dimension's
2350         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2351         * for example this would delete all dimension regions for the case(s)
2352         * where the sustain pedal is pressed down.
2353         *
2354         * @param pDimDef - dimension to delete
2355         * @throws gig::Exception if given dimension cannot be found
2356         */
2357        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2358            // get dimension's index
2359            int iDimensionNr = -1;
2360            for (int i = 0; i < Dimensions; i++) {
2361                if (&pDimensionDefinitions[i] == pDimDef) {
2362                    iDimensionNr = i;
2363                    break;
2364                }
2365            }
2366            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2367    
2368            // get amount of bits below the dimension to delete
2369            int iLowerBits = 0;
2370            for (int i = 0; i < iDimensionNr; i++)
2371                iLowerBits += pDimensionDefinitions[i].bits;
2372    
2373            // get amount ot bits above the dimension to delete
2374            int iUpperBits = 0;
2375            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2376                iUpperBits += pDimensionDefinitions[i].bits;
2377    
2378            // delete dimension regions which belong to the given dimension
2379            // (that is where the dimension's bit > 0)
2380            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2381                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2382                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2383                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2384                                        iObsoleteBit << iLowerBits |
2385                                        iLowerBit;
2386                        delete pDimensionRegions[iToDelete];
2387                        pDimensionRegions[iToDelete] = NULL;
2388                        DimensionRegions--;
2389                    }
2390                }
2391            }
2392    
2393            // defrag pDimensionRegions array
2394            // (that is remove the NULL spaces within the pDimensionRegions array)
2395            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2396                if (!pDimensionRegions[iTo]) {
2397                    if (iFrom <= iTo) iFrom = iTo + 1;
2398                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2399                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2400                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2401                        pDimensionRegions[iFrom] = NULL;
2402                    }
2403                }
2404          }          }
2405    
2406            // 'remove' dimension definition
2407            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2408                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2409            }
2410            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2411            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2412            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2413    
2414            Dimensions--;
2415    
2416            // if this was a layer dimension, update 'Layers' attribute
2417            if (pDimDef->dimension == dimension_layer) Layers = 1;
2418        }
2419    
2420        Region::~Region() {
2421          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2422              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2423          }          }
# Line 1532  namespace { Line 2442  namespace {
2442       * @see             Dimensions       * @see             Dimensions
2443       */       */
2444      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2445          uint8_t bits[8] = { 0 };          uint8_t bits;
2446            int veldim = -1;
2447            int velbitpos;
2448            int bitpos = 0;
2449            int dimregidx = 0;
2450          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2451              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2452              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2453                  case split_type_normal:                  veldim = i;
2454                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
2455                      break;              } else {
2456                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2457                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2458                      break;                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2459                  case split_type_bit: // the value is already the sought dimension bit number                          break;
2460                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                      case split_type_bit: // the value is already the sought dimension bit number
2461                      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;
2462                      break;                          bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2463              }                          break;
2464                    }
2465                    dimregidx |= bits << bitpos;
2466                }
2467                bitpos += pDimensionDefinitions[i].bits;
2468            }
2469            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2470            if (veldim != -1) {
2471                // (dimreg is now the dimension region for the lowest velocity)
2472                if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2473                    bits = dimreg->VelocityTable[DimValues[veldim]];
2474                else // normal split type
2475                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2476    
2477                dimregidx |= bits << velbitpos;
2478                dimreg = pDimensionRegions[dimregidx];
2479          }          }
2480          return GetDimensionRegionByBit(bits);          return dimreg;
2481      }      }
2482    
2483      /**      /**
# Line 1588  namespace { Line 2517  namespace {
2517      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2518          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2519          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2520            if (!file->pWavePoolTable) return NULL;
2521          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2522            unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2523          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
2524          while (sample) {          while (sample) {
2525              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2526                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2527              sample = file->GetNextSample();              sample = file->GetNextSample();
2528          }          }
2529          return NULL;          return NULL;
# Line 1603  namespace { Line 2535  namespace {
2535  // *  // *
2536    
2537      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {      Instrument::Instrument(File* pFile, RIFF::List* insList, progress_t* pProgress) : DLS::Instrument((DLS::File*)pFile, insList) {
2538            pInfo->UseFixedLengthStrings = true;
2539    
2540          // Initialization          // Initialization
2541          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2542    
2543          // Loading          // Loading
2544          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1621  namespace { Line 2554  namespace {
2554                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2555                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2556              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2557          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2558    
2559            if (!pRegions) pRegions = new RegionList;
2560          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2561          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2562          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2563          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              while (rgn) {
2564          RIFF::List* rgn = lrgn->GetFirstSubList();                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2565          unsigned int iRegion = 0;                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2566          while (rgn) {                      pRegions->push_back(new Region(this, rgn));
2567              if (rgn->GetListType() == LIST_TYPE_RGN) {                  }
2568                  __notify_progress(pProgress, (float) iRegion / (float) Regions);                  rgn = lrgn->GetNextSubList();
                 pRegions[iRegion] = new Region(this, rgn);  
                 iRegion++;  
             }  
             rgn = lrgn->GetNextSubList();  
         }  
   
         // Creating Region Key Table for fast lookup  
         for (uint iReg = 0; iReg < Regions; iReg++) {  
             for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {  
                 RegionKeyTable[iKey] = pRegions[iReg];  
2569              }              }
2570                // Creating Region Key Table for fast lookup
2571                UpdateRegionKeyTable();
2572          }          }
2573    
2574          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
2575      }      }
2576    
2577      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2578          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2579              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2580                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2581                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2582                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2583                    RegionKeyTable[iKey] = pRegion;
2584              }              }
2585          }          }
2586          if (pRegions) delete[] pRegions;      }
2587    
2588        Instrument::~Instrument() {
2589        }
2590    
2591        /**
2592         * Apply Instrument with all its Regions to the respective RIFF chunks.
2593         * You have to call File::Save() to make changes persistent.
2594         *
2595         * Usually there is absolutely no need to call this method explicitly.
2596         * It will be called automatically when File::Save() was called.
2597         *
2598         * @throws gig::Exception if samples cannot be dereferenced
2599         */
2600        void Instrument::UpdateChunks() {
2601            // first update base classes' chunks
2602            DLS::Instrument::UpdateChunks();
2603    
2604            // update Regions' chunks
2605            {
2606                RegionList::iterator iter = pRegions->begin();
2607                RegionList::iterator end  = pRegions->end();
2608                for (; iter != end; ++iter)
2609                    (*iter)->UpdateChunks();
2610            }
2611    
2612            // make sure 'lart' RIFF list chunk exists
2613            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2614            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2615            // make sure '3ewg' RIFF chunk exists
2616            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2617            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2618            // update '3ewg' RIFF chunk
2619            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2620            memcpy(&pData[0], &EffectSend, 2);
2621            memcpy(&pData[2], &Attenuation, 4);
2622            memcpy(&pData[6], &FineTune, 2);
2623            memcpy(&pData[8], &PitchbendRange, 2);
2624            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2625                                        DimensionKeyRange.low << 1;
2626            memcpy(&pData[10], &dimkeystart, 1);
2627            memcpy(&pData[11], &DimensionKeyRange.high, 1);
2628      }      }
2629    
2630      /**      /**
# Line 1667  namespace { Line 2635  namespace {
2635       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2636       */       */
2637      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2638          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2639          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2640    
2641          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2642              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2643                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1684  namespace { Line 2653  namespace {
2653       * @see      GetNextRegion()       * @see      GetNextRegion()
2654       */       */
2655      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2656          if (!Regions) return NULL;          if (!pRegions) return NULL;
2657          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2658          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2659      }      }
2660    
2661      /**      /**
# Line 1698  namespace { Line 2667  namespace {
2667       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2668       */       */
2669      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2670          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2671          return pRegions[RegionIndex++];          RegionsIterator++;
2672            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2673        }
2674    
2675        Region* Instrument::AddRegion() {
2676            // create new Region object (and its RIFF chunks)
2677            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2678            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2679            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2680            Region* pNewRegion = new Region(this, rgn);
2681            pRegions->push_back(pNewRegion);
2682            Regions = pRegions->size();
2683            // update Region key table for fast lookup
2684            UpdateRegionKeyTable();
2685            // done
2686            return pNewRegion;
2687        }
2688    
2689        void Instrument::DeleteRegion(Region* pRegion) {
2690            if (!pRegions) return;
2691            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2692            // update Region key table for fast lookup
2693            UpdateRegionKeyTable();
2694        }
2695    
2696    
2697    
2698    // *************** Group ***************
2699    // *
2700    
2701        /** @brief Constructor.
2702         *
2703         * @param file   - pointer to the gig::File object
2704         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
2705         *                 NULL if this is a new Group
2706         */
2707        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
2708            pFile      = file;
2709            pNameChunk = ck3gnm;
2710            ::LoadString(pNameChunk, Name);
2711        }
2712    
2713        Group::~Group() {
2714        }
2715    
2716        /** @brief Update chunks with current group settings.
2717         *
2718         * Apply current Group field values to the respective. You have to call
2719         * File::Save() to make changes persistent.
2720         */
2721        void Group::UpdateChunks() {
2722            // make sure <3gri> and <3gnl> list chunks exist
2723            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
2724            if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
2725            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
2726            if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);
2727            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
2728            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
2729        }
2730    
2731        /**
2732         * Returns the first Sample of this Group. You have to call this method
2733         * once before you use GetNextSample().
2734         *
2735         * <b>Notice:</b> this method might block for a long time, in case the
2736         * samples of this .gig file were not scanned yet
2737         *
2738         * @returns  pointer address to first Sample or NULL if there is none
2739         *           applied to this Group
2740         * @see      GetNextSample()
2741         */
2742        Sample* Group::GetFirstSample() {
2743            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2744            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
2745                if (pSample->GetGroup() == this) return pSample;
2746            }
2747            return NULL;
2748        }
2749    
2750        /**
2751         * Returns the next Sample of the Group. You have to call
2752         * GetFirstSample() once before you can use this method. By calling this
2753         * method multiple times it iterates through the Samples assigned to
2754         * this Group.
2755         *
2756         * @returns  pointer address to the next Sample of this Group or NULL if
2757         *           end reached
2758         * @see      GetFirstSample()
2759         */
2760        Sample* Group::GetNextSample() {
2761            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2762            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
2763                if (pSample->GetGroup() == this) return pSample;
2764            }
2765            return NULL;
2766        }
2767    
2768        /**
2769         * Move Sample given by \a pSample from another Group to this Group.
2770         */
2771        void Group::AddSample(Sample* pSample) {
2772            pSample->pGroup = this;
2773        }
2774    
2775        /**
2776         * Move all members of this group to another group (preferably the 1st
2777         * one except this). This method is called explicitly by
2778         * File::DeleteGroup() thus when a Group was deleted. This code was
2779         * intentionally not placed in the destructor!
2780         */
2781        void Group::MoveAll() {
2782            // get "that" other group first
2783            Group* pOtherGroup = NULL;
2784            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
2785                if (pOtherGroup != this) break;
2786            }
2787            if (!pOtherGroup) throw Exception(
2788                "Could not move samples to another group, since there is no "
2789                "other Group. This is a bug, report it!"
2790            );
2791            // now move all samples of this group to the other group
2792            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
2793                pOtherGroup->AddSample(pSample);
2794            }
2795      }      }
2796    
2797    
# Line 1707  namespace { Line 2799  namespace {
2799  // *************** File ***************  // *************** File ***************
2800  // *  // *
2801    
2802        File::File() : DLS::File() {
2803            pGroups = NULL;
2804            pInfo->UseFixedLengthStrings = true;
2805        }
2806    
2807      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2808          pSamples     = NULL;          pGroups = NULL;
2809          pInstruments = NULL;          pInfo->UseFixedLengthStrings = true;
2810      }      }
2811    
2812      File::~File() {      File::~File() {
2813          // free samples          if (pGroups) {
2814          if (pSamples) {              std::list<Group*>::iterator iter = pGroups->begin();
2815              SamplesIterator = pSamples->begin();              std::list<Group*>::iterator end  = pGroups->end();
2816              while (SamplesIterator != pSamples->end() ) {              while (iter != end) {
2817                  delete (*SamplesIterator);                  delete *iter;
2818                  SamplesIterator++;                  ++iter;
             }  
             pSamples->clear();  
             delete pSamples;  
   
         }  
         // free instruments  
         if (pInstruments) {  
             InstrumentsIterator = pInstruments->begin();  
             while (InstrumentsIterator != pInstruments->end() ) {  
                 delete (*InstrumentsIterator);  
                 InstrumentsIterator++;  
2819              }              }
2820              pInstruments->clear();              delete pGroups;
             delete pInstruments;  
2821          }          }
2822      }      }
2823    
# Line 1749  namespace { Line 2834  namespace {
2834          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2835      }      }
2836    
2837        /** @brief Add a new sample.
2838         *
2839         * This will create a new Sample object for the gig file. You have to
2840         * call Save() to make this persistent to the file.
2841         *
2842         * @returns pointer to new Sample object
2843         */
2844        Sample* File::AddSample() {
2845           if (!pSamples) LoadSamples();
2846           __ensureMandatoryChunksExist();
2847           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2848           // create new Sample object and its respective 'wave' list chunk
2849           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2850           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2851           pSamples->push_back(pSample);
2852           return pSample;
2853        }
2854    
2855        /** @brief Delete a sample.
2856         *
2857         * This will delete the given Sample object from the gig file. You have
2858         * to call Save() to make this persistent to the file.
2859         *
2860         * @param pSample - sample to delete
2861         * @throws gig::Exception if given sample could not be found
2862         */
2863        void File::DeleteSample(Sample* pSample) {
2864            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2865            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2866            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2867            pSamples->erase(iter);
2868            delete pSample;
2869        }
2870    
2871        void File::LoadSamples() {
2872            LoadSamples(NULL);
2873        }
2874    
2875      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
2876          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          // Groups must be loaded before samples, because samples will try
2877          if (wvpl) {          // to resolve the group they belong to
2878              // just for progress calculation          LoadGroups();
2879              int iSampleIndex  = 0;  
2880              int iTotalSamples = wvpl->CountSubLists(LIST_TYPE_WAVE);          if (!pSamples) pSamples = new SampleList;
2881    
2882              unsigned long wvplFileOffset = wvpl->GetFilePos();          RIFF::File* file = pRIFF;
2883              RIFF::List* wave = wvpl->GetFirstSubList();  
2884              while (wave) {          // just for progress calculation
2885                  if (wave->GetListType() == LIST_TYPE_WAVE) {          int iSampleIndex  = 0;
2886                      // notify current progress          int iTotalSamples = WavePoolCount;
2887                      const float subprogress = (float) iSampleIndex / (float) iTotalSamples;  
2888                      __notify_progress(pProgress, subprogress);          // check if samples should be loaded from extension files
2889            int lastFileNo = 0;
2890            for (int i = 0 ; i < WavePoolCount ; i++) {
2891                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2892            }
2893            String name(pRIFF->GetFileName());
2894            int nameLen = name.length();
2895            char suffix[6];
2896            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2897    
2898            for (int fileNo = 0 ; ; ) {
2899                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
2900                if (wvpl) {
2901                    unsigned long wvplFileOffset = wvpl->GetFilePos();
2902                    RIFF::List* wave = wvpl->GetFirstSubList();
2903                    while (wave) {
2904                        if (wave->GetListType() == LIST_TYPE_WAVE) {
2905                            // notify current progress
2906                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2907                            __notify_progress(pProgress, subprogress);
2908    
2909                      if (!pSamples) pSamples = new SampleList;                          unsigned long waveFileOffset = wave->GetFilePos();
2910                      unsigned long waveFileOffset = wave->GetFilePos();                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
                     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));  
2911    
2912                      iSampleIndex++;                          iSampleIndex++;
2913                        }
2914                        wave = wvpl->GetNextSubList();
2915                  }                  }
2916                  wave = wvpl->GetNextSubList();  
2917              }                  if (fileNo == lastFileNo) break;
2918              __notify_progress(pProgress, 1.0); // notify done  
2919                    // open extension file (*.gx01, *.gx02, ...)
2920                    fileNo++;
2921                    sprintf(suffix, ".gx%02d", fileNo);
2922                    name.replace(nameLen, 5, suffix);
2923                    file = new RIFF::File(name);
2924                    ExtensionFiles.push_back(file);
2925                } else break;
2926          }          }
2927          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2928            __notify_progress(pProgress, 1.0); // notify done
2929      }      }
2930    
2931      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
2932          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2933          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2934          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2935          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2936      }      }
2937    
2938      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2939          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2940          InstrumentsIterator++;          InstrumentsIterator++;
2941          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2942      }      }
2943    
2944      /**      /**
# Line 1820  namespace { Line 2971  namespace {
2971          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2972          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2973          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2974              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2975              InstrumentsIterator++;              InstrumentsIterator++;
2976          }          }
2977          return NULL;          return NULL;
2978      }      }
2979    
2980        /** @brief Add a new instrument definition.
2981         *
2982         * This will create a new Instrument object for the gig file. You have
2983         * to call Save() to make this persistent to the file.
2984         *
2985         * @returns pointer to new Instrument object
2986         */
2987        Instrument* File::AddInstrument() {
2988           if (!pInstruments) LoadInstruments();
2989           __ensureMandatoryChunksExist();
2990           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2991           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2992           Instrument* pInstrument = new Instrument(this, lstInstr);
2993           pInstruments->push_back(pInstrument);
2994           return pInstrument;
2995        }
2996    
2997        /** @brief Delete an instrument.
2998         *
2999         * This will delete the given Instrument object from the gig file. You
3000         * have to call Save() to make this persistent to the file.
3001         *
3002         * @param pInstrument - instrument to delete
3003         * @throws gig::Excption if given instrument could not be found
3004         */
3005        void File::DeleteInstrument(Instrument* pInstrument) {
3006            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
3007            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
3008            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
3009            pInstruments->erase(iter);
3010            delete pInstrument;
3011        }
3012    
3013        void File::LoadInstruments() {
3014            LoadInstruments(NULL);
3015        }
3016    
3017      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
3018            if (!pInstruments) pInstruments = new InstrumentList;
3019          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3020          if (lstInstruments) {          if (lstInstruments) {
3021              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 1841  namespace { Line 3030  namespace {
3030                      progress_t subprogress;                      progress_t subprogress;
3031                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
3032    
                     if (!pInstruments) pInstruments = new InstrumentList;  
3033                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
3034    
3035                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 1850  namespace { Line 3038  namespace {
3038              }              }
3039              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
3040          }          }
3041          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
3042    
3043        Group* File::GetFirstGroup() {
3044            if (!pGroups) LoadGroups();
3045            // there must always be at least one group
3046            GroupsIterator = pGroups->begin();
3047            return *GroupsIterator;
3048        }
3049    
3050        Group* File::GetNextGroup() {
3051            if (!pGroups) return NULL;
3052            ++GroupsIterator;
3053            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
3054        }
3055    
3056        /**
3057         * Returns the group with the given index.
3058         *
3059         * @param index - number of the sought group (0..n)
3060         * @returns sought group or NULL if there's no such group
3061         */
3062        Group* File::GetGroup(uint index) {
3063            if (!pGroups) LoadGroups();
3064            GroupsIterator = pGroups->begin();
3065            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
3066                if (i == index) return *GroupsIterator;
3067                ++GroupsIterator;
3068            }
3069            return NULL;
3070        }
3071    
3072        Group* File::AddGroup() {
3073            if (!pGroups) LoadGroups();
3074            // there must always be at least one group
3075            __ensureMandatoryChunksExist();
3076            Group* pGroup = new Group(this, NULL);
3077            pGroups->push_back(pGroup);
3078            return pGroup;
3079        }
3080    
3081        void File::DeleteGroup(Group* pGroup) {
3082            if (!pGroups) LoadGroups();
3083            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3084            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3085            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3086            // move all members of this group to another group
3087            pGroup->MoveAll();
3088            pGroups->erase(iter);
3089            delete pGroup;
3090        }
3091    
3092        void File::LoadGroups() {
3093            if (!pGroups) pGroups = new std::list<Group*>;
3094            // try to read defined groups from file
3095            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
3096            if (lst3gri) {
3097                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
3098                if (lst3gnl) {
3099                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3100                    while (ck) {
3101                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3102                            pGroups->push_back(new Group(this, ck));
3103                        }
3104                        ck = lst3gnl->GetNextSubChunk();
3105                    }
3106                }
3107            }
3108            // if there were no group(s), create at least the mandatory default group
3109            if (!pGroups->size()) {
3110                Group* pGroup = new Group(this, NULL);
3111                pGroup->Name = "Default Group";
3112                pGroups->push_back(pGroup);
3113            }
3114      }      }
3115    
3116    

Legend:
Removed from v.518  
changed lines
  Added in v.1050

  ViewVC Help
Powered by ViewVC