/[svn]/libgig/trunk/src/gig.cpp
ViewVC logotype

Diff of /libgig/trunk/src/gig.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 516 by schoenebeck, Sat May 7 21:24:04 2005 UTC revision 1192 by persson, Thu May 17 10:12:08 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 237  namespace { Line 254  namespace {
254  }  }
255    
256    
257    
258    // *************** Other Internal functions  ***************
259    // *
260    
261        static split_type_t __resolveSplitType(dimension_t dimension) {
262            return (
263                dimension == dimension_layer ||
264                dimension == dimension_samplechannel ||
265                dimension == dimension_releasetrigger ||
266                dimension == dimension_keyboard ||
267                dimension == dimension_roundrobin ||
268                dimension == dimension_random ||
269                dimension == dimension_smartmidi ||
270                dimension == dimension_roundrobinkeyboard
271            ) ? split_type_bit : split_type_normal;
272        }
273    
274        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
275            return (dimension_definition.split_type == split_type_normal)
276            ? int(128.0 / dimension_definition.zones) : 0;
277        }
278    
279    
280    
281  // *************** Sample ***************  // *************** Sample ***************
282  // *  // *
283    
284      unsigned int Sample::Instances = 0;      unsigned int Sample::Instances = 0;
285      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
286    
287      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      /** @brief Constructor.
288         *
289         * Load an existing sample or create a new one. A 'wave' list chunk must
290         * be given to this constructor. In case the given 'wave' list chunk
291         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
292         * format and sample data will be loaded from there, otherwise default
293         * values will be used and those chunks will be created when
294         * File::Save() will be called later on.
295         *
296         * @param pFile          - pointer to gig::File where this sample is
297         *                         located (or will be located)
298         * @param waveList       - pointer to 'wave' list chunk which is (or
299         *                         will be) associated with this sample
300         * @param WavePoolOffset - offset of this sample data from wave pool
301         *                         ('wvpl') list chunk
302         * @param fileNo         - number of an extension file where this sample
303         *                         is located, 0 otherwise
304         */
305        Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
306            static const DLS::Info::FixedStringLength fixedStringLengths[] = {
307                { CHUNK_ID_INAM, 64 },
308                { 0, 0 }
309            };
310            pInfo->FixedStringLengths = fixedStringLengths;
311          Instances++;          Instances++;
312            FileNo = fileNo;
313    
314          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
315          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
316          SampleGroup = _3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
317                pGroup = pFile->GetGroup(iSampleGroup);
318          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          } else { // '3gix' chunk missing
319          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              // by default assigned to that mandatory "Default Group"
320          Manufacturer      = smpl->ReadInt32();              pGroup = pFile->GetGroup(0);
321          Product           = smpl->ReadInt32();          }
322          SamplePeriod      = smpl->ReadInt32();  
323          MIDIUnityNote     = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
324          FineTune          = smpl->ReadInt32();          if (pCkSmpl) {
325          smpl->Read(&SMPTEFormat, 1, 4);              Manufacturer  = pCkSmpl->ReadInt32();
326          SMPTEOffset       = smpl->ReadInt32();              Product       = pCkSmpl->ReadInt32();
327          Loops             = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
328          smpl->ReadInt32(); // manufByt              MIDIUnityNote = pCkSmpl->ReadInt32();
329          LoopID            = smpl->ReadInt32();              FineTune      = pCkSmpl->ReadInt32();
330          smpl->Read(&LoopType, 1, 4);              pCkSmpl->Read(&SMPTEFormat, 1, 4);
331          LoopStart         = smpl->ReadInt32();              SMPTEOffset   = pCkSmpl->ReadInt32();
332          LoopEnd           = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
333          LoopFraction      = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
334          LoopPlayCount     = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
335                pCkSmpl->Read(&LoopType, 1, 4);
336                LoopStart     = pCkSmpl->ReadInt32();
337                LoopEnd       = pCkSmpl->ReadInt32();
338                LoopFraction  = pCkSmpl->ReadInt32();
339                LoopPlayCount = pCkSmpl->ReadInt32();
340            } else { // 'smpl' chunk missing
341                // use default values
342                Manufacturer  = 0;
343                Product       = 0;
344                SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
345                MIDIUnityNote = 64;
346                FineTune      = 0;
347                SMPTEFormat   = smpte_format_no_offset;
348                SMPTEOffset   = 0;
349                Loops         = 0;
350                LoopID        = 0;
351                LoopType      = loop_type_normal;
352                LoopStart     = 0;
353                LoopEnd       = 0;
354                LoopFraction  = 0;
355                LoopPlayCount = 0;
356            }
357    
358          FrameTable                 = NULL;          FrameTable                 = NULL;
359          SamplePos                  = 0;          SamplePos                  = 0;
# Line 297  namespace { Line 384  namespace {
384          }          }
385          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
386    
387          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
388        }
389    
390        /**
391         * Apply sample and its settings to the respective RIFF chunks. You have
392         * to call File::Save() to make changes persistent.
393         *
394         * Usually there is absolutely no need to call this method explicitly.
395         * It will be called automatically when File::Save() was called.
396         *
397         * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
398         *                        was provided yet
399         * @throws gig::Exception if there is any invalid sample setting
400         */
401        void Sample::UpdateChunks() {
402            // first update base class's chunks
403            DLS::Sample::UpdateChunks();
404    
405            // make sure 'smpl' chunk exists
406            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
407            if (!pCkSmpl) {
408                pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
409                memset(pCkSmpl->LoadChunkData(), 0, 60);
410            }
411            // update 'smpl' chunk
412            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
413            SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
414            store32(&pData[0], Manufacturer);
415            store32(&pData[4], Product);
416            store32(&pData[8], SamplePeriod);
417            store32(&pData[12], MIDIUnityNote);
418            store32(&pData[16], FineTune);
419            store32(&pData[20], SMPTEFormat);
420            store32(&pData[24], SMPTEOffset);
421            store32(&pData[28], Loops);
422    
423            // we skip 'manufByt' for now (4 bytes)
424    
425            store32(&pData[36], LoopID);
426            store32(&pData[40], LoopType);
427            store32(&pData[44], LoopStart);
428            store32(&pData[48], LoopEnd);
429            store32(&pData[52], LoopFraction);
430            store32(&pData[56], LoopPlayCount);
431    
432            // make sure '3gix' chunk exists
433            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
434            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
435            // determine appropriate sample group index (to be stored in chunk)
436            uint16_t iSampleGroup = 0; // 0 refers to default sample group
437            File* pFile = static_cast<File*>(pParent);
438            if (pFile->pGroups) {
439                std::list<Group*>::iterator iter = pFile->pGroups->begin();
440                std::list<Group*>::iterator end  = pFile->pGroups->end();
441                for (int i = 0; iter != end; i++, iter++) {
442                    if (*iter == pGroup) {
443                        iSampleGroup = i;
444                        break; // found
445                    }
446                }
447            }
448            // update '3gix' chunk
449            pData = (uint8_t*) pCk3gix->LoadChunkData();
450            store16(&pData[0], iSampleGroup);
451      }      }
452    
453      /// 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 650  namespace {
650          RAMCache.Size   = 0;          RAMCache.Size   = 0;
651      }      }
652    
653        /** @brief Resize sample.
654         *
655         * Resizes the sample's wave form data, that is the actual size of
656         * sample wave data possible to be written for this sample. This call
657         * will return immediately and just schedule the resize operation. You
658         * should call File::Save() to actually perform the resize operation(s)
659         * "physically" to the file. As this can take a while on large files, it
660         * is recommended to call Resize() first on all samples which have to be
661         * resized and finally to call File::Save() to perform all those resize
662         * operations in one rush.
663         *
664         * The actual size (in bytes) is dependant to the current FrameSize
665         * value. You may want to set FrameSize before calling Resize().
666         *
667         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
668         * enlarged samples before calling File::Save() as this might exceed the
669         * current sample's boundary!
670         *
671         * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
672         * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
673         * other formats will fail!
674         *
675         * @param iNewSize - new sample wave data size in sample points (must be
676         *                   greater than zero)
677         * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
678         *                         or if \a iNewSize is less than 1
679         * @throws gig::Exception if existing sample is compressed
680         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
681         *      DLS::Sample::FormatTag, File::Save()
682         */
683        void Sample::Resize(int iNewSize) {
684            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
685            DLS::Sample::Resize(iNewSize);
686        }
687    
688      /**      /**
689       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
690       * 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 774  namespace {
774       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
775       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
776       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
777         * @param pDimRgn          dimension region with looping information
778       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
779       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
780       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
781       */       */
782      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,
783                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
784          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
785          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
786    
787          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
788    
789          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
790    
791              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
792                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
793    
794                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
795                      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  
796    
797                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
798                              // determine the end position within the loop first,                          do {
799                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
800                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
801                              // backward playback  
802                                if (!pPlaybackState->reverse) { // forward playback
803                              unsigned long swapareastart       = totalreadsamples;                                  do {
804                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
805                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
806                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
807                                        totalreadsamples += readsamples;
808                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
809                                            pPlaybackState->reverse = true;
810                              // read samples for backward playback                                          break;
811                              do {                                      }
812                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
813                                  samplestoreadinloop -= readsamples;                              }
814                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
815    
816                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
817                                    // determine the end position within the loop first,
818                                    // read forward from that 'end' and finally after
819                                    // reading, swap all sample frames so it reflects
820                                    // backward playback
821    
822                                    unsigned long swapareastart       = totalreadsamples;
823                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
824                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
825                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
826    
827                                    SetPos(reverseplaybackend);
828    
829                                    // read samples for backward playback
830                                    do {
831                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
832                                        samplestoreadinloop -= readsamples;
833                                        samplestoread       -= readsamples;
834                                        totalreadsamples    += readsamples;
835                                    } while (samplestoreadinloop && readsamples);
836    
837                                    SetPos(reverseplaybackend); // pretend we really read backwards
838    
839                                    if (reverseplaybackend == loop.LoopStart) {
840                                        pPlaybackState->loop_cycles_left--;
841                                        pPlaybackState->reverse = false;
842                                    }
843    
844                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
845                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
846                              }                              }
847                            } while (samplestoread && readsamples);
848                            break;
849                        }
850    
851                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
852                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
853                          }                          if (!pPlaybackState->reverse) do {
854                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
855                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
856                  }                              samplestoread    -= readsamples;
857                                totalreadsamples += readsamples;
858                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
859                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
860                      if (!pPlaybackState->reverse) do {                                  break;
861                          samplestoloopend  = this->LoopEnd - GetPos();                              }
862                          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);  
863    
864                      if (!samplestoread) break;                          if (!samplestoread) break;
865    
866                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
867                      // determine the end position within the loop first,                          // determine the end position within the loop first,
868                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
869                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
870                      // backward playback                          // backward playback
871    
872                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
873                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
874                      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)
875                                                                                : samplestoread;                                                                                    : samplestoread;
876                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
877    
878                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
879    
880                      // read samples for backward playback                          // read samples for backward playback
881                      do {                          do {
882                          // 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
883                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
884                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
885                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
886                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
887                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
888                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
889                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
890                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
891                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
892                          }                              }
893                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
894    
895                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
896    
897                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
898                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
899                      break;                          break;
900                  }                      }
901    
902                  default: case loop_type_normal: {                      default: case loop_type_normal: {
903                      do {                          do {
904                          // 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
905                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
906                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
907                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
908                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
909                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
910                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
911                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
912                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
913                          }                              }
914                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
915                      break;                          break;
916                        }
917                  }                  }
918              }              }
919          }          }
# Line 751  namespace { Line 943  namespace {
943       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
944       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
945       *       *
946         * For 16 bit samples, the data in the buffer will be int16_t
947         * (using native endianness). For 24 bit, the buffer will
948         * contain three bytes per sample, little-endian.
949         *
950       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
951       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
952       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 761  namespace { Line 957  namespace {
957          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
958          if (!Compressed) {          if (!Compressed) {
959              if (BitDepth == 24) {              if (BitDepth == 24) {
960                  // 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);  
                 }  
961              }              }
962              else { // 16 bit              else { // 16 bit
963                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 811  namespace { Line 987  namespace {
987    
988              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
989              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
990                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
991              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
992    
993              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 892  namespace { Line 1069  namespace {
1069                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1070                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1071    
1072                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1073                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1074                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1075                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1076                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1077                          }                          }
1078                          else { // Mono                          else { // Mono
1079                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1080                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1081                              pDst += copysamples;                              pDst24 += copysamples * 3;
1082                          }                          }
1083                      }                      }
1084                      else { // 16 bit                      else { // 16 bit
# Line 943  namespace { Line 1120  namespace {
1120          }          }
1121      }      }
1122    
1123        /** @brief Write sample wave data.
1124         *
1125         * Writes \a SampleCount number of sample points from the buffer pointed
1126         * by \a pBuffer and increments the position within the sample. Use this
1127         * method to directly write the sample data to disk, i.e. if you don't
1128         * want or cannot load the whole sample data into RAM.
1129         *
1130         * You have to Resize() the sample to the desired size and call
1131         * File::Save() <b>before</b> using Write().
1132         *
1133         * Note: there is currently no support for writing compressed samples.
1134         *
1135         * @param pBuffer     - source buffer
1136         * @param SampleCount - number of sample points to write
1137         * @throws DLS::Exception if current sample size is too small
1138         * @throws gig::Exception if sample is compressed
1139         * @see DLS::LoadSampleData()
1140         */
1141        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1142            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1143            return DLS::Sample::Write(pBuffer, SampleCount);
1144        }
1145    
1146      /**      /**
1147       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1148       * 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 1185  namespace {
1185          }          }
1186      }      }
1187    
1188        /**
1189         * Returns pointer to the Group this Sample belongs to. In the .gig
1190         * format a sample always belongs to one group. If it wasn't explicitly
1191         * assigned to a certain group, it will be automatically assigned to a
1192         * default group.
1193         *
1194         * @returns Sample's Group (never NULL)
1195         */
1196        Group* Sample::GetGroup() const {
1197            return pGroup;
1198        }
1199    
1200      Sample::~Sample() {      Sample::~Sample() {
1201          Instances--;          Instances--;
1202          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1007  namespace { Line 1219  namespace {
1219      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1220          Instances++;          Instances++;
1221    
1222            pSample = NULL;
1223    
1224          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1225          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1226    
1227          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1228          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1229          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1230          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1231          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1232          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1233          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1234          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1235          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1236          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1237          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1238          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1239          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1240          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1241          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1242          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1243          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1244          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1245          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1246          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1247          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1248          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1249          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1250          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1251          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1252          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1253          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1254          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1255          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1256          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1257          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1258          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1259          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1260          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1261          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1262          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1263          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1264          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1265          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1266          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1267          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1268          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1269          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1270          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1271          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1272          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1273          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1274          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1275          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1276          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1277          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1278          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1279              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1280              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1281          }                  VelocityResponseDepth = velocityresponse;
1282          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1283              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1284              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1285          }              } else if (velocityresponse < 15) {
1286          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1287              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1288              VelocityResponseDepth = velocityresponse - 10;              } else {
1289                    VelocityResponseCurve = curve_type_unknown;
1290                    VelocityResponseDepth = 0;
1291                }
1292                uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1293                if (releasevelocityresponse < 5) {
1294                    ReleaseVelocityResponseCurve = curve_type_nonlinear;
1295                    ReleaseVelocityResponseDepth = releasevelocityresponse;
1296                } else if (releasevelocityresponse < 10) {
1297                    ReleaseVelocityResponseCurve = curve_type_linear;
1298                    ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1299                } else if (releasevelocityresponse < 15) {
1300                    ReleaseVelocityResponseCurve = curve_type_special;
1301                    ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1302                } else {
1303                    ReleaseVelocityResponseCurve = curve_type_unknown;
1304                    ReleaseVelocityResponseDepth = 0;
1305                }
1306                VelocityResponseCurveScaling = _3ewa->ReadUint8();
1307                AttenuationControllerThreshold = _3ewa->ReadInt8();
1308                _3ewa->ReadInt32(); // unknown
1309                SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1310                _3ewa->ReadInt16(); // unknown
1311                uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1312                PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1313                if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1314                else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1315                else                                       DimensionBypass = dim_bypass_ctrl_none;
1316                uint8_t pan = _3ewa->ReadUint8();
1317                Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1318                SelfMask = _3ewa->ReadInt8() & 0x01;
1319                _3ewa->ReadInt8(); // unknown
1320                uint8_t lfo3ctrl = _3ewa->ReadUint8();
1321                LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1322                LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1323                InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1324                AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1325                uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1326                LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1327                LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1328                LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1329                bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1330                uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1331                LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1332                LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1333                LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1334                VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1335                                                            : vcf_res_ctrl_none;
1336                uint16_t eg3depth = _3ewa->ReadUint16();
1337                EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1338                                            : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1339                _3ewa->ReadInt16(); // unknown
1340                ChannelOffset = _3ewa->ReadUint8() / 4;
1341                uint8_t regoptions = _3ewa->ReadUint8();
1342                MSDecode           = regoptions & 0x01; // bit 0
1343                SustainDefeat      = regoptions & 0x02; // bit 1
1344                _3ewa->ReadInt16(); // unknown
1345                VelocityUpperLimit = _3ewa->ReadInt8();
1346                _3ewa->ReadInt8(); // unknown
1347                _3ewa->ReadInt16(); // unknown
1348                ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1349                _3ewa->ReadInt8(); // unknown
1350                _3ewa->ReadInt8(); // unknown
1351                EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1352                uint8_t vcfcutoff = _3ewa->ReadUint8();
1353                VCFEnabled = vcfcutoff & 0x80; // bit 7
1354                VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1355                VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1356                uint8_t vcfvelscale = _3ewa->ReadUint8();
1357                VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1358                VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1359                _3ewa->ReadInt8(); // unknown
1360                uint8_t vcfresonance = _3ewa->ReadUint8();
1361                VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1362                VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1363                uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1364                VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1365                VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1366                uint8_t vcfvelocity = _3ewa->ReadUint8();
1367                VCFVelocityDynamicRange = vcfvelocity % 5;
1368                VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1369                VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1370                if (VCFType == vcf_type_lowpass) {
1371                    if (lfo3ctrl & 0x40) // bit 6
1372                        VCFType = vcf_type_lowpassturbo;
1373                }
1374                if (_3ewa->RemainingBytes() >= 8) {
1375                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1376                } else {
1377                    memset(DimensionUpperLimits, 0, 8);
1378                }
1379            } else { // '3ewa' chunk does not exist yet
1380                // use default values
1381                LFO3Frequency                   = 1.0;
1382                EG3Attack                       = 0.0;
1383                LFO1InternalDepth               = 0;
1384                LFO3InternalDepth               = 0;
1385                LFO1ControlDepth                = 0;
1386                LFO3ControlDepth                = 0;
1387                EG1Attack                       = 0.0;
1388                EG1Decay1                       = 0.0;
1389                EG1Sustain                      = 0;
1390                EG1Release                      = 0.0;
1391                EG1Controller.type              = eg1_ctrl_t::type_none;
1392                EG1Controller.controller_number = 0;
1393                EG1ControllerInvert             = false;
1394                EG1ControllerAttackInfluence    = 0;
1395                EG1ControllerDecayInfluence     = 0;
1396                EG1ControllerReleaseInfluence   = 0;
1397                EG2Controller.type              = eg2_ctrl_t::type_none;
1398                EG2Controller.controller_number = 0;
1399                EG2ControllerInvert             = false;
1400                EG2ControllerAttackInfluence    = 0;
1401                EG2ControllerDecayInfluence     = 0;
1402                EG2ControllerReleaseInfluence   = 0;
1403                LFO1Frequency                   = 1.0;
1404                EG2Attack                       = 0.0;
1405                EG2Decay1                       = 0.0;
1406                EG2Sustain                      = 0;
1407                EG2Release                      = 0.0;
1408                LFO2ControlDepth                = 0;
1409                LFO2Frequency                   = 1.0;
1410                LFO2InternalDepth               = 0;
1411                EG1Decay2                       = 0.0;
1412                EG1InfiniteSustain              = false;
1413                EG1PreAttack                    = 1000;
1414                EG2Decay2                       = 0.0;
1415                EG2InfiniteSustain              = false;
1416                EG2PreAttack                    = 1000;
1417                VelocityResponseCurve           = curve_type_nonlinear;
1418                VelocityResponseDepth           = 3;
1419                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1420                ReleaseVelocityResponseDepth    = 3;
1421                VelocityResponseCurveScaling    = 32;
1422                AttenuationControllerThreshold  = 0;
1423                SampleStartOffset               = 0;
1424                PitchTrack                      = true;
1425                DimensionBypass                 = dim_bypass_ctrl_none;
1426                Pan                             = 0;
1427                SelfMask                        = true;
1428                LFO3Controller                  = lfo3_ctrl_modwheel;
1429                LFO3Sync                        = false;
1430                InvertAttenuationController     = false;
1431                AttenuationController.type      = attenuation_ctrl_t::type_none;
1432                AttenuationController.controller_number = 0;
1433                LFO2Controller                  = lfo2_ctrl_internal;
1434                LFO2FlipPhase                   = false;
1435                LFO2Sync                        = false;
1436                LFO1Controller                  = lfo1_ctrl_internal;
1437                LFO1FlipPhase                   = false;
1438                LFO1Sync                        = false;
1439                VCFResonanceController          = vcf_res_ctrl_none;
1440                EG3Depth                        = 0;
1441                ChannelOffset                   = 0;
1442                MSDecode                        = false;
1443                SustainDefeat                   = false;
1444                VelocityUpperLimit              = 0;
1445                ReleaseTriggerDecay             = 0;
1446                EG1Hold                         = false;
1447                VCFEnabled                      = false;
1448                VCFCutoff                       = 0;
1449                VCFCutoffController             = vcf_cutoff_ctrl_none;
1450                VCFCutoffControllerInvert       = false;
1451                VCFVelocityScale                = 0;
1452                VCFResonance                    = 0;
1453                VCFResonanceDynamic             = false;
1454                VCFKeyboardTracking             = false;
1455                VCFKeyboardTrackingBreakpoint   = 0;
1456                VCFVelocityDynamicRange         = 0x04;
1457                VCFVelocityCurve                = curve_type_linear;
1458                VCFType                         = vcf_type_lowpass;
1459                memset(DimensionUpperLimits, 0, 8);
1460            }
1461    
1462            pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
1463                                                         VelocityResponseDepth,
1464                                                         VelocityResponseCurveScaling);
1465    
1466            curve_type_t curveType = ReleaseVelocityResponseCurve;
1467            uint8_t depth = ReleaseVelocityResponseDepth;
1468    
1469            // this models a strange behaviour or bug in GSt: two of the
1470            // velocity response curves for release time are not used even
1471            // if specified, instead another curve is chosen.
1472            if ((curveType == curve_type_nonlinear && depth == 0) ||
1473                (curveType == curve_type_special   && depth == 4)) {
1474                curveType = curve_type_nonlinear;
1475                depth = 3;
1476            }
1477            pVelocityReleaseTable = GetVelocityTable(curveType, depth, 0);
1478    
1479            curveType = VCFVelocityCurve;
1480            depth = VCFVelocityDynamicRange;
1481    
1482            // even stranger GSt: two of the velocity response curves for
1483            // filter cutoff are not used, instead another special curve
1484            // is chosen. This curve is not used anywhere else.
1485            if ((curveType == curve_type_nonlinear && depth == 0) ||
1486                (curveType == curve_type_special   && depth == 4)) {
1487                curveType = curve_type_special;
1488                depth = 5;
1489          }          }
1490          else {          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1491              VelocityResponseCurve = curve_type_unknown;                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1492              VelocityResponseDepth = 0;  
1493            SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1494            VelocityTable = 0;
1495        }
1496    
1497        /**
1498         * Apply dimension region settings to the respective RIFF chunks. You
1499         * have to call File::Save() to make changes persistent.
1500         *
1501         * Usually there is absolutely no need to call this method explicitly.
1502         * It will be called automatically when File::Save() was called.
1503         */
1504        void DimensionRegion::UpdateChunks() {
1505            // first update base class's chunk
1506            DLS::Sampler::UpdateChunks();
1507    
1508            // make sure '3ewa' chunk exists
1509            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1510            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1511            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1512    
1513            // update '3ewa' chunk with DimensionRegion's current settings
1514    
1515            const uint32_t chunksize = _3ewa->GetNewSize();
1516            store32(&pData[0], chunksize); // unknown, always chunk size?
1517    
1518            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1519            store32(&pData[4], lfo3freq);
1520    
1521            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1522            store32(&pData[8], eg3attack);
1523    
1524            // next 2 bytes unknown
1525    
1526            store16(&pData[14], LFO1InternalDepth);
1527    
1528            // next 2 bytes unknown
1529    
1530            store16(&pData[18], LFO3InternalDepth);
1531    
1532            // next 2 bytes unknown
1533    
1534            store16(&pData[22], LFO1ControlDepth);
1535    
1536            // next 2 bytes unknown
1537    
1538            store16(&pData[26], LFO3ControlDepth);
1539    
1540            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1541            store32(&pData[28], eg1attack);
1542    
1543            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1544            store32(&pData[32], eg1decay1);
1545    
1546            // next 2 bytes unknown
1547    
1548            store16(&pData[38], EG1Sustain);
1549    
1550            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1551            store32(&pData[40], eg1release);
1552    
1553            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1554            pData[44] = eg1ctl;
1555    
1556            const uint8_t eg1ctrloptions =
1557                (EG1ControllerInvert) ? 0x01 : 0x00 |
1558                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1559                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1560                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1561            pData[45] = eg1ctrloptions;
1562    
1563            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1564            pData[46] = eg2ctl;
1565    
1566            const uint8_t eg2ctrloptions =
1567                (EG2ControllerInvert) ? 0x01 : 0x00 |
1568                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1569                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1570                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1571            pData[47] = eg2ctrloptions;
1572    
1573            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1574            store32(&pData[48], lfo1freq);
1575    
1576            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1577            store32(&pData[52], eg2attack);
1578    
1579            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1580            store32(&pData[56], eg2decay1);
1581    
1582            // next 2 bytes unknown
1583    
1584            store16(&pData[62], EG2Sustain);
1585    
1586            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1587            store32(&pData[64], eg2release);
1588    
1589            // next 2 bytes unknown
1590    
1591            store16(&pData[70], LFO2ControlDepth);
1592    
1593            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1594            store32(&pData[72], lfo2freq);
1595    
1596            // next 2 bytes unknown
1597    
1598            store16(&pData[78], LFO2InternalDepth);
1599    
1600            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1601            store32(&pData[80], eg1decay2);
1602    
1603            // next 2 bytes unknown
1604    
1605            store16(&pData[86], EG1PreAttack);
1606    
1607            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1608            store32(&pData[88], eg2decay2);
1609    
1610            // next 2 bytes unknown
1611    
1612            store16(&pData[94], EG2PreAttack);
1613    
1614            {
1615                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1616                uint8_t velocityresponse = VelocityResponseDepth;
1617                switch (VelocityResponseCurve) {
1618                    case curve_type_nonlinear:
1619                        break;
1620                    case curve_type_linear:
1621                        velocityresponse += 5;
1622                        break;
1623                    case curve_type_special:
1624                        velocityresponse += 10;
1625                        break;
1626                    case curve_type_unknown:
1627                    default:
1628                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1629                }
1630                pData[96] = velocityresponse;
1631            }
1632    
1633            {
1634                if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1635                uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1636                switch (ReleaseVelocityResponseCurve) {
1637                    case curve_type_nonlinear:
1638                        break;
1639                    case curve_type_linear:
1640                        releasevelocityresponse += 5;
1641                        break;
1642                    case curve_type_special:
1643                        releasevelocityresponse += 10;
1644                        break;
1645                    case curve_type_unknown:
1646                    default:
1647                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1648                }
1649                pData[97] = releasevelocityresponse;
1650          }          }
1651          uint8_t releasevelocityresponse = _3ewa->ReadUint8();  
1652          if (releasevelocityresponse < 5) {          pData[98] = VelocityResponseCurveScaling;
1653              ReleaseVelocityResponseCurve = curve_type_nonlinear;  
1654              ReleaseVelocityResponseDepth = releasevelocityresponse;          pData[99] = AttenuationControllerThreshold;
1655          }  
1656          else if (releasevelocityresponse < 10) {          // next 4 bytes unknown
1657              ReleaseVelocityResponseCurve = curve_type_linear;  
1658              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;          store16(&pData[104], SampleStartOffset);
1659          }  
1660          else if (releasevelocityresponse < 15) {          // next 2 bytes unknown
1661              ReleaseVelocityResponseCurve = curve_type_special;  
1662              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;          {
1663                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1664                switch (DimensionBypass) {
1665                    case dim_bypass_ctrl_94:
1666                        pitchTrackDimensionBypass |= 0x10;
1667                        break;
1668                    case dim_bypass_ctrl_95:
1669                        pitchTrackDimensionBypass |= 0x20;
1670                        break;
1671                    case dim_bypass_ctrl_none:
1672                        //FIXME: should we set anything here?
1673                        break;
1674                    default:
1675                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1676                }
1677                pData[108] = pitchTrackDimensionBypass;
1678          }          }
1679          else {  
1680              ReleaseVelocityResponseCurve = curve_type_unknown;          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1681              ReleaseVelocityResponseDepth = 0;          pData[109] = pan;
1682    
1683            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1684            pData[110] = selfmask;
1685    
1686            // next byte unknown
1687    
1688            {
1689                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1690                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1691                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1692                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1693                pData[112] = lfo3ctrl;
1694            }
1695    
1696            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1697            pData[113] = attenctl;
1698    
1699            {
1700                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1701                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1702                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1703                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1704                pData[114] = lfo2ctrl;
1705            }
1706    
1707            {
1708                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1709                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1710                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1711                if (VCFResonanceController != vcf_res_ctrl_none)
1712                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1713                pData[115] = lfo1ctrl;
1714            }
1715    
1716            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1717                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1718            pData[116] = eg3depth;
1719    
1720            // next 2 bytes unknown
1721    
1722            const uint8_t channeloffset = ChannelOffset * 4;
1723            pData[120] = channeloffset;
1724    
1725            {
1726                uint8_t regoptions = 0;
1727                if (MSDecode)      regoptions |= 0x01; // bit 0
1728                if (SustainDefeat) regoptions |= 0x02; // bit 1
1729                pData[121] = regoptions;
1730          }          }
1731          VelocityResponseCurveScaling = _3ewa->ReadUint8();  
1732          AttenuationControllerThreshold = _3ewa->ReadInt8();          // next 2 bytes unknown
1733          _3ewa->ReadInt32(); // unknown  
1734          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();          pData[124] = VelocityUpperLimit;
1735          _3ewa->ReadInt16(); // unknown  
1736          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();          // next 3 bytes unknown
1737          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);  
1738          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;          pData[128] = ReleaseTriggerDecay;
1739          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;  
1740          else                                       DimensionBypass = dim_bypass_ctrl_none;          // next 2 bytes unknown
1741          uint8_t pan = _3ewa->ReadUint8();  
1742          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1743          SelfMask = _3ewa->ReadInt8() & 0x01;          pData[131] = eg1hold;
1744          _3ewa->ReadInt8(); // unknown  
1745          uint8_t lfo3ctrl = _3ewa->ReadUint8();          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1746          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1747          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5          pData[132] = vcfcutoff;
1748          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7  
1749          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));          pData[133] = VCFCutoffController;
1750          uint8_t lfo2ctrl       = _3ewa->ReadUint8();  
1751          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1752          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1753          LFO2Sync               = lfo2ctrl & 0x20; // bit 5          pData[134] = vcfvelscale;
1754          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6  
1755          uint8_t lfo1ctrl       = _3ewa->ReadUint8();          // next byte unknown
1756          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits  
1757          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1758          LFO1Sync               = lfo1ctrl & 0x40; // bit 6                                       (VCFResonance & 0x7f); /* lower 7 bits */
1759          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))          pData[136] = vcfresonance;
1760                                                      : vcf_res_ctrl_none;  
1761          uint16_t eg3depth = _3ewa->ReadUint16();          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1762          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1763                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */          pData[137] = vcfbreakpoint;
1764          _3ewa->ReadInt16(); // unknown  
1765          ChannelOffset = _3ewa->ReadUint8() / 4;          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1766          uint8_t regoptions = _3ewa->ReadUint8();                                      VCFVelocityCurve * 5;
1767          MSDecode           = regoptions & 0x01; // bit 0          pData[138] = vcfvelocity;
1768          SustainDefeat      = regoptions & 0x02; // bit 1  
1769          _3ewa->ReadInt16(); // unknown          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1770          VelocityUpperLimit = _3ewa->ReadInt8();          pData[139] = vcftype;
1771          _3ewa->ReadInt8(); // unknown  
1772          _3ewa->ReadInt16(); // unknown          if (chunksize >= 148) {
1773          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay              memcpy(&pData[140], DimensionUpperLimits, 8);
         _3ewa->ReadInt8(); // unknown  
         _3ewa->ReadInt8(); // unknown  
         EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7  
         uint8_t vcfcutoff = _3ewa->ReadUint8();  
         VCFEnabled = vcfcutoff & 0x80; // bit 7  
         VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits  
         VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());  
         VCFVelocityScale = _3ewa->ReadUint8();  
         _3ewa->ReadInt8(); // unknown  
         uint8_t vcfresonance = _3ewa->ReadUint8();  
         VCFResonance = vcfresonance & 0x7f; // lower 7 bits  
         VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7  
         uint8_t vcfbreakpoint         = _3ewa->ReadUint8();  
         VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7  
         VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits  
         uint8_t vcfvelocity = _3ewa->ReadUint8();  
         VCFVelocityDynamicRange = vcfvelocity % 5;  
         VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);  
         VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());  
         if (VCFType == vcf_type_lowpass) {  
             if (lfo3ctrl & 0x40) // bit 6  
                 VCFType = vcf_type_lowpassturbo;  
1774          }          }
1775        }
1776    
1777          // get the corresponding velocity->volume table from the table map or create & calculate that table if it doesn't exist yet      // get the corresponding velocity table from the table map or create & calculate that table if it doesn't exist yet
1778          uint32_t tableKey = (VelocityResponseCurve<<16) | (VelocityResponseDepth<<8) | VelocityResponseCurveScaling;      double* DimensionRegion::GetVelocityTable(curve_type_t curveType, uint8_t depth, uint8_t scaling)
1779        {
1780            double* table;
1781            uint32_t tableKey = (curveType<<16) | (depth<<8) | scaling;
1782          if (pVelocityTables->count(tableKey)) { // if key exists          if (pVelocityTables->count(tableKey)) { // if key exists
1783              pVelocityAttenuationTable = (*pVelocityTables)[tableKey];              table = (*pVelocityTables)[tableKey];
1784          }          }
1785          else {          else {
1786              pVelocityAttenuationTable =              table = CreateVelocityTable(curveType, depth, scaling);
1787                  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  
1788          }          }
1789            return table;
         SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));  
1790      }      }
1791    
1792      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {      leverage_ctrl_t DimensionRegion::DecodeLeverageController(_lev_ctrl_t EncodedController) {
# Line 1295  namespace { Line 1907  namespace {
1907          return decodedcontroller;          return decodedcontroller;
1908      }      }
1909    
1910        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1911            _lev_ctrl_t encodedcontroller;
1912            switch (DecodedController.type) {
1913                // special controller
1914                case leverage_ctrl_t::type_none:
1915                    encodedcontroller = _lev_ctrl_none;
1916                    break;
1917                case leverage_ctrl_t::type_velocity:
1918                    encodedcontroller = _lev_ctrl_velocity;
1919                    break;
1920                case leverage_ctrl_t::type_channelaftertouch:
1921                    encodedcontroller = _lev_ctrl_channelaftertouch;
1922                    break;
1923    
1924                // ordinary MIDI control change controller
1925                case leverage_ctrl_t::type_controlchange:
1926                    switch (DecodedController.controller_number) {
1927                        case 1:
1928                            encodedcontroller = _lev_ctrl_modwheel;
1929                            break;
1930                        case 2:
1931                            encodedcontroller = _lev_ctrl_breath;
1932                            break;
1933                        case 4:
1934                            encodedcontroller = _lev_ctrl_foot;
1935                            break;
1936                        case 12:
1937                            encodedcontroller = _lev_ctrl_effect1;
1938                            break;
1939                        case 13:
1940                            encodedcontroller = _lev_ctrl_effect2;
1941                            break;
1942                        case 16:
1943                            encodedcontroller = _lev_ctrl_genpurpose1;
1944                            break;
1945                        case 17:
1946                            encodedcontroller = _lev_ctrl_genpurpose2;
1947                            break;
1948                        case 18:
1949                            encodedcontroller = _lev_ctrl_genpurpose3;
1950                            break;
1951                        case 19:
1952                            encodedcontroller = _lev_ctrl_genpurpose4;
1953                            break;
1954                        case 5:
1955                            encodedcontroller = _lev_ctrl_portamentotime;
1956                            break;
1957                        case 64:
1958                            encodedcontroller = _lev_ctrl_sustainpedal;
1959                            break;
1960                        case 65:
1961                            encodedcontroller = _lev_ctrl_portamento;
1962                            break;
1963                        case 66:
1964                            encodedcontroller = _lev_ctrl_sostenutopedal;
1965                            break;
1966                        case 67:
1967                            encodedcontroller = _lev_ctrl_softpedal;
1968                            break;
1969                        case 80:
1970                            encodedcontroller = _lev_ctrl_genpurpose5;
1971                            break;
1972                        case 81:
1973                            encodedcontroller = _lev_ctrl_genpurpose6;
1974                            break;
1975                        case 82:
1976                            encodedcontroller = _lev_ctrl_genpurpose7;
1977                            break;
1978                        case 83:
1979                            encodedcontroller = _lev_ctrl_genpurpose8;
1980                            break;
1981                        case 91:
1982                            encodedcontroller = _lev_ctrl_effect1depth;
1983                            break;
1984                        case 92:
1985                            encodedcontroller = _lev_ctrl_effect2depth;
1986                            break;
1987                        case 93:
1988                            encodedcontroller = _lev_ctrl_effect3depth;
1989                            break;
1990                        case 94:
1991                            encodedcontroller = _lev_ctrl_effect4depth;
1992                            break;
1993                        case 95:
1994                            encodedcontroller = _lev_ctrl_effect5depth;
1995                            break;
1996                        default:
1997                            throw gig::Exception("leverage controller number is not supported by the gig format");
1998                    }
1999                    break;
2000                default:
2001                    throw gig::Exception("Unknown leverage controller type.");
2002            }
2003            return encodedcontroller;
2004        }
2005    
2006      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
2007          Instances--;          Instances--;
2008          if (!Instances) {          if (!Instances) {
# Line 1308  namespace { Line 2016  namespace {
2016              delete pVelocityTables;              delete pVelocityTables;
2017              pVelocityTables = NULL;              pVelocityTables = NULL;
2018          }          }
2019            if (VelocityTable) delete[] VelocityTable;
2020      }      }
2021    
2022      /**      /**
# Line 1325  namespace { Line 2034  namespace {
2034          return pVelocityAttenuationTable[MIDIKeyVelocity];          return pVelocityAttenuationTable[MIDIKeyVelocity];
2035      }      }
2036    
2037        double DimensionRegion::GetVelocityRelease(uint8_t MIDIKeyVelocity) {
2038            return pVelocityReleaseTable[MIDIKeyVelocity];
2039        }
2040    
2041        double DimensionRegion::GetVelocityCutoff(uint8_t MIDIKeyVelocity) {
2042            return pVelocityCutoffTable[MIDIKeyVelocity];
2043        }
2044    
2045      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) {
2046    
2047          // line-segment approximations of the 15 velocity curves          // line-segment approximations of the 15 velocity curves
# Line 1358  namespace { Line 2075  namespace {
2075          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,
2076                               127, 127 };                               127, 127 };
2077    
2078            // this is only used by the VCF velocity curve
2079            const int spe5[] = { 1, 2, 30, 5, 60, 19, 77, 70, 83, 85, 88, 106,
2080                                 91, 127, 127, 127 };
2081    
2082          const int* const curves[] = { non0, non1, non2, non3, non4,          const int* const curves[] = { non0, non1, non2, non3, non4,
2083                                        lin0, lin1, lin2, lin3, lin4,                                        lin0, lin1, lin2, lin3, lin4,
2084                                        spe0, spe1, spe2, spe3, spe4 };                                        spe0, spe1, spe2, spe3, spe4, spe5 };
2085    
2086          double* const table = new double[128];          double* const table = new double[128];
2087    
# Line 1412  namespace { Line 2133  namespace {
2133              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2134                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2135                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2136                    _3lnk->ReadUint8(); // probably the position of the dimension
2137                    _3lnk->ReadUint8(); // unknown
2138                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2139                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2140                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2141                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2142                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2143                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2144                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2145                  }                  }
2146                  else { // active dimension                  else { // active dimension
2147                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2148                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2149                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2150                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2151                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random) ? split_type_bit  
                                                                                           : split_type_normal;  
                     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2152                      Dimensions++;                      Dimensions++;
2153    
2154                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2155                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2156                  }                  }
2157                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2158              }              }
2159                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2160    
2161              // 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,
2162              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2163                  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;  
                             }  
                         }  
                     }  
                 }  
             }  
2164    
2165              // 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();  
2166              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2167                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2168              else              else
# Line 1482  namespace { Line 2171  namespace {
2171              // load sample references              // load sample references
2172              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2173                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2174                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2175                }
2176                GetSample(); // load global region sample reference
2177            } else {
2178                DimensionRegions = 0;
2179                for (int i = 0 ; i < 8 ; i++) {
2180                    pDimensionDefinitions[i].dimension  = dimension_none;
2181                    pDimensionDefinitions[i].bits       = 0;
2182                    pDimensionDefinitions[i].zones      = 0;
2183              }              }
2184          }          }
2185          else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2186            // make sure there is at least one dimension region
2187            if (!DimensionRegions) {
2188                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2189                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2190                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2191                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2192                DimensionRegions = 1;
2193            }
2194        }
2195    
2196        /**
2197         * Apply Region settings and all its DimensionRegions to the respective
2198         * RIFF chunks. You have to call File::Save() to make changes persistent.
2199         *
2200         * Usually there is absolutely no need to call this method explicitly.
2201         * It will be called automatically when File::Save() was called.
2202         *
2203         * @throws gig::Exception if samples cannot be dereferenced
2204         */
2205        void Region::UpdateChunks() {
2206            // in the gig format we don't care about the Region's sample reference
2207            // but we still have to provide some existing one to not corrupt the
2208            // file, so to avoid the latter we simply always assign the sample of
2209            // the first dimension region of this region
2210            pSample = pDimensionRegions[0]->pSample;
2211    
2212            // first update base class's chunks
2213            DLS::Region::UpdateChunks();
2214    
2215            // update dimension region's chunks
2216            for (int i = 0; i < DimensionRegions; i++) {
2217                pDimensionRegions[i]->UpdateChunks();
2218            }
2219    
2220            File* pFile = (File*) GetParent()->GetParent();
2221            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2222            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2223    
2224            // make sure '3lnk' chunk exists
2225            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2226            if (!_3lnk) {
2227                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2228                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2229                memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
2230    
2231                // move 3prg to last position
2232                pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);
2233            }
2234    
2235            // update dimension definitions in '3lnk' chunk
2236            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2237            store32(&pData[0], DimensionRegions);
2238            for (int i = 0; i < iMaxDimensions; i++) {
2239                pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2240                pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2241                // next 2 bytes unknown
2242                pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2243                // next 3 bytes unknown
2244            }
2245    
2246            // update wave pool table in '3lnk' chunk
2247            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2248            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2249                int iWaveIndex = -1;
2250                if (i < DimensionRegions) {
2251                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2252                    File::SampleList::iterator iter = pFile->pSamples->begin();
2253                    File::SampleList::iterator end  = pFile->pSamples->end();
2254                    for (int index = 0; iter != end; ++iter, ++index) {
2255                        if (*iter == pDimensionRegions[i]->pSample) {
2256                            iWaveIndex = index;
2257                            break;
2258                        }
2259                    }
2260                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2261                }
2262                store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2263            }
2264      }      }
2265    
2266      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1504  namespace { Line 2279  namespace {
2279          }          }
2280      }      }
2281    
2282      Region::~Region() {      void Region::UpdateVelocityTable() {
2283          for (uint i = 0; i < Dimensions; i++) {          // get velocity dimension's index
2284              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          int veldim = -1;
2285            for (int i = 0 ; i < Dimensions ; i++) {
2286                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2287                    veldim = i;
2288                    break;
2289                }
2290            }
2291            if (veldim == -1) return;
2292    
2293            int step = 1;
2294            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2295            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2296            int end = step * pDimensionDefinitions[veldim].zones;
2297    
2298            // loop through all dimension regions for all dimensions except the velocity dimension
2299            int dim[8] = { 0 };
2300            for (int i = 0 ; i < DimensionRegions ; i++) {
2301    
2302                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2303                    pDimensionRegions[i]->VelocityUpperLimit) {
2304                    // create the velocity table
2305                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2306                    if (!table) {
2307                        table = new uint8_t[128];
2308                        pDimensionRegions[i]->VelocityTable = table;
2309                    }
2310                    int tableidx = 0;
2311                    int velocityZone = 0;
2312                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2313                        for (int k = i ; k < end ; k += step) {
2314                            DimensionRegion *d = pDimensionRegions[k];
2315                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2316                            velocityZone++;
2317                        }
2318                    } else { // gig2
2319                        for (int k = i ; k < end ; k += step) {
2320                            DimensionRegion *d = pDimensionRegions[k];
2321                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2322                            velocityZone++;
2323                        }
2324                    }
2325                } else {
2326                    if (pDimensionRegions[i]->VelocityTable) {
2327                        delete[] pDimensionRegions[i]->VelocityTable;
2328                        pDimensionRegions[i]->VelocityTable = 0;
2329                    }
2330                }
2331    
2332                int j;
2333                int shift = 0;
2334                for (j = 0 ; j < Dimensions ; j++) {
2335                    if (j == veldim) i += skipveldim; // skip velocity dimension
2336                    else {
2337                        dim[j]++;
2338                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2339                        else {
2340                            // skip unused dimension regions
2341                            dim[j] = 0;
2342                            i += ((1 << pDimensionDefinitions[j].bits) -
2343                                  pDimensionDefinitions[j].zones) << shift;
2344                        }
2345                    }
2346                    shift += pDimensionDefinitions[j].bits;
2347                }
2348                if (j == Dimensions) break;
2349            }
2350        }
2351    
2352        /** @brief Einstein would have dreamed of it - create a new dimension.
2353         *
2354         * Creates a new dimension with the dimension definition given by
2355         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2356         * There is a hard limit of dimensions and total amount of "bits" all
2357         * dimensions can have. This limit is dependant to what gig file format
2358         * version this file refers to. The gig v2 (and lower) format has a
2359         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2360         * format has a limit of 8.
2361         *
2362         * @param pDimDef - defintion of the new dimension
2363         * @throws gig::Exception if dimension of the same type exists already
2364         * @throws gig::Exception if amount of dimensions or total amount of
2365         *                        dimension bits limit is violated
2366         */
2367        void Region::AddDimension(dimension_def_t* pDimDef) {
2368            // check if max. amount of dimensions reached
2369            File* file = (File*) GetParent()->GetParent();
2370            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2371            if (Dimensions >= iMaxDimensions)
2372                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2373            // check if max. amount of dimension bits reached
2374            int iCurrentBits = 0;
2375            for (int i = 0; i < Dimensions; i++)
2376                iCurrentBits += pDimensionDefinitions[i].bits;
2377            if (iCurrentBits >= iMaxDimensions)
2378                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2379            const int iNewBits = iCurrentBits + pDimDef->bits;
2380            if (iNewBits > iMaxDimensions)
2381                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2382            // check if there's already a dimensions of the same type
2383            for (int i = 0; i < Dimensions; i++)
2384                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2385                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2386    
2387            // assign definition of new dimension
2388            pDimensionDefinitions[Dimensions] = *pDimDef;
2389    
2390            // auto correct certain dimension definition fields (where possible)
2391            pDimensionDefinitions[Dimensions].split_type  =
2392                __resolveSplitType(pDimensionDefinitions[Dimensions].dimension);
2393            pDimensionDefinitions[Dimensions].zone_size =
2394                __resolveZoneSize(pDimensionDefinitions[Dimensions]);
2395    
2396            // create new dimension region(s) for this new dimension
2397            for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2398                //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2399                RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2400                pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2401                DimensionRegions++;
2402            }
2403    
2404            Dimensions++;
2405    
2406            // if this is a layer dimension, update 'Layers' attribute
2407            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2408    
2409            UpdateVelocityTable();
2410        }
2411    
2412        /** @brief Delete an existing dimension.
2413         *
2414         * Deletes the dimension given by \a pDimDef and deletes all respective
2415         * dimension regions, that is all dimension regions where the dimension's
2416         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2417         * for example this would delete all dimension regions for the case(s)
2418         * where the sustain pedal is pressed down.
2419         *
2420         * @param pDimDef - dimension to delete
2421         * @throws gig::Exception if given dimension cannot be found
2422         */
2423        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2424            // get dimension's index
2425            int iDimensionNr = -1;
2426            for (int i = 0; i < Dimensions; i++) {
2427                if (&pDimensionDefinitions[i] == pDimDef) {
2428                    iDimensionNr = i;
2429                    break;
2430                }
2431          }          }
2432            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2433    
2434            // get amount of bits below the dimension to delete
2435            int iLowerBits = 0;
2436            for (int i = 0; i < iDimensionNr; i++)
2437                iLowerBits += pDimensionDefinitions[i].bits;
2438    
2439            // get amount ot bits above the dimension to delete
2440            int iUpperBits = 0;
2441            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2442                iUpperBits += pDimensionDefinitions[i].bits;
2443    
2444            // delete dimension regions which belong to the given dimension
2445            // (that is where the dimension's bit > 0)
2446            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2447                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2448                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2449                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2450                                        iObsoleteBit << iLowerBits |
2451                                        iLowerBit;
2452                        delete pDimensionRegions[iToDelete];
2453                        pDimensionRegions[iToDelete] = NULL;
2454                        DimensionRegions--;
2455                    }
2456                }
2457            }
2458    
2459            // defrag pDimensionRegions array
2460            // (that is remove the NULL spaces within the pDimensionRegions array)
2461            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2462                if (!pDimensionRegions[iTo]) {
2463                    if (iFrom <= iTo) iFrom = iTo + 1;
2464                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2465                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2466                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2467                        pDimensionRegions[iFrom] = NULL;
2468                    }
2469                }
2470            }
2471    
2472            // 'remove' dimension definition
2473            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2474                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2475            }
2476            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2477            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2478            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2479    
2480            Dimensions--;
2481    
2482            // if this was a layer dimension, update 'Layers' attribute
2483            if (pDimDef->dimension == dimension_layer) Layers = 1;
2484        }
2485    
2486        Region::~Region() {
2487          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2488              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2489          }          }
# Line 1532  namespace { Line 2508  namespace {
2508       * @see             Dimensions       * @see             Dimensions
2509       */       */
2510      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2511          uint8_t bits[8] = { 0 };          uint8_t bits;
2512            int veldim = -1;
2513            int velbitpos;
2514            int bitpos = 0;
2515            int dimregidx = 0;
2516          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2517              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2518              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2519                  case split_type_normal:                  veldim = i;
2520                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
2521                      break;              } else {
2522                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2523                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2524                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2525                  case split_type_bit: // the value is already the sought dimension bit number                              // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2526                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2527                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                                  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2528                      break;                              }
2529              }                          } else {
2530                                // gig2: evenly sized zones
2531                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2532                            }
2533                            break;
2534                        case split_type_bit: // the value is already the sought dimension bit number
2535                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2536                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2537                            break;
2538                    }
2539                    dimregidx |= bits << bitpos;
2540                }
2541                bitpos += pDimensionDefinitions[i].bits;
2542            }
2543            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2544            if (veldim != -1) {
2545                // (dimreg is now the dimension region for the lowest velocity)
2546                if (dimreg->VelocityTable) // custom defined zone ranges
2547                    bits = dimreg->VelocityTable[DimValues[veldim]];
2548                else // normal split type
2549                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2550    
2551                dimregidx |= bits << velbitpos;
2552                dimreg = pDimensionRegions[dimregidx];
2553          }          }
2554          return GetDimensionRegionByBit(bits);          return dimreg;
2555      }      }
2556    
2557      /**      /**
# Line 1588  namespace { Line 2591  namespace {
2591      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2592          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2593          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2594            if (!file->pWavePoolTable) return NULL;
2595          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2596            unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2597          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
2598          while (sample) {          while (sample) {
2599              if (sample->ulWavePoolOffset == soughtoffset) return static_cast<gig::Sample*>(pSample = sample);              if (sample->ulWavePoolOffset == soughtoffset &&
2600                    sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2601              sample = file->GetNextSample();              sample = file->GetNextSample();
2602          }          }
2603          return NULL;          return NULL;
# Line 1603  namespace { Line 2609  namespace {
2609  // *  // *
2610    
2611      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) {
2612            static const DLS::Info::FixedStringLength fixedStringLengths[] = {
2613                { CHUNK_ID_INAM, 64 },
2614                { CHUNK_ID_ISFT, 12 },
2615                { 0, 0 }
2616            };
2617            pInfo->FixedStringLengths = fixedStringLengths;
2618    
2619          // Initialization          // Initialization
2620          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2621          RegionIndex = -1;          EffectSend = 0;
2622            Attenuation = 0;
2623            FineTune = 0;
2624            PitchbendRange = 0;
2625            PianoReleaseMode = false;
2626            DimensionKeyRange.low = 0;
2627            DimensionKeyRange.high = 0;
2628    
2629          // Loading          // Loading
2630          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1621  namespace { Line 2640  namespace {
2640                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2641                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2642              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2643          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2644    
2645            if (!pRegions) pRegions = new RegionList;
2646          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2647          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2648          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2649          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              while (rgn) {
2650          RIFF::List* rgn = lrgn->GetFirstSubList();                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2651          unsigned int iRegion = 0;                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2652          while (rgn) {                      pRegions->push_back(new Region(this, rgn));
2653              if (rgn->GetListType() == LIST_TYPE_RGN) {                  }
2654                  __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];  
2655              }              }
2656                // Creating Region Key Table for fast lookup
2657                UpdateRegionKeyTable();
2658          }          }
2659    
2660          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
2661      }      }
2662    
2663      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2664          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2665              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2666                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2667                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2668                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2669                    RegionKeyTable[iKey] = pRegion;
2670              }              }
2671          }          }
2672          if (pRegions) delete[] pRegions;      }
2673    
2674        Instrument::~Instrument() {
2675        }
2676    
2677        /**
2678         * Apply Instrument with all its Regions to the respective RIFF chunks.
2679         * You have to call File::Save() to make changes persistent.
2680         *
2681         * Usually there is absolutely no need to call this method explicitly.
2682         * It will be called automatically when File::Save() was called.
2683         *
2684         * @throws gig::Exception if samples cannot be dereferenced
2685         */
2686        void Instrument::UpdateChunks() {
2687            // first update base classes' chunks
2688            DLS::Instrument::UpdateChunks();
2689    
2690            // update Regions' chunks
2691            {
2692                RegionList::iterator iter = pRegions->begin();
2693                RegionList::iterator end  = pRegions->end();
2694                for (; iter != end; ++iter)
2695                    (*iter)->UpdateChunks();
2696            }
2697    
2698            // make sure 'lart' RIFF list chunk exists
2699            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2700            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2701            // make sure '3ewg' RIFF chunk exists
2702            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2703            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2704            // update '3ewg' RIFF chunk
2705            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2706            store16(&pData[0], EffectSend);
2707            store32(&pData[2], Attenuation);
2708            store16(&pData[6], FineTune);
2709            store16(&pData[8], PitchbendRange);
2710            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2711                                        DimensionKeyRange.low << 1;
2712            pData[10] = dimkeystart;
2713            pData[11] = DimensionKeyRange.high;
2714      }      }
2715    
2716      /**      /**
# Line 1667  namespace { Line 2721  namespace {
2721       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2722       */       */
2723      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2724          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2725          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2726    
2727          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2728              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2729                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1684  namespace { Line 2739  namespace {
2739       * @see      GetNextRegion()       * @see      GetNextRegion()
2740       */       */
2741      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2742          if (!Regions) return NULL;          if (!pRegions) return NULL;
2743          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2744          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2745      }      }
2746    
2747      /**      /**
# Line 1698  namespace { Line 2753  namespace {
2753       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2754       */       */
2755      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2756          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2757          return pRegions[RegionIndex++];          RegionsIterator++;
2758            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2759        }
2760    
2761        Region* Instrument::AddRegion() {
2762            // create new Region object (and its RIFF chunks)
2763            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2764            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2765            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2766            Region* pNewRegion = new Region(this, rgn);
2767            pRegions->push_back(pNewRegion);
2768            Regions = pRegions->size();
2769            // update Region key table for fast lookup
2770            UpdateRegionKeyTable();
2771            // done
2772            return pNewRegion;
2773        }
2774    
2775        void Instrument::DeleteRegion(Region* pRegion) {
2776            if (!pRegions) return;
2777            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2778            // update Region key table for fast lookup
2779            UpdateRegionKeyTable();
2780        }
2781    
2782    
2783    
2784    // *************** Group ***************
2785    // *
2786    
2787        /** @brief Constructor.
2788         *
2789         * @param file   - pointer to the gig::File object
2790         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
2791         *                 NULL if this is a new Group
2792         */
2793        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
2794            pFile      = file;
2795            pNameChunk = ck3gnm;
2796            ::LoadString(pNameChunk, Name);
2797        }
2798    
2799        Group::~Group() {
2800            // remove the chunk associated with this group (if any)
2801            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
2802        }
2803    
2804        /** @brief Update chunks with current group settings.
2805         *
2806         * Apply current Group field values to the respective chunks. You have
2807         * to call File::Save() to make changes persistent.
2808         *
2809         * Usually there is absolutely no need to call this method explicitly.
2810         * It will be called automatically when File::Save() was called.
2811         */
2812        void Group::UpdateChunks() {
2813            // make sure <3gri> and <3gnl> list chunks exist
2814            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
2815            if (!_3gri) {
2816                _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
2817                pFile->pRIFF->MoveSubChunk(_3gri, pFile->pRIFF->GetSubChunk(CHUNK_ID_PTBL));
2818            }
2819            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
2820            if (!_3gnl) _3gnl = _3gri->AddSubList(LIST_TYPE_3GNL);
2821            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
2822            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
2823        }
2824    
2825        /**
2826         * Returns the first Sample of this Group. You have to call this method
2827         * once before you use GetNextSample().
2828         *
2829         * <b>Notice:</b> this method might block for a long time, in case the
2830         * samples of this .gig file were not scanned yet
2831         *
2832         * @returns  pointer address to first Sample or NULL if there is none
2833         *           applied to this Group
2834         * @see      GetNextSample()
2835         */
2836        Sample* Group::GetFirstSample() {
2837            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2838            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
2839                if (pSample->GetGroup() == this) return pSample;
2840            }
2841            return NULL;
2842        }
2843    
2844        /**
2845         * Returns the next Sample of the Group. You have to call
2846         * GetFirstSample() once before you can use this method. By calling this
2847         * method multiple times it iterates through the Samples assigned to
2848         * this Group.
2849         *
2850         * @returns  pointer address to the next Sample of this Group or NULL if
2851         *           end reached
2852         * @see      GetFirstSample()
2853         */
2854        Sample* Group::GetNextSample() {
2855            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2856            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
2857                if (pSample->GetGroup() == this) return pSample;
2858            }
2859            return NULL;
2860        }
2861    
2862        /**
2863         * Move Sample given by \a pSample from another Group to this Group.
2864         */
2865        void Group::AddSample(Sample* pSample) {
2866            pSample->pGroup = this;
2867        }
2868    
2869        /**
2870         * Move all members of this group to another group (preferably the 1st
2871         * one except this). This method is called explicitly by
2872         * File::DeleteGroup() thus when a Group was deleted. This code was
2873         * intentionally not placed in the destructor!
2874         */
2875        void Group::MoveAll() {
2876            // get "that" other group first
2877            Group* pOtherGroup = NULL;
2878            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
2879                if (pOtherGroup != this) break;
2880            }
2881            if (!pOtherGroup) throw Exception(
2882                "Could not move samples to another group, since there is no "
2883                "other Group. This is a bug, report it!"
2884            );
2885            // now move all samples of this group to the other group
2886            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
2887                pOtherGroup->AddSample(pSample);
2888            }
2889      }      }
2890    
2891    
# Line 1707  namespace { Line 2893  namespace {
2893  // *************** File ***************  // *************** File ***************
2894  // *  // *
2895    
2896        const DLS::Info::FixedStringLength File::FixedStringLengths[] = {
2897            { CHUNK_ID_IARL, 256 },
2898            { CHUNK_ID_IART, 128 },
2899            { CHUNK_ID_ICMS, 128 },
2900            { CHUNK_ID_ICMT, 1024 },
2901            { CHUNK_ID_ICOP, 128 },
2902            { CHUNK_ID_ICRD, 128 },
2903            { CHUNK_ID_IENG, 128 },
2904            { CHUNK_ID_IGNR, 128 },
2905            { CHUNK_ID_IKEY, 128 },
2906            { CHUNK_ID_IMED, 128 },
2907            { CHUNK_ID_INAM, 128 },
2908            { CHUNK_ID_IPRD, 128 },
2909            { CHUNK_ID_ISBJ, 128 },
2910            { CHUNK_ID_ISFT, 128 },
2911            { CHUNK_ID_ISRC, 128 },
2912            { CHUNK_ID_ISRF, 128 },
2913            { CHUNK_ID_ITCH, 128 },
2914            { 0, 0 }
2915        };
2916    
2917        File::File() : DLS::File() {
2918            pGroups = NULL;
2919            pInfo->FixedStringLengths = FixedStringLengths;
2920            pInfo->ArchivalLocation = String(256, ' ');
2921    
2922            // add some mandatory chunks to get the file chunks in right
2923            // order (INFO chunk will be moved to first position later)
2924            pRIFF->AddSubChunk(CHUNK_ID_VERS, 8);
2925            pRIFF->AddSubChunk(CHUNK_ID_COLH, 4);
2926        }
2927    
2928      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2929          pSamples     = NULL;          pGroups = NULL;
2930          pInstruments = NULL;          pInfo->FixedStringLengths = FixedStringLengths;
2931      }      }
2932    
2933      File::~File() {      File::~File() {
2934          // free samples          if (pGroups) {
2935          if (pSamples) {              std::list<Group*>::iterator iter = pGroups->begin();
2936              SamplesIterator = pSamples->begin();              std::list<Group*>::iterator end  = pGroups->end();
2937              while (SamplesIterator != pSamples->end() ) {              while (iter != end) {
2938                  delete (*SamplesIterator);                  delete *iter;
2939                  SamplesIterator++;                  ++iter;
             }  
             pSamples->clear();  
             delete pSamples;  
   
         }  
         // free instruments  
         if (pInstruments) {  
             InstrumentsIterator = pInstruments->begin();  
             while (InstrumentsIterator != pInstruments->end() ) {  
                 delete (*InstrumentsIterator);  
                 InstrumentsIterator++;  
2940              }              }
2941              pInstruments->clear();              delete pGroups;
             delete pInstruments;  
2942          }          }
2943      }      }
2944    
# Line 1749  namespace { Line 2955  namespace {
2955          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2956      }      }
2957    
2958        /** @brief Add a new sample.
2959         *
2960         * This will create a new Sample object for the gig file. You have to
2961         * call Save() to make this persistent to the file.
2962         *
2963         * @returns pointer to new Sample object
2964         */
2965        Sample* File::AddSample() {
2966           if (!pSamples) LoadSamples();
2967           __ensureMandatoryChunksExist();
2968           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2969           // create new Sample object and its respective 'wave' list chunk
2970           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2971           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2972    
2973           // add mandatory chunks to get the chunks in right order
2974           wave->AddSubChunk(CHUNK_ID_FMT, 16);
2975           wave->AddSubList(LIST_TYPE_INFO);
2976    
2977           pSamples->push_back(pSample);
2978           return pSample;
2979        }
2980    
2981        /** @brief Delete a sample.
2982         *
2983         * This will delete the given Sample object from the gig file. You have
2984         * to call Save() to make this persistent to the file.
2985         *
2986         * @param pSample - sample to delete
2987         * @throws gig::Exception if given sample could not be found
2988         */
2989        void File::DeleteSample(Sample* pSample) {
2990            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2991            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2992            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2993            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
2994            pSamples->erase(iter);
2995            delete pSample;
2996        }
2997    
2998        void File::LoadSamples() {
2999            LoadSamples(NULL);
3000        }
3001    
3002      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
3003          RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);          // Groups must be loaded before samples, because samples will try
3004          if (wvpl) {          // to resolve the group they belong to
3005              // just for progress calculation          if (!pGroups) LoadGroups();
3006              int iSampleIndex  = 0;  
3007              int iTotalSamples = wvpl->CountSubLists(LIST_TYPE_WAVE);          if (!pSamples) pSamples = new SampleList;
3008    
3009              unsigned long wvplFileOffset = wvpl->GetFilePos();          RIFF::File* file = pRIFF;
3010              RIFF::List* wave = wvpl->GetFirstSubList();  
3011              while (wave) {          // just for progress calculation
3012                  if (wave->GetListType() == LIST_TYPE_WAVE) {          int iSampleIndex  = 0;
3013                      // notify current progress          int iTotalSamples = WavePoolCount;
3014                      const float subprogress = (float) iSampleIndex / (float) iTotalSamples;  
3015                      __notify_progress(pProgress, subprogress);          // check if samples should be loaded from extension files
3016            int lastFileNo = 0;
3017            for (int i = 0 ; i < WavePoolCount ; i++) {
3018                if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
3019            }
3020            String name(pRIFF->GetFileName());
3021            int nameLen = name.length();
3022            char suffix[6];
3023            if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
3024    
3025            for (int fileNo = 0 ; ; ) {
3026                RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
3027                if (wvpl) {
3028                    unsigned long wvplFileOffset = wvpl->GetFilePos();
3029                    RIFF::List* wave = wvpl->GetFirstSubList();
3030                    while (wave) {
3031                        if (wave->GetListType() == LIST_TYPE_WAVE) {
3032                            // notify current progress
3033                            const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
3034                            __notify_progress(pProgress, subprogress);
3035    
3036                      if (!pSamples) pSamples = new SampleList;                          unsigned long waveFileOffset = wave->GetFilePos();
3037                      unsigned long waveFileOffset = wave->GetFilePos();                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
                     pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset));  
3038    
3039                      iSampleIndex++;                          iSampleIndex++;
3040                        }
3041                        wave = wvpl->GetNextSubList();
3042                  }                  }
3043                  wave = wvpl->GetNextSubList();  
3044              }                  if (fileNo == lastFileNo) break;
3045              __notify_progress(pProgress, 1.0); // notify done  
3046                    // open extension file (*.gx01, *.gx02, ...)
3047                    fileNo++;
3048                    sprintf(suffix, ".gx%02d", fileNo);
3049                    name.replace(nameLen, 5, suffix);
3050                    file = new RIFF::File(name);
3051                    ExtensionFiles.push_back(file);
3052                } else break;
3053          }          }
3054          else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
3055            __notify_progress(pProgress, 1.0); // notify done
3056      }      }
3057    
3058      Instrument* File::GetFirstInstrument() {      Instrument* File::GetFirstInstrument() {
3059          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
3060          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3061          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3062          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3063      }      }
3064    
3065      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
3066          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3067          InstrumentsIterator++;          InstrumentsIterator++;
3068          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3069      }      }
3070    
3071      /**      /**
# Line 1820  namespace { Line 3098  namespace {
3098          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3099          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3100          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
3101              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
3102              InstrumentsIterator++;              InstrumentsIterator++;
3103          }          }
3104          return NULL;          return NULL;
3105      }      }
3106    
3107        /** @brief Add a new instrument definition.
3108         *
3109         * This will create a new Instrument object for the gig file. You have
3110         * to call Save() to make this persistent to the file.
3111         *
3112         * @returns pointer to new Instrument object
3113         */
3114        Instrument* File::AddInstrument() {
3115           if (!pInstruments) LoadInstruments();
3116           __ensureMandatoryChunksExist();
3117           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3118           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
3119    
3120           // add mandatory chunks to get the chunks in right order
3121           lstInstr->AddSubList(LIST_TYPE_INFO);
3122    
3123           Instrument* pInstrument = new Instrument(this, lstInstr);
3124    
3125           lstInstr->AddSubChunk(CHUNK_ID_INSH, 12);
3126    
3127           // this string is needed for the gig to be loadable in GSt:
3128           pInstrument->pInfo->Software = "Endless Wave";
3129    
3130           pInstruments->push_back(pInstrument);
3131           return pInstrument;
3132        }
3133    
3134        /** @brief Delete an instrument.
3135         *
3136         * This will delete the given Instrument object from the gig file. You
3137         * have to call Save() to make this persistent to the file.
3138         *
3139         * @param pInstrument - instrument to delete
3140         * @throws gig::Exception if given instrument could not be found
3141         */
3142        void File::DeleteInstrument(Instrument* pInstrument) {
3143            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
3144            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
3145            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
3146            pInstruments->erase(iter);
3147            delete pInstrument;
3148        }
3149    
3150        void File::LoadInstruments() {
3151            LoadInstruments(NULL);
3152        }
3153    
3154      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
3155            if (!pInstruments) pInstruments = new InstrumentList;
3156          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3157          if (lstInstruments) {          if (lstInstruments) {
3158              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 1841  namespace { Line 3167  namespace {
3167                      progress_t subprogress;                      progress_t subprogress;
3168                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
3169    
                     if (!pInstruments) pInstruments = new InstrumentList;  
3170                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
3171    
3172                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 1850  namespace { Line 3175  namespace {
3175              }              }
3176              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
3177          }          }
3178          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
3179    
3180        Group* File::GetFirstGroup() {
3181            if (!pGroups) LoadGroups();
3182            // there must always be at least one group
3183            GroupsIterator = pGroups->begin();
3184            return *GroupsIterator;
3185        }
3186    
3187        Group* File::GetNextGroup() {
3188            if (!pGroups) return NULL;
3189            ++GroupsIterator;
3190            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
3191        }
3192    
3193        /**
3194         * Returns the group with the given index.
3195         *
3196         * @param index - number of the sought group (0..n)
3197         * @returns sought group or NULL if there's no such group
3198         */
3199        Group* File::GetGroup(uint index) {
3200            if (!pGroups) LoadGroups();
3201            GroupsIterator = pGroups->begin();
3202            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
3203                if (i == index) return *GroupsIterator;
3204                ++GroupsIterator;
3205            }
3206            return NULL;
3207        }
3208    
3209        Group* File::AddGroup() {
3210            if (!pGroups) LoadGroups();
3211            // there must always be at least one group
3212            __ensureMandatoryChunksExist();
3213            Group* pGroup = new Group(this, NULL);
3214            pGroups->push_back(pGroup);
3215            return pGroup;
3216        }
3217    
3218        /** @brief Delete a group and its samples.
3219         *
3220         * This will delete the given Group object and all the samples that
3221         * belong to this group from the gig file. You have to call Save() to
3222         * make this persistent to the file.
3223         *
3224         * @param pGroup - group to delete
3225         * @throws gig::Exception if given group could not be found
3226         */
3227        void File::DeleteGroup(Group* pGroup) {
3228            if (!pGroups) LoadGroups();
3229            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3230            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3231            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3232            // delete all members of this group
3233            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
3234                DeleteSample(pSample);
3235            }
3236            // now delete this group object
3237            pGroups->erase(iter);
3238            delete pGroup;
3239        }
3240    
3241        /** @brief Delete a group.
3242         *
3243         * This will delete the given Group object from the gig file. All the
3244         * samples that belong to this group will not be deleted, but instead
3245         * be moved to another group. You have to call Save() to make this
3246         * persistent to the file.
3247         *
3248         * @param pGroup - group to delete
3249         * @throws gig::Exception if given group could not be found
3250         */
3251        void File::DeleteGroupOnly(Group* pGroup) {
3252            if (!pGroups) LoadGroups();
3253            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3254            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3255            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3256            // move all members of this group to another group
3257            pGroup->MoveAll();
3258            pGroups->erase(iter);
3259            delete pGroup;
3260        }
3261    
3262        void File::LoadGroups() {
3263            if (!pGroups) pGroups = new std::list<Group*>;
3264            // try to read defined groups from file
3265            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
3266            if (lst3gri) {
3267                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
3268                if (lst3gnl) {
3269                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3270                    while (ck) {
3271                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3272                            pGroups->push_back(new Group(this, ck));
3273                        }
3274                        ck = lst3gnl->GetNextSubChunk();
3275                    }
3276                }
3277            }
3278            // if there were no group(s), create at least the mandatory default group
3279            if (!pGroups->size()) {
3280                Group* pGroup = new Group(this, NULL);
3281                pGroup->Name = "Default Group";
3282                pGroups->push_back(pGroup);
3283            }
3284        }
3285    
3286        /**
3287         * Apply all the gig file's current instruments, samples, groups and settings
3288         * to the respective RIFF chunks. You have to call Save() to make changes
3289         * persistent.
3290         *
3291         * Usually there is absolutely no need to call this method explicitly.
3292         * It will be called automatically when File::Save() was called.
3293         *
3294         * @throws Exception - on errors
3295         */
3296        void File::UpdateChunks() {
3297            RIFF::Chunk* info = pRIFF->GetSubList(LIST_TYPE_INFO);
3298    
3299            // first update base class's chunks
3300            DLS::File::UpdateChunks();
3301    
3302            if (!info) {
3303                // INFO was added by Resource::UpdateChunks - make sure it
3304                // is placed first in file
3305                info = pRIFF->GetSubList(LIST_TYPE_INFO);
3306                RIFF::Chunk* first = pRIFF->GetFirstSubChunk();
3307                if (first != info) {
3308                    pRIFF->MoveSubChunk(info, first);
3309                }
3310            }
3311    
3312            // update group's chunks
3313            if (pGroups) {
3314                std::list<Group*>::iterator iter = pGroups->begin();
3315                std::list<Group*>::iterator end  = pGroups->end();
3316                for (; iter != end; ++iter) {
3317                    (*iter)->UpdateChunks();
3318                }
3319            }
3320      }      }
3321    
3322    
# Line 1865  namespace { Line 3331  namespace {
3331          std::cout << "gig::Exception: " << Message << std::endl;          std::cout << "gig::Exception: " << Message << std::endl;
3332      }      }
3333    
3334    
3335    // *************** functions ***************
3336    // *
3337    
3338        /**
3339         * Returns the name of this C++ library. This is usually "libgig" of
3340         * course. This call is equivalent to RIFF::libraryName() and
3341         * DLS::libraryName().
3342         */
3343        String libraryName() {
3344            return PACKAGE;
3345        }
3346    
3347        /**
3348         * Returns version of this C++ library. This call is equivalent to
3349         * RIFF::libraryVersion() and DLS::libraryVersion().
3350         */
3351        String libraryVersion() {
3352            return VERSION;
3353        }
3354    
3355  } // namespace gig  } // namespace gig

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

  ViewVC Help
Powered by ViewVC