/[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 728 by persson, Tue Jul 26 11:13:53 2005 UTC revision 902 by persson, Sat Jul 22 14:22:01 2006 UTC
# Line 23  Line 23 
23    
24  #include "gig.h"  #include "gig.h"
25    
26    #include "helper.h"
27    
28    #include <math.h>
29  #include <iostream>  #include <iostream>
30    
31    /// Initial size of the sample buffer which is used for decompression of
32    /// compressed sample wave streams - this value should always be bigger than
33    /// the biggest sample piece expected to be read by the sampler engine,
34    /// otherwise the buffer size will be raised at runtime and thus the buffer
35    /// reallocated which is time consuming and unefficient.
36    #define INITIAL_SAMPLE_BUFFER_SIZE              512000 // 512 kB
37    
38    /** (so far) every exponential paramater in the gig format has a basis of 1.000000008813822 */
39    #define GIG_EXP_DECODE(x)                       (pow(1.000000008813822, x))
40    #define GIG_EXP_ENCODE(x)                       (log(x) / log(1.000000008813822))
41    #define GIG_PITCH_TRACK_EXTRACT(x)              (!(x & 0x01))
42    #define GIG_PITCH_TRACK_ENCODE(x)               ((x) ? 0x00 : 0x01)
43    #define GIG_VCF_RESONANCE_CTRL_EXTRACT(x)       ((x >> 4) & 0x03)
44    #define GIG_VCF_RESONANCE_CTRL_ENCODE(x)        ((x & 0x03) << 4)
45    #define GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(x)  ((x >> 1) & 0x03)
46    #define GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(x)   ((x >> 3) & 0x03)
47    #define GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(x) ((x >> 5) & 0x03)
48    #define GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(x)   ((x & 0x03) << 1)
49    #define GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(x)    ((x & 0x03) << 3)
50    #define GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(x)  ((x & 0x03) << 5)
51    
52  namespace gig {  namespace gig {
53    
54  // *************** 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      {      {
         // Note: The 24 bits are truncated to 16 bits for now.  
   
164          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
         const int shift = 8 - truncatedBits;  
165    
166  #define GET_PARAMS(params)                      \  #define GET_PARAMS(params)                      \
167          y    = get24(params);                   \          y    = get24(params);                   \
# Line 149  namespace { Line 177  namespace {
177    
178  #define COPY_ONE(x)                             \  #define COPY_ONE(x)                             \
179          SKIP_ONE(x);                            \          SKIP_ONE(x);                            \
180          *pDst = y >> shift;                     \          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 232  namespace { Line 260  namespace {
260      unsigned int Sample::Instances = 0;      unsigned int Sample::Instances = 0;
261      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
262    
263        /** @brief Constructor.
264         *
265         * Load an existing sample or create a new one. A 'wave' list chunk must
266         * be given to this constructor. In case the given 'wave' list chunk
267         * contains a 'fmt', 'data' (and optionally a '3gix', 'smpl') chunk, the
268         * format and sample data will be loaded from there, otherwise default
269         * values will be used and those chunks will be created when
270         * File::Save() will be called later on.
271         *
272         * @param pFile          - pointer to gig::File where this sample is
273         *                         located (or will be located)
274         * @param waveList       - pointer to 'wave' list chunk which is (or
275         *                         will be) associated with this sample
276         * @param WavePoolOffset - offset of this sample data from wave pool
277         *                         ('wvpl') list chunk
278         * @param fileNo         - number of an extension file where this sample
279         *                         is located, 0 otherwise
280         */
281      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
282          Instances++;          Instances++;
283          FileNo = fileNo;          FileNo = fileNo;
284    
285          RIFF::Chunk* _3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
286          if (!_3gix) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");          if (pCk3gix) {
287          SampleGroup = _3gix->ReadInt16();              SampleGroup = pCk3gix->ReadInt16();
288            } else { // '3gix' chunk missing
289          RIFF::Chunk* smpl = waveList->GetSubChunk(CHUNK_ID_SMPL);              // use default value(s)
290          if (!smpl) throw gig::Exception("Mandatory chunks in <wave> list chunk not found.");              SampleGroup = 0;
291          Manufacturer      = smpl->ReadInt32();          }
292          Product           = smpl->ReadInt32();  
293          SamplePeriod      = smpl->ReadInt32();          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
294          MIDIUnityNote     = smpl->ReadInt32();          if (pCkSmpl) {
295          FineTune          = smpl->ReadInt32();              Manufacturer  = pCkSmpl->ReadInt32();
296          smpl->Read(&SMPTEFormat, 1, 4);              Product       = pCkSmpl->ReadInt32();
297          SMPTEOffset       = smpl->ReadInt32();              SamplePeriod  = pCkSmpl->ReadInt32();
298          Loops             = smpl->ReadInt32();              MIDIUnityNote = pCkSmpl->ReadInt32();
299          smpl->ReadInt32(); // manufByt              FineTune      = pCkSmpl->ReadInt32();
300          LoopID            = smpl->ReadInt32();              pCkSmpl->Read(&SMPTEFormat, 1, 4);
301          smpl->Read(&LoopType, 1, 4);              SMPTEOffset   = pCkSmpl->ReadInt32();
302          LoopStart         = smpl->ReadInt32();              Loops         = pCkSmpl->ReadInt32();
303          LoopEnd           = smpl->ReadInt32();              pCkSmpl->ReadInt32(); // manufByt
304          LoopFraction      = smpl->ReadInt32();              LoopID        = pCkSmpl->ReadInt32();
305          LoopPlayCount     = smpl->ReadInt32();              pCkSmpl->Read(&LoopType, 1, 4);
306                LoopStart     = pCkSmpl->ReadInt32();
307                LoopEnd       = pCkSmpl->ReadInt32();
308                LoopFraction  = pCkSmpl->ReadInt32();
309                LoopPlayCount = pCkSmpl->ReadInt32();
310            } else { // 'smpl' chunk missing
311                // use default values
312                Manufacturer  = 0;
313                Product       = 0;
314                SamplePeriod  = 1 / SamplesPerSecond;
315                MIDIUnityNote = 64;
316                FineTune      = 0;
317                SMPTEOffset   = 0;
318                Loops         = 0;
319                LoopID        = 0;
320                LoopStart     = 0;
321                LoopEnd       = 0;
322                LoopFraction  = 0;
323                LoopPlayCount = 0;
324            }
325    
326          FrameTable                 = NULL;          FrameTable                 = NULL;
327          SamplePos                  = 0;          SamplePos                  = 0;
# Line 287  namespace { Line 352  namespace {
352          }          }
353          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
354    
355          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
356        }
357    
358        /**
359         * Apply sample and its settings to the respective RIFF chunks. You have
360         * to call File::Save() to make changes persistent.
361         *
362         * Usually there is absolutely no need to call this method explicitly.
363         * It will be called automatically when File::Save() was called.
364         *
365         * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data
366         *                        was provided yet
367         * @throws gig::Exception if there is any invalid sample setting
368         */
369        void Sample::UpdateChunks() {
370            // first update base class's chunks
371            DLS::Sample::UpdateChunks();
372    
373            // make sure 'smpl' chunk exists
374            pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
375            if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
376            // update 'smpl' chunk
377            uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
378            SamplePeriod = 1 / SamplesPerSecond;
379            memcpy(&pData[0], &Manufacturer, 4);
380            memcpy(&pData[4], &Product, 4);
381            memcpy(&pData[8], &SamplePeriod, 4);
382            memcpy(&pData[12], &MIDIUnityNote, 4);
383            memcpy(&pData[16], &FineTune, 4);
384            memcpy(&pData[20], &SMPTEFormat, 4);
385            memcpy(&pData[24], &SMPTEOffset, 4);
386            memcpy(&pData[28], &Loops, 4);
387    
388            // we skip 'manufByt' for now (4 bytes)
389    
390            memcpy(&pData[36], &LoopID, 4);
391            memcpy(&pData[40], &LoopType, 4);
392            memcpy(&pData[44], &LoopStart, 4);
393            memcpy(&pData[48], &LoopEnd, 4);
394            memcpy(&pData[52], &LoopFraction, 4);
395            memcpy(&pData[56], &LoopPlayCount, 4);
396    
397            // make sure '3gix' chunk exists
398            pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
399            if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
400            // update '3gix' chunk
401            pData = (uint8_t*) pCk3gix->LoadChunkData();
402            memcpy(&pData[0], &SampleGroup, 2);
403      }      }
404    
405      /// 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 490  namespace { Line 602  namespace {
602          RAMCache.Size   = 0;          RAMCache.Size   = 0;
603      }      }
604    
605        /** @brief Resize sample.
606         *
607         * Resizes the sample's wave form data, that is the actual size of
608         * sample wave data possible to be written for this sample. This call
609         * will return immediately and just schedule the resize operation. You
610         * should call File::Save() to actually perform the resize operation(s)
611         * "physically" to the file. As this can take a while on large files, it
612         * is recommended to call Resize() first on all samples which have to be
613         * resized and finally to call File::Save() to perform all those resize
614         * operations in one rush.
615         *
616         * The actual size (in bytes) is dependant to the current FrameSize
617         * value. You may want to set FrameSize before calling Resize().
618         *
619         * <b>Caution:</b> You cannot directly write (i.e. with Write()) to
620         * enlarged samples before calling File::Save() as this might exceed the
621         * current sample's boundary!
622         *
623         * Also note: only WAVE_FORMAT_PCM is currently supported, that is
624         * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with
625         * other formats will fail!
626         *
627         * @param iNewSize - new sample wave data size in sample points (must be
628         *                   greater than zero)
629         * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM
630         *                         or if \a iNewSize is less than 1
631         * @throws gig::Exception if existing sample is compressed
632         * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
633         *      DLS::Sample::FormatTag, File::Save()
634         */
635        void Sample::Resize(int iNewSize) {
636            if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
637            DLS::Sample::Resize(iNewSize);
638        }
639    
640      /**      /**
641       * Sets the position within the sample (in sample points, not in       * Sets the position within the sample (in sample points, not in
642       * 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 579  namespace { Line 726  namespace {
726       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
727       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
728       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
729         * @param pDimRgn          dimension region with looping information
730       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
731       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
732       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
733       */       */
734      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,
735                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
736          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
737          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
738    
739          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
740    
741          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
742    
743              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
744                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
745    
746                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
747                      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  
748    
749                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
750                              // determine the end position within the loop first,                          do {
751                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
752                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
753                              // backward playback  
754                                if (!pPlaybackState->reverse) { // forward playback
755                              unsigned long swapareastart       = totalreadsamples;                                  do {
756                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
757                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
758                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
759                                        totalreadsamples += readsamples;
760                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
761                                            pPlaybackState->reverse = true;
762                              // read samples for backward playback                                          break;
763                              do {                                      }
764                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
765                                  samplestoreadinloop -= readsamples;                              }
766                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
767    
768                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
769                                    // determine the end position within the loop first,
770                                    // read forward from that 'end' and finally after
771                                    // reading, swap all sample frames so it reflects
772                                    // backward playback
773    
774                                    unsigned long swapareastart       = totalreadsamples;
775                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
776                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
777                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
778    
779                                    SetPos(reverseplaybackend);
780    
781                                    // read samples for backward playback
782                                    do {
783                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
784                                        samplestoreadinloop -= readsamples;
785                                        samplestoread       -= readsamples;
786                                        totalreadsamples    += readsamples;
787                                    } while (samplestoreadinloop && readsamples);
788    
789                                    SetPos(reverseplaybackend); // pretend we really read backwards
790    
791                                    if (reverseplaybackend == loop.LoopStart) {
792                                        pPlaybackState->loop_cycles_left--;
793                                        pPlaybackState->reverse = false;
794                                    }
795    
796                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
797                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
798                              }                              }
799                            } while (samplestoread && readsamples);
800                            break;
801                        }
802    
803                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
804                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
805                          }                          if (!pPlaybackState->reverse) do {
806                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
807                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
808                  }                              samplestoread    -= readsamples;
809                                totalreadsamples += readsamples;
810                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
811                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
812                      if (!pPlaybackState->reverse) do {                                  break;
813                          samplestoloopend  = this->LoopEnd - GetPos();                              }
814                          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);  
815    
816                      if (!samplestoread) break;                          if (!samplestoread) break;
817    
818                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
819                      // determine the end position within the loop first,                          // determine the end position within the loop first,
820                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
821                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
822                      // backward playback                          // backward playback
823    
824                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
825                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
826                      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)
827                                                                                : samplestoread;                                                                                    : samplestoread;
828                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
829    
830                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
831    
832                      // read samples for backward playback                          // read samples for backward playback
833                      do {                          do {
834                          // 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
835                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
836                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
837                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
838                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
839                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
840                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
841                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
842                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
843                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
844                          }                              }
845                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
846    
847                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
848    
849                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
850                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
851                      break;                          break;
852                  }                      }
853    
854                  default: case loop_type_normal: {                      default: case loop_type_normal: {
855                      do {                          do {
856                          // 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
857                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
858                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
859                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
860                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
861                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
862                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
863                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
864                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
865                          }                              }
866                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
867                      break;                          break;
868                        }
869                  }                  }
870              }              }
871          }          }
# Line 741  namespace { Line 895  namespace {
895       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
896       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
897       *       *
898         * For 16 bit samples, the data in the buffer will be int16_t
899         * (using native endianness). For 24 bit, the buffer will
900         * contain three bytes per sample, little-endian.
901         *
902       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
903       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
904       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 751  namespace { Line 909  namespace {
909          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
910          if (!Compressed) {          if (!Compressed) {
911              if (BitDepth == 24) {              if (BitDepth == 24) {
912                  // 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);  
                 }  
913              }              }
914              else { // 16 bit              else { // 16 bit
915                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 801  namespace { Line 939  namespace {
939    
940              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
941              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
942                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
943              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
944    
945              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 882  namespace { Line 1021  namespace {
1021                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1022                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1023    
1024                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1025                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1026                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1027                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1028                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1029                          }                          }
1030                          else { // Mono                          else { // Mono
1031                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1032                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1033                              pDst += copysamples;                              pDst24 += copysamples * 3;
1034                          }                          }
1035                      }                      }
1036                      else { // 16 bit                      else { // 16 bit
# Line 933  namespace { Line 1072  namespace {
1072          }          }
1073      }      }
1074    
1075        /** @brief Write sample wave data.
1076         *
1077         * Writes \a SampleCount number of sample points from the buffer pointed
1078         * by \a pBuffer and increments the position within the sample. Use this
1079         * method to directly write the sample data to disk, i.e. if you don't
1080         * want or cannot load the whole sample data into RAM.
1081         *
1082         * You have to Resize() the sample to the desired size and call
1083         * File::Save() <b>before</b> using Write().
1084         *
1085         * Note: there is currently no support for writing compressed samples.
1086         *
1087         * @param pBuffer     - source buffer
1088         * @param SampleCount - number of sample points to write
1089         * @throws DLS::Exception if current sample size is too small
1090         * @throws gig::Exception if sample is compressed
1091         * @see DLS::LoadSampleData()
1092         */
1093        unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {
1094            if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1095            return DLS::Sample::Write(pBuffer, SampleCount);
1096        }
1097    
1098      /**      /**
1099       * Allocates a decompression buffer for streaming (compressed) samples       * Allocates a decompression buffer for streaming (compressed) samples
1100       * 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 997  namespace { Line 1159  namespace {
1159      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1160          Instances++;          Instances++;
1161    
1162            pSample = NULL;
1163    
1164          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1165          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1166    
1167          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1168          _3ewa->ReadInt32(); // unknown, always 0x0000008C ?          if (_3ewa) { // if '3ewa' chunk exists
1169          LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?
1170          EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1171          _3ewa->ReadInt16(); // unknown              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1172          LFO1InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1173          _3ewa->ReadInt16(); // unknown              LFO1InternalDepth = _3ewa->ReadUint16();
1174          LFO3InternalDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1175          _3ewa->ReadInt16(); // unknown              LFO3InternalDepth = _3ewa->ReadInt16();
1176          LFO1ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1177          _3ewa->ReadInt16(); // unknown              LFO1ControlDepth = _3ewa->ReadUint16();
1178          LFO3ControlDepth = _3ewa->ReadInt16();              _3ewa->ReadInt16(); // unknown
1179          EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3ControlDepth = _3ewa->ReadInt16();
1180          EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Attack           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1181          _3ewa->ReadInt16(); // unknown              EG1Decay1           = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1182          EG1Sustain          = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1183          EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG1Sustain          = _3ewa->ReadUint16();
1184          EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1Release          = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1185          uint8_t eg1ctrloptions        = _3ewa->ReadUint8();              EG1Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1186          EG1ControllerInvert           = eg1ctrloptions & 0x01;              uint8_t eg1ctrloptions        = _3ewa->ReadUint8();
1187          EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerInvert           = eg1ctrloptions & 0x01;
1188          EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg1ctrloptions);
1189          EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);              EG1ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg1ctrloptions);
1190          EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              EG1ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg1ctrloptions);
1191          uint8_t eg2ctrloptions        = _3ewa->ReadUint8();              EG2Controller       = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1192          EG2ControllerInvert           = eg2ctrloptions & 0x01;              uint8_t eg2ctrloptions        = _3ewa->ReadUint8();
1193          EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerInvert           = eg2ctrloptions & 0x01;
1194          EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerAttackInfluence  = GIG_EG_CTR_ATTACK_INFLUENCE_EXTRACT(eg2ctrloptions);
1195          EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);              EG2ControllerDecayInfluence   = GIG_EG_CTR_DECAY_INFLUENCE_EXTRACT(eg2ctrloptions);
1196          LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2ControllerReleaseInfluence = GIG_EG_CTR_RELEASE_INFLUENCE_EXTRACT(eg2ctrloptions);
1197          EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO1Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1198          EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Attack        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1199          _3ewa->ReadInt16(); // unknown              EG2Decay1        = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1200          EG2Sustain       = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1201          EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG2Sustain       = _3ewa->ReadUint16();
1202          _3ewa->ReadInt16(); // unknown              EG2Release       = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1203          LFO2ControlDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1204          LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO2ControlDepth = _3ewa->ReadUint16();
1205          _3ewa->ReadInt16(); // unknown              LFO2Frequency    = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1206          LFO2InternalDepth = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1207          int32_t eg1decay2 = _3ewa->ReadInt32();              LFO2InternalDepth = _3ewa->ReadUint16();
1208          EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);              int32_t eg1decay2 = _3ewa->ReadInt32();
1209          EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);              EG1Decay2          = (double) GIG_EXP_DECODE(eg1decay2);
1210          _3ewa->ReadInt16(); // unknown              EG1InfiniteSustain = (eg1decay2 == 0x7fffffff);
1211          EG1PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1212          int32_t eg2decay2 = _3ewa->ReadInt32();              EG1PreAttack      = _3ewa->ReadUint16();
1213          EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);              int32_t eg2decay2 = _3ewa->ReadInt32();
1214          EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);              EG2Decay2         = (double) GIG_EXP_DECODE(eg2decay2);
1215          _3ewa->ReadInt16(); // unknown              EG2InfiniteSustain = (eg2decay2 == 0x7fffffff);
1216          EG2PreAttack      = _3ewa->ReadUint16();              _3ewa->ReadInt16(); // unknown
1217          uint8_t velocityresponse = _3ewa->ReadUint8();              EG2PreAttack      = _3ewa->ReadUint16();
1218          if (velocityresponse < 5) {              uint8_t velocityresponse = _3ewa->ReadUint8();
1219              VelocityResponseCurve = curve_type_nonlinear;              if (velocityresponse < 5) {
1220              VelocityResponseDepth = velocityresponse;                  VelocityResponseCurve = curve_type_nonlinear;
1221          }                  VelocityResponseDepth = velocityresponse;
1222          else if (velocityresponse < 10) {              } else if (velocityresponse < 10) {
1223              VelocityResponseCurve = curve_type_linear;                  VelocityResponseCurve = curve_type_linear;
1224              VelocityResponseDepth = velocityresponse - 5;                  VelocityResponseDepth = velocityresponse - 5;
1225          }              } else if (velocityresponse < 15) {
1226          else if (velocityresponse < 15) {                  VelocityResponseCurve = curve_type_special;
1227              VelocityResponseCurve = curve_type_special;                  VelocityResponseDepth = velocityresponse - 10;
1228              VelocityResponseDepth = velocityresponse - 10;              } else {
1229          }                  VelocityResponseCurve = curve_type_unknown;
1230          else {                  VelocityResponseDepth = 0;
1231              VelocityResponseCurve = curve_type_unknown;              }
1232              VelocityResponseDepth = 0;              uint8_t releasevelocityresponse = _3ewa->ReadUint8();
1233          }              if (releasevelocityresponse < 5) {
1234          uint8_t releasevelocityresponse = _3ewa->ReadUint8();                  ReleaseVelocityResponseCurve = curve_type_nonlinear;
1235          if (releasevelocityresponse < 5) {                  ReleaseVelocityResponseDepth = releasevelocityresponse;
1236              ReleaseVelocityResponseCurve = curve_type_nonlinear;              } else if (releasevelocityresponse < 10) {
1237              ReleaseVelocityResponseDepth = releasevelocityresponse;                  ReleaseVelocityResponseCurve = curve_type_linear;
1238          }                  ReleaseVelocityResponseDepth = releasevelocityresponse - 5;
1239          else if (releasevelocityresponse < 10) {              } else if (releasevelocityresponse < 15) {
1240              ReleaseVelocityResponseCurve = curve_type_linear;                  ReleaseVelocityResponseCurve = curve_type_special;
1241              ReleaseVelocityResponseDepth = releasevelocityresponse - 5;                  ReleaseVelocityResponseDepth = releasevelocityresponse - 10;
1242          }              } else {
1243          else if (releasevelocityresponse < 15) {                  ReleaseVelocityResponseCurve = curve_type_unknown;
1244              ReleaseVelocityResponseCurve = curve_type_special;                  ReleaseVelocityResponseDepth = 0;
1245              ReleaseVelocityResponseDepth = releasevelocityresponse - 10;              }
1246          }              VelocityResponseCurveScaling = _3ewa->ReadUint8();
1247          else {              AttenuationControllerThreshold = _3ewa->ReadInt8();
1248              ReleaseVelocityResponseCurve = curve_type_unknown;              _3ewa->ReadInt32(); // unknown
1249              ReleaseVelocityResponseDepth = 0;              SampleStartOffset = (uint16_t) _3ewa->ReadInt16();
1250          }              _3ewa->ReadInt16(); // unknown
1251          VelocityResponseCurveScaling = _3ewa->ReadUint8();              uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();
1252          AttenuationControllerThreshold = _3ewa->ReadInt8();              PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);
1253          _3ewa->ReadInt32(); // unknown              if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;
1254          SampleStartOffset = (uint16_t) _3ewa->ReadInt16();              else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;
1255          _3ewa->ReadInt16(); // unknown              else                                       DimensionBypass = dim_bypass_ctrl_none;
1256          uint8_t pitchTrackDimensionBypass = _3ewa->ReadInt8();              uint8_t pan = _3ewa->ReadUint8();
1257          PitchTrack = GIG_PITCH_TRACK_EXTRACT(pitchTrackDimensionBypass);              Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit
1258          if      (pitchTrackDimensionBypass & 0x10) DimensionBypass = dim_bypass_ctrl_94;              SelfMask = _3ewa->ReadInt8() & 0x01;
1259          else if (pitchTrackDimensionBypass & 0x20) DimensionBypass = dim_bypass_ctrl_95;              _3ewa->ReadInt8(); // unknown
1260          else                                       DimensionBypass = dim_bypass_ctrl_none;              uint8_t lfo3ctrl = _3ewa->ReadUint8();
1261          uint8_t pan = _3ewa->ReadUint8();              LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits
1262          Pan         = (pan < 64) ? pan : -((int)pan - 63); // signed 7 bit -> signed 8 bit              LFO3Sync                 = lfo3ctrl & 0x20; // bit 5
1263          SelfMask = _3ewa->ReadInt8() & 0x01;              InvertAttenuationController = lfo3ctrl & 0x80; // bit 7
1264          _3ewa->ReadInt8(); // unknown              AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));
1265          uint8_t lfo3ctrl = _3ewa->ReadUint8();              uint8_t lfo2ctrl       = _3ewa->ReadUint8();
1266          LFO3Controller           = static_cast<lfo3_ctrl_t>(lfo3ctrl & 0x07); // lower 3 bits              LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits
1267          LFO3Sync                 = lfo3ctrl & 0x20; // bit 5              LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7
1268          InvertAttenuationController = lfo3ctrl & 0x80; // bit 7              LFO2Sync               = lfo2ctrl & 0x20; // bit 5
1269          AttenuationController  = DecodeLeverageController(static_cast<_lev_ctrl_t>(_3ewa->ReadUint8()));              bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6
1270          uint8_t lfo2ctrl       = _3ewa->ReadUint8();              uint8_t lfo1ctrl       = _3ewa->ReadUint8();
1271          LFO2Controller         = static_cast<lfo2_ctrl_t>(lfo2ctrl & 0x07); // lower 3 bits              LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits
1272          LFO2FlipPhase          = lfo2ctrl & 0x80; // bit 7              LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7
1273          LFO2Sync               = lfo2ctrl & 0x20; // bit 5              LFO1Sync               = lfo1ctrl & 0x40; // bit 6
1274          bool extResonanceCtrl  = lfo2ctrl & 0x40; // bit 6              VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))
1275          uint8_t lfo1ctrl       = _3ewa->ReadUint8();                                                          : vcf_res_ctrl_none;
1276          LFO1Controller         = static_cast<lfo1_ctrl_t>(lfo1ctrl & 0x07); // lower 3 bits              uint16_t eg3depth = _3ewa->ReadUint16();
1277          LFO1FlipPhase          = lfo1ctrl & 0x80; // bit 7              EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */
1278          LFO1Sync               = lfo1ctrl & 0x40; // bit 6                                          : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */
1279          VCFResonanceController = (extResonanceCtrl) ? static_cast<vcf_res_ctrl_t>(GIG_VCF_RESONANCE_CTRL_EXTRACT(lfo1ctrl))              _3ewa->ReadInt16(); // unknown
1280                                                      : vcf_res_ctrl_none;              ChannelOffset = _3ewa->ReadUint8() / 4;
1281          uint16_t eg3depth = _3ewa->ReadUint16();              uint8_t regoptions = _3ewa->ReadUint8();
1282          EG3Depth = (eg3depth <= 1200) ? eg3depth /* positives */              MSDecode           = regoptions & 0x01; // bit 0
1283                                        : (-1) * (int16_t) ((eg3depth ^ 0xffff) + 1); /* binary complementary for negatives */              SustainDefeat      = regoptions & 0x02; // bit 1
1284          _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
1285          ChannelOffset = _3ewa->ReadUint8() / 4;              VelocityUpperLimit = _3ewa->ReadInt8();
1286          uint8_t regoptions = _3ewa->ReadUint8();              _3ewa->ReadInt8(); // unknown
1287          MSDecode           = regoptions & 0x01; // bit 0              _3ewa->ReadInt16(); // unknown
1288          SustainDefeat      = regoptions & 0x02; // bit 1              ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay
1289          _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt8(); // unknown
1290          VelocityUpperLimit = _3ewa->ReadInt8();              _3ewa->ReadInt8(); // unknown
1291          _3ewa->ReadInt8(); // unknown              EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7
1292          _3ewa->ReadInt16(); // unknown              uint8_t vcfcutoff = _3ewa->ReadUint8();
1293          ReleaseTriggerDecay = _3ewa->ReadUint8(); // release trigger decay              VCFEnabled = vcfcutoff & 0x80; // bit 7
1294          _3ewa->ReadInt8(); // unknown              VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits
1295          _3ewa->ReadInt8(); // unknown              VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());
1296          EG1Hold = _3ewa->ReadUint8() & 0x80; // bit 7              uint8_t vcfvelscale = _3ewa->ReadUint8();
1297          uint8_t vcfcutoff = _3ewa->ReadUint8();              VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7
1298          VCFEnabled = vcfcutoff & 0x80; // bit 7              VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits
1299          VCFCutoff  = vcfcutoff & 0x7f; // lower 7 bits              _3ewa->ReadInt8(); // unknown
1300          VCFCutoffController = static_cast<vcf_cutoff_ctrl_t>(_3ewa->ReadUint8());              uint8_t vcfresonance = _3ewa->ReadUint8();
1301          uint8_t vcfvelscale = _3ewa->ReadUint8();              VCFResonance = vcfresonance & 0x7f; // lower 7 bits
1302          VCFCutoffControllerInvert = vcfvelscale & 0x80; // bit 7              VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7
1303          VCFVelocityScale = vcfvelscale & 0x7f; // lower 7 bits              uint8_t vcfbreakpoint         = _3ewa->ReadUint8();
1304          _3ewa->ReadInt8(); // unknown              VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7
1305          uint8_t vcfresonance = _3ewa->ReadUint8();              VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits
1306          VCFResonance = vcfresonance & 0x7f; // lower 7 bits              uint8_t vcfvelocity = _3ewa->ReadUint8();
1307          VCFResonanceDynamic = !(vcfresonance & 0x80); // bit 7              VCFVelocityDynamicRange = vcfvelocity % 5;
1308          uint8_t vcfbreakpoint         = _3ewa->ReadUint8();              VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);
1309          VCFKeyboardTracking           = vcfbreakpoint & 0x80; // bit 7              VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());
1310          VCFKeyboardTrackingBreakpoint = vcfbreakpoint & 0x7f; // lower 7 bits              if (VCFType == vcf_type_lowpass) {
1311          uint8_t vcfvelocity = _3ewa->ReadUint8();                  if (lfo3ctrl & 0x40) // bit 6
1312          VCFVelocityDynamicRange = vcfvelocity % 5;                      VCFType = vcf_type_lowpassturbo;
1313          VCFVelocityCurve        = static_cast<curve_type_t>(vcfvelocity / 5);              }
1314          VCFType = static_cast<vcf_type_t>(_3ewa->ReadUint8());          } else { // '3ewa' chunk does not exist yet
1315          if (VCFType == vcf_type_lowpass) {              // use default values
1316              if (lfo3ctrl & 0x40) // bit 6              LFO3Frequency                   = 1.0;
1317                  VCFType = vcf_type_lowpassturbo;              EG3Attack                       = 0.0;
1318                LFO1InternalDepth               = 0;
1319                LFO3InternalDepth               = 0;
1320                LFO1ControlDepth                = 0;
1321                LFO3ControlDepth                = 0;
1322                EG1Attack                       = 0.0;
1323                EG1Decay1                       = 0.0;
1324                EG1Sustain                      = 0;
1325                EG1Release                      = 0.0;
1326                EG1Controller.type              = eg1_ctrl_t::type_none;
1327                EG1Controller.controller_number = 0;
1328                EG1ControllerInvert             = false;
1329                EG1ControllerAttackInfluence    = 0;
1330                EG1ControllerDecayInfluence     = 0;
1331                EG1ControllerReleaseInfluence   = 0;
1332                EG2Controller.type              = eg2_ctrl_t::type_none;
1333                EG2Controller.controller_number = 0;
1334                EG2ControllerInvert             = false;
1335                EG2ControllerAttackInfluence    = 0;
1336                EG2ControllerDecayInfluence     = 0;
1337                EG2ControllerReleaseInfluence   = 0;
1338                LFO1Frequency                   = 1.0;
1339                EG2Attack                       = 0.0;
1340                EG2Decay1                       = 0.0;
1341                EG2Sustain                      = 0;
1342                EG2Release                      = 0.0;
1343                LFO2ControlDepth                = 0;
1344                LFO2Frequency                   = 1.0;
1345                LFO2InternalDepth               = 0;
1346                EG1Decay2                       = 0.0;
1347                EG1InfiniteSustain              = false;
1348                EG1PreAttack                    = 1000;
1349                EG2Decay2                       = 0.0;
1350                EG2InfiniteSustain              = false;
1351                EG2PreAttack                    = 1000;
1352                VelocityResponseCurve           = curve_type_nonlinear;
1353                VelocityResponseDepth           = 3;
1354                ReleaseVelocityResponseCurve    = curve_type_nonlinear;
1355                ReleaseVelocityResponseDepth    = 3;
1356                VelocityResponseCurveScaling    = 32;
1357                AttenuationControllerThreshold  = 0;
1358                SampleStartOffset               = 0;
1359                PitchTrack                      = true;
1360                DimensionBypass                 = dim_bypass_ctrl_none;
1361                Pan                             = 0;
1362                SelfMask                        = true;
1363                LFO3Controller                  = lfo3_ctrl_modwheel;
1364                LFO3Sync                        = false;
1365                InvertAttenuationController     = false;
1366                AttenuationController.type      = attenuation_ctrl_t::type_none;
1367                AttenuationController.controller_number = 0;
1368                LFO2Controller                  = lfo2_ctrl_internal;
1369                LFO2FlipPhase                   = false;
1370                LFO2Sync                        = false;
1371                LFO1Controller                  = lfo1_ctrl_internal;
1372                LFO1FlipPhase                   = false;
1373                LFO1Sync                        = false;
1374                VCFResonanceController          = vcf_res_ctrl_none;
1375                EG3Depth                        = 0;
1376                ChannelOffset                   = 0;
1377                MSDecode                        = false;
1378                SustainDefeat                   = false;
1379                VelocityUpperLimit              = 0;
1380                ReleaseTriggerDecay             = 0;
1381                EG1Hold                         = false;
1382                VCFEnabled                      = false;
1383                VCFCutoff                       = 0;
1384                VCFCutoffController             = vcf_cutoff_ctrl_none;
1385                VCFCutoffControllerInvert       = false;
1386                VCFVelocityScale                = 0;
1387                VCFResonance                    = 0;
1388                VCFResonanceDynamic             = false;
1389                VCFKeyboardTracking             = false;
1390                VCFKeyboardTrackingBreakpoint   = 0;
1391                VCFVelocityDynamicRange         = 0x04;
1392                VCFVelocityCurve                = curve_type_linear;
1393                VCFType                         = vcf_type_lowpass;
1394          }          }
1395    
1396          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
# Line 1182  namespace { Line 1422  namespace {
1422              depth = 5;              depth = 5;
1423          }          }
1424          pVelocityCutoffTable = GetVelocityTable(curveType, depth,          pVelocityCutoffTable = GetVelocityTable(curveType, depth,
1425                                                  VCFCutoffController == vcf_cutoff_ctrl_none ? VCFVelocityScale : 0);                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1426    
1427          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1428            VelocityTable = 0;
1429        }
1430    
1431        /**
1432         * Apply dimension region settings to the respective RIFF chunks. You
1433         * have to call File::Save() to make changes persistent.
1434         *
1435         * Usually there is absolutely no need to call this method explicitly.
1436         * It will be called automatically when File::Save() was called.
1437         */
1438        void DimensionRegion::UpdateChunks() {
1439            // first update base class's chunk
1440            DLS::Sampler::UpdateChunks();
1441    
1442            // make sure '3ewa' chunk exists
1443            RIFF::Chunk* _3ewa = pParentList->GetSubChunk(CHUNK_ID_3EWA);
1444            if (!_3ewa)  _3ewa = pParentList->AddSubChunk(CHUNK_ID_3EWA, 140);
1445            uint8_t* pData = (uint8_t*) _3ewa->LoadChunkData();
1446    
1447            // update '3ewa' chunk with DimensionRegion's current settings
1448    
1449            const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?
1450            memcpy(&pData[0], &unknown, 4);
1451    
1452            const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1453            memcpy(&pData[4], &lfo3freq, 4);
1454    
1455            const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1456            memcpy(&pData[4], &eg3attack, 4);
1457    
1458            // next 2 bytes unknown
1459    
1460            memcpy(&pData[10], &LFO1InternalDepth, 2);
1461    
1462            // next 2 bytes unknown
1463    
1464            memcpy(&pData[14], &LFO3InternalDepth, 2);
1465    
1466            // next 2 bytes unknown
1467    
1468            memcpy(&pData[18], &LFO1ControlDepth, 2);
1469    
1470            // next 2 bytes unknown
1471    
1472            memcpy(&pData[22], &LFO3ControlDepth, 2);
1473    
1474            const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1475            memcpy(&pData[24], &eg1attack, 4);
1476    
1477            const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1478            memcpy(&pData[28], &eg1decay1, 4);
1479    
1480            // next 2 bytes unknown
1481    
1482            memcpy(&pData[34], &EG1Sustain, 2);
1483    
1484            const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1485            memcpy(&pData[36], &eg1release, 4);
1486    
1487            const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1488            memcpy(&pData[40], &eg1ctl, 1);
1489    
1490            const uint8_t eg1ctrloptions =
1491                (EG1ControllerInvert) ? 0x01 : 0x00 |
1492                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1493                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1494                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1495            memcpy(&pData[41], &eg1ctrloptions, 1);
1496    
1497            const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1498            memcpy(&pData[42], &eg2ctl, 1);
1499    
1500            const uint8_t eg2ctrloptions =
1501                (EG2ControllerInvert) ? 0x01 : 0x00 |
1502                GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1503                GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1504                GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1505            memcpy(&pData[43], &eg2ctrloptions, 1);
1506    
1507            const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1508            memcpy(&pData[44], &lfo1freq, 4);
1509    
1510            const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1511            memcpy(&pData[48], &eg2attack, 4);
1512    
1513            const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1514            memcpy(&pData[52], &eg2decay1, 4);
1515    
1516            // next 2 bytes unknown
1517    
1518            memcpy(&pData[58], &EG2Sustain, 2);
1519    
1520            const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1521            memcpy(&pData[60], &eg2release, 4);
1522    
1523            // next 2 bytes unknown
1524    
1525            memcpy(&pData[66], &LFO2ControlDepth, 2);
1526    
1527            const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1528            memcpy(&pData[68], &lfo2freq, 4);
1529    
1530            // next 2 bytes unknown
1531    
1532            memcpy(&pData[72], &LFO2InternalDepth, 2);
1533    
1534            const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1535            memcpy(&pData[74], &eg1decay2, 4);
1536    
1537            // next 2 bytes unknown
1538    
1539            memcpy(&pData[80], &EG1PreAttack, 2);
1540    
1541            const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1542            memcpy(&pData[82], &eg2decay2, 4);
1543    
1544            // next 2 bytes unknown
1545    
1546            memcpy(&pData[88], &EG2PreAttack, 2);
1547    
1548            {
1549                if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
1550                uint8_t velocityresponse = VelocityResponseDepth;
1551                switch (VelocityResponseCurve) {
1552                    case curve_type_nonlinear:
1553                        break;
1554                    case curve_type_linear:
1555                        velocityresponse += 5;
1556                        break;
1557                    case curve_type_special:
1558                        velocityresponse += 10;
1559                        break;
1560                    case curve_type_unknown:
1561                    default:
1562                        throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1563                }
1564                memcpy(&pData[90], &velocityresponse, 1);
1565            }
1566    
1567            {
1568                if (ReleaseVelocityResponseDepth > 4) throw Exception("ReleaseVelocityResponseDepth must be between 0 and 4");
1569                uint8_t releasevelocityresponse = ReleaseVelocityResponseDepth;
1570                switch (ReleaseVelocityResponseCurve) {
1571                    case curve_type_nonlinear:
1572                        break;
1573                    case curve_type_linear:
1574                        releasevelocityresponse += 5;
1575                        break;
1576                    case curve_type_special:
1577                        releasevelocityresponse += 10;
1578                        break;
1579                    case curve_type_unknown:
1580                    default:
1581                        throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1582                }
1583                memcpy(&pData[91], &releasevelocityresponse, 1);
1584            }
1585    
1586            memcpy(&pData[92], &VelocityResponseCurveScaling, 1);
1587    
1588            memcpy(&pData[93], &AttenuationControllerThreshold, 1);
1589    
1590            // next 4 bytes unknown
1591    
1592            memcpy(&pData[98], &SampleStartOffset, 2);
1593    
1594            // next 2 bytes unknown
1595    
1596            {
1597                uint8_t pitchTrackDimensionBypass = GIG_PITCH_TRACK_ENCODE(PitchTrack);
1598                switch (DimensionBypass) {
1599                    case dim_bypass_ctrl_94:
1600                        pitchTrackDimensionBypass |= 0x10;
1601                        break;
1602                    case dim_bypass_ctrl_95:
1603                        pitchTrackDimensionBypass |= 0x20;
1604                        break;
1605                    case dim_bypass_ctrl_none:
1606                        //FIXME: should we set anything here?
1607                        break;
1608                    default:
1609                        throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1610                }
1611                memcpy(&pData[102], &pitchTrackDimensionBypass, 1);
1612            }
1613    
1614            const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1615            memcpy(&pData[103], &pan, 1);
1616    
1617            const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1618            memcpy(&pData[104], &selfmask, 1);
1619    
1620            // next byte unknown
1621    
1622            {
1623                uint8_t lfo3ctrl = LFO3Controller & 0x07; // lower 3 bits
1624                if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1625                if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1626                if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1627                memcpy(&pData[106], &lfo3ctrl, 1);
1628            }
1629    
1630            const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1631            memcpy(&pData[107], &attenctl, 1);
1632    
1633            {
1634                uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1635                if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1636                if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1637                if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1638                memcpy(&pData[108], &lfo2ctrl, 1);
1639            }
1640    
1641            {
1642                uint8_t lfo1ctrl = LFO1Controller & 0x07; // lower 3 bits
1643                if (LFO1FlipPhase) lfo1ctrl |= 0x80; // bit 7
1644                if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1645                if (VCFResonanceController != vcf_res_ctrl_none)
1646                    lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1647                memcpy(&pData[109], &lfo1ctrl, 1);
1648            }
1649    
1650            const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1651                                                      : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1652            memcpy(&pData[110], &eg3depth, 1);
1653    
1654            // next 2 bytes unknown
1655    
1656            const uint8_t channeloffset = ChannelOffset * 4;
1657            memcpy(&pData[113], &channeloffset, 1);
1658    
1659            {
1660                uint8_t regoptions = 0;
1661                if (MSDecode)      regoptions |= 0x01; // bit 0
1662                if (SustainDefeat) regoptions |= 0x02; // bit 1
1663                memcpy(&pData[114], &regoptions, 1);
1664            }
1665    
1666            // next 2 bytes unknown
1667    
1668            memcpy(&pData[117], &VelocityUpperLimit, 1);
1669    
1670            // next 3 bytes unknown
1671    
1672            memcpy(&pData[121], &ReleaseTriggerDecay, 1);
1673    
1674            // next 2 bytes unknown
1675    
1676            const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1677            memcpy(&pData[124], &eg1hold, 1);
1678    
1679            const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1680                                      (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */
1681            memcpy(&pData[125], &vcfcutoff, 1);
1682    
1683            memcpy(&pData[126], &VCFCutoffController, 1);
1684    
1685            const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1686                                        (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */
1687            memcpy(&pData[127], &vcfvelscale, 1);
1688    
1689            // next byte unknown
1690    
1691            const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1692                                         (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */
1693            memcpy(&pData[129], &vcfresonance, 1);
1694    
1695            const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1696                                          (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */
1697            memcpy(&pData[130], &vcfbreakpoint, 1);
1698    
1699            const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1700                                        VCFVelocityCurve * 5;
1701            memcpy(&pData[131], &vcfvelocity, 1);
1702    
1703            const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1704            memcpy(&pData[132], &vcftype, 1);
1705      }      }
1706    
1707      // get the corresponding velocity 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
# Line 1320  namespace { Line 1837  namespace {
1837          return decodedcontroller;          return decodedcontroller;
1838      }      }
1839    
1840        DimensionRegion::_lev_ctrl_t DimensionRegion::EncodeLeverageController(leverage_ctrl_t DecodedController) {
1841            _lev_ctrl_t encodedcontroller;
1842            switch (DecodedController.type) {
1843                // special controller
1844                case leverage_ctrl_t::type_none:
1845                    encodedcontroller = _lev_ctrl_none;
1846                    break;
1847                case leverage_ctrl_t::type_velocity:
1848                    encodedcontroller = _lev_ctrl_velocity;
1849                    break;
1850                case leverage_ctrl_t::type_channelaftertouch:
1851                    encodedcontroller = _lev_ctrl_channelaftertouch;
1852                    break;
1853    
1854                // ordinary MIDI control change controller
1855                case leverage_ctrl_t::type_controlchange:
1856                    switch (DecodedController.controller_number) {
1857                        case 1:
1858                            encodedcontroller = _lev_ctrl_modwheel;
1859                            break;
1860                        case 2:
1861                            encodedcontroller = _lev_ctrl_breath;
1862                            break;
1863                        case 4:
1864                            encodedcontroller = _lev_ctrl_foot;
1865                            break;
1866                        case 12:
1867                            encodedcontroller = _lev_ctrl_effect1;
1868                            break;
1869                        case 13:
1870                            encodedcontroller = _lev_ctrl_effect2;
1871                            break;
1872                        case 16:
1873                            encodedcontroller = _lev_ctrl_genpurpose1;
1874                            break;
1875                        case 17:
1876                            encodedcontroller = _lev_ctrl_genpurpose2;
1877                            break;
1878                        case 18:
1879                            encodedcontroller = _lev_ctrl_genpurpose3;
1880                            break;
1881                        case 19:
1882                            encodedcontroller = _lev_ctrl_genpurpose4;
1883                            break;
1884                        case 5:
1885                            encodedcontroller = _lev_ctrl_portamentotime;
1886                            break;
1887                        case 64:
1888                            encodedcontroller = _lev_ctrl_sustainpedal;
1889                            break;
1890                        case 65:
1891                            encodedcontroller = _lev_ctrl_portamento;
1892                            break;
1893                        case 66:
1894                            encodedcontroller = _lev_ctrl_sostenutopedal;
1895                            break;
1896                        case 67:
1897                            encodedcontroller = _lev_ctrl_softpedal;
1898                            break;
1899                        case 80:
1900                            encodedcontroller = _lev_ctrl_genpurpose5;
1901                            break;
1902                        case 81:
1903                            encodedcontroller = _lev_ctrl_genpurpose6;
1904                            break;
1905                        case 82:
1906                            encodedcontroller = _lev_ctrl_genpurpose7;
1907                            break;
1908                        case 83:
1909                            encodedcontroller = _lev_ctrl_genpurpose8;
1910                            break;
1911                        case 91:
1912                            encodedcontroller = _lev_ctrl_effect1depth;
1913                            break;
1914                        case 92:
1915                            encodedcontroller = _lev_ctrl_effect2depth;
1916                            break;
1917                        case 93:
1918                            encodedcontroller = _lev_ctrl_effect3depth;
1919                            break;
1920                        case 94:
1921                            encodedcontroller = _lev_ctrl_effect4depth;
1922                            break;
1923                        case 95:
1924                            encodedcontroller = _lev_ctrl_effect5depth;
1925                            break;
1926                        default:
1927                            throw gig::Exception("leverage controller number is not supported by the gig format");
1928                    }
1929                default:
1930                    throw gig::Exception("Unknown leverage controller type.");
1931            }
1932            return encodedcontroller;
1933        }
1934    
1935      DimensionRegion::~DimensionRegion() {      DimensionRegion::~DimensionRegion() {
1936          Instances--;          Instances--;
1937          if (!Instances) {          if (!Instances) {
# Line 1333  namespace { Line 1945  namespace {
1945              delete pVelocityTables;              delete pVelocityTables;
1946              pVelocityTables = NULL;              pVelocityTables = NULL;
1947          }          }
1948            if (VelocityTable) delete[] VelocityTable;
1949      }      }
1950    
1951      /**      /**
# Line 1449  namespace { Line 2062  namespace {
2062              for (int i = 0; i < dimensionBits; i++) {              for (int i = 0; i < dimensionBits; i++) {
2063                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());                  dimension_t dimension = static_cast<dimension_t>(_3lnk->ReadUint8());
2064                  uint8_t     bits      = _3lnk->ReadUint8();                  uint8_t     bits      = _3lnk->ReadUint8();
2065                    _3lnk->ReadUint8(); // probably the position of the dimension
2066                    _3lnk->ReadUint8(); // unknown
2067                    uint8_t     zones     = _3lnk->ReadUint8(); // new for v3: number of zones doesn't have to be == pow(2,bits)
2068                  if (dimension == dimension_none) { // inactive dimension                  if (dimension == dimension_none) { // inactive dimension
2069                      pDimensionDefinitions[i].dimension  = dimension_none;                      pDimensionDefinitions[i].dimension  = dimension_none;
2070                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2071                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2072                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2073                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2074                  }                  }
2075                  else { // active dimension                  else { // active dimension
2076                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2077                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2078                      pDimensionDefinitions[i].zones     = 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2079                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2080                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2081                                                             dimension == dimension_releasetrigger ||                                                             dimension == dimension_releasetrigger ||
2082                                                               dimension == dimension_keyboard ||
2083                                                             dimension == dimension_roundrobin ||                                                             dimension == dimension_roundrobin ||
2084                                                             dimension == dimension_random) ? split_type_bit                                                             dimension == dimension_random) ? split_type_bit
2085                                                                                            : split_type_normal;                                                                                            : split_type_normal;
                     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point  
2086                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2087                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2088                                                                                     : 0;                                                                                     : 0;
2089                      Dimensions++;                      Dimensions++;
2090    
2091                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
2092                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;                      if (dimension == dimension_layer) Layers = pDimensionDefinitions[i].zones;
2093                  }                  }
2094                  _3lnk->SetPos(6, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2095              }              }
2096                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2097    
2098              // 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,
2099              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2100                  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;  
                             }  
                         }  
                     }  
                 }  
             }  
2101    
2102              // 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();  
2103              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2104                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2105              else              else
# Line 1519  namespace { Line 2108  namespace {
2108              // load sample references              // load sample references
2109              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2110                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2111                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2112              }              }
2113          }          }
2114          else throw gig::Exception("Mandatory <3lnk> chunk not found.");  
2115            // make sure there is at least one dimension region
2116            if (!DimensionRegions) {
2117                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2118                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2119                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2120                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2121                DimensionRegions = 1;
2122            }
2123        }
2124    
2125        /**
2126         * Apply Region settings and all its DimensionRegions to the respective
2127         * RIFF chunks. You have to call File::Save() to make changes persistent.
2128         *
2129         * Usually there is absolutely no need to call this method explicitly.
2130         * It will be called automatically when File::Save() was called.
2131         *
2132         * @throws gig::Exception if samples cannot be dereferenced
2133         */
2134        void Region::UpdateChunks() {
2135            // first update base class's chunks
2136            DLS::Region::UpdateChunks();
2137    
2138            // update dimension region's chunks
2139            for (int i = 0; i < DimensionRegions; i++) {
2140                pDimensionRegions[i]->UpdateChunks();
2141            }
2142    
2143            File* pFile = (File*) GetParent()->GetParent();
2144            const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
2145            const int iMaxDimensionRegions = (pFile->pVersion && pFile->pVersion->major == 3) ? 256 : 32;
2146    
2147            // make sure '3lnk' chunk exists
2148            RIFF::Chunk* _3lnk = pCkRegion->GetSubChunk(CHUNK_ID_3LNK);
2149            if (!_3lnk) {
2150                const int _3lnkChunkSize = (pFile->pVersion && pFile->pVersion->major == 3) ? 1092 : 172;
2151                _3lnk = pCkRegion->AddSubChunk(CHUNK_ID_3LNK, _3lnkChunkSize);
2152            }
2153    
2154            // update dimension definitions in '3lnk' chunk
2155            uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2156            for (int i = 0; i < iMaxDimensions; i++) {
2157                pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;
2158                pData[i * 8 + 1] = pDimensionDefinitions[i].bits;
2159                // next 2 bytes unknown
2160                pData[i * 8 + 4] = pDimensionDefinitions[i].zones;
2161                // next 3 bytes unknown
2162            }
2163    
2164            // update wave pool table in '3lnk' chunk
2165            const int iWavePoolOffset = (pFile->pVersion && pFile->pVersion->major == 3) ? 68 : 44;
2166            for (uint i = 0; i < iMaxDimensionRegions; i++) {
2167                int iWaveIndex = -1;
2168                if (i < DimensionRegions) {
2169                    if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2170                    File::SampleList::iterator iter = pFile->pSamples->begin();
2171                    File::SampleList::iterator end  = pFile->pSamples->end();
2172                    for (int index = 0; iter != end; ++iter, ++index) {
2173                        if (*iter == pDimensionRegions[i]->pSample) {
2174                            iWaveIndex = index;
2175                            break;
2176                        }
2177                    }
2178                    if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2179                }
2180                memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);
2181            }
2182      }      }
2183    
2184      void Region::LoadDimensionRegions(RIFF::List* rgn) {      void Region::LoadDimensionRegions(RIFF::List* rgn) {
# Line 1541  namespace { Line 2197  namespace {
2197          }          }
2198      }      }
2199    
2200      Region::~Region() {      void Region::UpdateVelocityTable() {
2201          for (uint i = 0; i < Dimensions; i++) {          // get velocity dimension's index
2202              if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;          int veldim = -1;
2203            for (int i = 0 ; i < Dimensions ; i++) {
2204                if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2205                    veldim = i;
2206                    break;
2207                }
2208            }
2209            if (veldim == -1) return;
2210    
2211            int step = 1;
2212            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2213            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2214            int end = step * pDimensionDefinitions[veldim].zones;
2215    
2216            // loop through all dimension regions for all dimensions except the velocity dimension
2217            int dim[8] = { 0 };
2218            for (int i = 0 ; i < DimensionRegions ; i++) {
2219    
2220                if (pDimensionRegions[i]->VelocityUpperLimit) {
2221                    // create the velocity table
2222                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2223                    if (!table) {
2224                        table = new uint8_t[128];
2225                        pDimensionRegions[i]->VelocityTable = table;
2226                    }
2227                    int tableidx = 0;
2228                    int velocityZone = 0;
2229                    for (int k = i ; k < end ; k += step) {
2230                        DimensionRegion *d = pDimensionRegions[k];
2231                        for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2232                        velocityZone++;
2233                    }
2234                } else {
2235                    if (pDimensionRegions[i]->VelocityTable) {
2236                        delete[] pDimensionRegions[i]->VelocityTable;
2237                        pDimensionRegions[i]->VelocityTable = 0;
2238                    }
2239                }
2240    
2241                int j;
2242                int shift = 0;
2243                for (j = 0 ; j < Dimensions ; j++) {
2244                    if (j == veldim) i += skipveldim; // skip velocity dimension
2245                    else {
2246                        dim[j]++;
2247                        if (dim[j] < pDimensionDefinitions[j].zones) break;
2248                        else {
2249                            // skip unused dimension regions
2250                            dim[j] = 0;
2251                            i += ((1 << pDimensionDefinitions[j].bits) -
2252                                  pDimensionDefinitions[j].zones) << shift;
2253                        }
2254                    }
2255                    shift += pDimensionDefinitions[j].bits;
2256                }
2257                if (j == Dimensions) break;
2258            }
2259        }
2260    
2261        /** @brief Einstein would have dreamed of it - create a new dimension.
2262         *
2263         * Creates a new dimension with the dimension definition given by
2264         * \a pDimDef. The appropriate amount of DimensionRegions will be created.
2265         * There is a hard limit of dimensions and total amount of "bits" all
2266         * dimensions can have. This limit is dependant to what gig file format
2267         * version this file refers to. The gig v2 (and lower) format has a
2268         * dimension limit and total amount of bits limit of 5, whereas the gig v3
2269         * format has a limit of 8.
2270         *
2271         * @param pDimDef - defintion of the new dimension
2272         * @throws gig::Exception if dimension of the same type exists already
2273         * @throws gig::Exception if amount of dimensions or total amount of
2274         *                        dimension bits limit is violated
2275         */
2276        void Region::AddDimension(dimension_def_t* pDimDef) {
2277            // check if max. amount of dimensions reached
2278            File* file = (File*) GetParent()->GetParent();
2279            const int iMaxDimensions = (file->pVersion && file->pVersion->major == 3) ? 8 : 5;
2280            if (Dimensions >= iMaxDimensions)
2281                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimensions already reached");
2282            // check if max. amount of dimension bits reached
2283            int iCurrentBits = 0;
2284            for (int i = 0; i < Dimensions; i++)
2285                iCurrentBits += pDimensionDefinitions[i].bits;
2286            if (iCurrentBits >= iMaxDimensions)
2287                throw gig::Exception("Could not add new dimension, max. amount of " + ToString(iMaxDimensions) + " dimension bits already reached");
2288            const int iNewBits = iCurrentBits + pDimDef->bits;
2289            if (iNewBits > iMaxDimensions)
2290                throw gig::Exception("Could not add new dimension, new dimension would exceed max. amount of " + ToString(iMaxDimensions) + " dimension bits");
2291            // check if there's already a dimensions of the same type
2292            for (int i = 0; i < Dimensions; i++)
2293                if (pDimensionDefinitions[i].dimension == pDimDef->dimension)
2294                    throw gig::Exception("Could not add new dimension, there is already a dimension of the same type");
2295    
2296            // assign definition of new dimension
2297            pDimensionDefinitions[Dimensions] = *pDimDef;
2298    
2299            // create new dimension region(s) for this new dimension
2300            for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2301                //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
2302                RIFF::List* pNewDimRgnListChunk = pCkRegion->AddSubList(LIST_TYPE_3EWL);
2303                pDimensionRegions[i] = new DimensionRegion(pNewDimRgnListChunk);
2304                DimensionRegions++;
2305            }
2306    
2307            Dimensions++;
2308    
2309            // if this is a layer dimension, update 'Layers' attribute
2310            if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2311    
2312            UpdateVelocityTable();
2313        }
2314    
2315        /** @brief Delete an existing dimension.
2316         *
2317         * Deletes the dimension given by \a pDimDef and deletes all respective
2318         * dimension regions, that is all dimension regions where the dimension's
2319         * bit(s) part is greater than 0. In case of a 'sustain pedal' dimension
2320         * for example this would delete all dimension regions for the case(s)
2321         * where the sustain pedal is pressed down.
2322         *
2323         * @param pDimDef - dimension to delete
2324         * @throws gig::Exception if given dimension cannot be found
2325         */
2326        void Region::DeleteDimension(dimension_def_t* pDimDef) {
2327            // get dimension's index
2328            int iDimensionNr = -1;
2329            for (int i = 0; i < Dimensions; i++) {
2330                if (&pDimensionDefinitions[i] == pDimDef) {
2331                    iDimensionNr = i;
2332                    break;
2333                }
2334            }
2335            if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");
2336    
2337            // get amount of bits below the dimension to delete
2338            int iLowerBits = 0;
2339            for (int i = 0; i < iDimensionNr; i++)
2340                iLowerBits += pDimensionDefinitions[i].bits;
2341    
2342            // get amount ot bits above the dimension to delete
2343            int iUpperBits = 0;
2344            for (int i = iDimensionNr + 1; i < Dimensions; i++)
2345                iUpperBits += pDimensionDefinitions[i].bits;
2346    
2347            // delete dimension regions which belong to the given dimension
2348            // (that is where the dimension's bit > 0)
2349            for (int iUpperBit = 0; iUpperBit < 1 << iUpperBits; iUpperBit++) {
2350                for (int iObsoleteBit = 1; iObsoleteBit < 1 << pDimensionDefinitions[iDimensionNr].bits; iObsoleteBit++) {
2351                    for (int iLowerBit = 0; iLowerBit < 1 << iLowerBits; iLowerBit++) {
2352                        int iToDelete = iUpperBit    << (pDimensionDefinitions[iDimensionNr].bits + iLowerBits) |
2353                                        iObsoleteBit << iLowerBits |
2354                                        iLowerBit;
2355                        delete pDimensionRegions[iToDelete];
2356                        pDimensionRegions[iToDelete] = NULL;
2357                        DimensionRegions--;
2358                    }
2359                }
2360            }
2361    
2362            // defrag pDimensionRegions array
2363            // (that is remove the NULL spaces within the pDimensionRegions array)
2364            for (int iFrom = 2, iTo = 1; iFrom < 256 && iTo < 256 - 1; iTo++) {
2365                if (!pDimensionRegions[iTo]) {
2366                    if (iFrom <= iTo) iFrom = iTo + 1;
2367                    while (!pDimensionRegions[iFrom] && iFrom < 256) iFrom++;
2368                    if (iFrom < 256 && pDimensionRegions[iFrom]) {
2369                        pDimensionRegions[iTo]   = pDimensionRegions[iFrom];
2370                        pDimensionRegions[iFrom] = NULL;
2371                    }
2372                }
2373            }
2374    
2375            // 'remove' dimension definition
2376            for (int i = iDimensionNr + 1; i < Dimensions; i++) {
2377                pDimensionDefinitions[i - 1] = pDimensionDefinitions[i];
2378          }          }
2379            pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2380            pDimensionDefinitions[Dimensions - 1].bits      = 0;
2381            pDimensionDefinitions[Dimensions - 1].zones     = 0;
2382    
2383            Dimensions--;
2384    
2385            // if this was a layer dimension, update 'Layers' attribute
2386            if (pDimDef->dimension == dimension_layer) Layers = 1;
2387        }
2388    
2389        Region::~Region() {
2390          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2391              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2392          }          }
# Line 1569  namespace { Line 2411  namespace {
2411       * @see             Dimensions       * @see             Dimensions
2412       */       */
2413      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2414          uint8_t bits[8] = { 0 };          uint8_t bits;
2415            int veldim = -1;
2416            int velbitpos;
2417            int bitpos = 0;
2418            int dimregidx = 0;
2419          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2420              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2421              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2422                  case split_type_normal:                  veldim = i;
2423                      bits[i] /= pDimensionDefinitions[i].zone_size;                  velbitpos = bitpos;
2424                      break;              } else {
2425                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2426                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2427                      break;                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2428                  case split_type_bit: // the value is already the sought dimension bit number                          break;
2429                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                      case split_type_bit: // the value is already the sought dimension bit number
2430                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                          const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2431                      break;                          bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2432              }                          break;
2433                    }
2434                    dimregidx |= bits << bitpos;
2435                }
2436                bitpos += pDimensionDefinitions[i].bits;
2437            }
2438            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2439            if (veldim != -1) {
2440                // (dimreg is now the dimension region for the lowest velocity)
2441                if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2442                    bits = dimreg->VelocityTable[DimValues[veldim]];
2443                else // normal split type
2444                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2445    
2446                dimregidx |= bits << velbitpos;
2447                dimreg = pDimensionRegions[dimregidx];
2448          }          }
2449          return GetDimensionRegionByBit(bits);          return dimreg;
2450      }      }
2451    
2452      /**      /**
# Line 1625  namespace { Line 2486  namespace {
2486      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2487          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2488          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2489            if (!file->pWavePoolTable) return NULL;
2490          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2491          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2492          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
# Line 1644  namespace { Line 2506  namespace {
2506      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) {
2507          // Initialization          // Initialization
2508          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2509    
2510          // Loading          // Loading
2511          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 1660  namespace { Line 2521  namespace {
2521                  DimensionKeyRange.low  = dimkeystart >> 1;                  DimensionKeyRange.low  = dimkeystart >> 1;
2522                  DimensionKeyRange.high = _3ewg->ReadUint8();                  DimensionKeyRange.high = _3ewg->ReadUint8();
2523              }              }
             else throw gig::Exception("Mandatory <3ewg> chunk not found.");  
2524          }          }
         else throw gig::Exception("Mandatory <lart> list chunk not found.");  
2525    
2526            if (!pRegions) pRegions = new RegionList;
2527          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2528          if (!lrgn) throw gig::Exception("Mandatory chunks in <ins > chunk not found.");          if (lrgn) {
2529          pRegions = new Region*[Regions];              RIFF::List* rgn = lrgn->GetFirstSubList();
2530          for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;              while (rgn) {
2531          RIFF::List* rgn = lrgn->GetFirstSubList();                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2532          unsigned int iRegion = 0;                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2533          while (rgn) {                      pRegions->push_back(new Region(this, rgn));
2534              if (rgn->GetListType() == LIST_TYPE_RGN) {                  }
2535                  __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];  
2536              }              }
2537                // Creating Region Key Table for fast lookup
2538                UpdateRegionKeyTable();
2539          }          }
2540    
2541          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
2542      }      }
2543    
2544      Instrument::~Instrument() {      void Instrument::UpdateRegionKeyTable() {
2545          for (uint i = 0; i < Regions; i++) {          RegionList::iterator iter = pRegions->begin();
2546              if (pRegions) {          RegionList::iterator end  = pRegions->end();
2547                  if (pRegions[i]) delete (pRegions[i]);          for (; iter != end; ++iter) {
2548                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2549                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2550                    RegionKeyTable[iKey] = pRegion;
2551              }              }
2552          }          }
2553          if (pRegions) delete[] pRegions;      }
2554    
2555        Instrument::~Instrument() {
2556        }
2557    
2558        /**
2559         * Apply Instrument with all its Regions to the respective RIFF chunks.
2560         * You have to call File::Save() to make changes persistent.
2561         *
2562         * Usually there is absolutely no need to call this method explicitly.
2563         * It will be called automatically when File::Save() was called.
2564         *
2565         * @throws gig::Exception if samples cannot be dereferenced
2566         */
2567        void Instrument::UpdateChunks() {
2568            // first update base classes' chunks
2569            DLS::Instrument::UpdateChunks();
2570    
2571            // update Regions' chunks
2572            {
2573                RegionList::iterator iter = pRegions->begin();
2574                RegionList::iterator end  = pRegions->end();
2575                for (; iter != end; ++iter)
2576                    (*iter)->UpdateChunks();
2577            }
2578    
2579            // make sure 'lart' RIFF list chunk exists
2580            RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
2581            if (!lart)  lart = pCkInstrument->AddSubList(LIST_TYPE_LART);
2582            // make sure '3ewg' RIFF chunk exists
2583            RIFF::Chunk* _3ewg = lart->GetSubChunk(CHUNK_ID_3EWG);
2584            if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2585            // update '3ewg' RIFF chunk
2586            uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2587            memcpy(&pData[0], &EffectSend, 2);
2588            memcpy(&pData[2], &Attenuation, 4);
2589            memcpy(&pData[6], &FineTune, 2);
2590            memcpy(&pData[8], &PitchbendRange, 2);
2591            const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2592                                        DimensionKeyRange.low << 1;
2593            memcpy(&pData[10], &dimkeystart, 1);
2594            memcpy(&pData[11], &DimensionKeyRange.high, 1);
2595      }      }
2596    
2597      /**      /**
# Line 1706  namespace { Line 2602  namespace {
2602       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2603       */       */
2604      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2605          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2606          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2607    
2608          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2609              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2610                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 1723  namespace { Line 2620  namespace {
2620       * @see      GetNextRegion()       * @see      GetNextRegion()
2621       */       */
2622      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2623          if (!Regions) return NULL;          if (!pRegions) return NULL;
2624          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2625          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2626      }      }
2627    
2628      /**      /**
# Line 1737  namespace { Line 2634  namespace {
2634       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2635       */       */
2636      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2637          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2638          return pRegions[RegionIndex++];          RegionsIterator++;
2639            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2640        }
2641    
2642        Region* Instrument::AddRegion() {
2643            // create new Region object (and its RIFF chunks)
2644            RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
2645            if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2646            RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2647            Region* pNewRegion = new Region(this, rgn);
2648            pRegions->push_back(pNewRegion);
2649            Regions = pRegions->size();
2650            // update Region key table for fast lookup
2651            UpdateRegionKeyTable();
2652            // done
2653            return pNewRegion;
2654        }
2655    
2656        void Instrument::DeleteRegion(Region* pRegion) {
2657            if (!pRegions) return;
2658            DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
2659            // update Region key table for fast lookup
2660            UpdateRegionKeyTable();
2661      }      }
2662    
2663    
# Line 1746  namespace { Line 2665  namespace {
2665  // *************** File ***************  // *************** File ***************
2666  // *  // *
2667    
2668      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File() : DLS::File() {
         pSamples     = NULL;  
         pInstruments = NULL;  
2669      }      }
2670    
2671      File::~File() {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
         // free samples  
         if (pSamples) {  
             SamplesIterator = pSamples->begin();  
             while (SamplesIterator != pSamples->end() ) {  
                 delete (*SamplesIterator);  
                 SamplesIterator++;  
             }  
             pSamples->clear();  
             delete pSamples;  
   
         }  
         // free instruments  
         if (pInstruments) {  
             InstrumentsIterator = pInstruments->begin();  
             while (InstrumentsIterator != pInstruments->end() ) {  
                 delete (*InstrumentsIterator);  
                 InstrumentsIterator++;  
             }  
             pInstruments->clear();  
             delete pInstruments;  
         }  
         // free extension files  
         for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)  
             delete *i;  
2672      }      }
2673    
2674      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 1791  namespace { Line 2684  namespace {
2684          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );          return static_cast<gig::Sample*>( (SamplesIterator != pSamples->end()) ? *SamplesIterator : NULL );
2685      }      }
2686    
2687        /** @brief Add a new sample.
2688         *
2689         * This will create a new Sample object for the gig file. You have to
2690         * call Save() to make this persistent to the file.
2691         *
2692         * @returns pointer to new Sample object
2693         */
2694        Sample* File::AddSample() {
2695           if (!pSamples) LoadSamples();
2696           __ensureMandatoryChunksExist();
2697           RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2698           // create new Sample object and its respective 'wave' list chunk
2699           RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2700           Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2701           pSamples->push_back(pSample);
2702           return pSample;
2703        }
2704    
2705        /** @brief Delete a sample.
2706         *
2707         * This will delete the given Sample object from the gig file. You have
2708         * to call Save() to make this persistent to the file.
2709         *
2710         * @param pSample - sample to delete
2711         * @throws gig::Exception if given sample could not be found
2712         */
2713        void File::DeleteSample(Sample* pSample) {
2714            if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2715            SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2716            if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2717            pSamples->erase(iter);
2718            delete pSample;
2719        }
2720    
2721        void File::LoadSamples() {
2722            LoadSamples(NULL);
2723        }
2724    
2725      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
2726            if (!pSamples) pSamples = new SampleList;
2727    
2728          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
2729    
2730          // just for progress calculation          // just for progress calculation
# Line 1803  namespace { Line 2736  namespace {
2736          for (int i = 0 ; i < WavePoolCount ; i++) {          for (int i = 0 ; i < WavePoolCount ; i++) {
2737              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
2738          }          }
2739          String name(pRIFF->Filename);          String name(pRIFF->GetFileName());
2740          int nameLen = pRIFF->Filename.length();          int nameLen = name.length();
2741          char suffix[6];          char suffix[6];
2742          if (nameLen > 4 && pRIFF->Filename.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
2743    
2744          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
2745              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
# Line 1819  namespace { Line 2752  namespace {
2752                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2753                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
2754    
                         if (!pSamples) pSamples = new SampleList;  
2755                          unsigned long waveFileOffset = wave->GetFilePos();                          unsigned long waveFileOffset = wave->GetFilePos();
2756                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2757    
# Line 1836  namespace { Line 2768  namespace {
2768                  name.replace(nameLen, 5, suffix);                  name.replace(nameLen, 5, suffix);
2769                  file = new RIFF::File(name);                  file = new RIFF::File(name);
2770                  ExtensionFiles.push_back(file);                  ExtensionFiles.push_back(file);
2771              }              } else break;
             else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2772          }          }
2773    
2774          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
# Line 1847  namespace { Line 2778  namespace {
2778          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2779          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2780          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2781          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2782      }      }
2783    
2784      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2785          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2786          InstrumentsIterator++;          InstrumentsIterator++;
2787          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2788      }      }
2789    
2790      /**      /**
# Line 1886  namespace { Line 2817  namespace {
2817          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2818          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2819          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2820              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2821              InstrumentsIterator++;              InstrumentsIterator++;
2822          }          }
2823          return NULL;          return NULL;
2824      }      }
2825    
2826        /** @brief Add a new instrument definition.
2827         *
2828         * This will create a new Instrument object for the gig file. You have
2829         * to call Save() to make this persistent to the file.
2830         *
2831         * @returns pointer to new Instrument object
2832         */
2833        Instrument* File::AddInstrument() {
2834           if (!pInstruments) LoadInstruments();
2835           __ensureMandatoryChunksExist();
2836           RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2837           RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2838           Instrument* pInstrument = new Instrument(this, lstInstr);
2839           pInstruments->push_back(pInstrument);
2840           return pInstrument;
2841        }
2842    
2843        /** @brief Delete an instrument.
2844         *
2845         * This will delete the given Instrument object from the gig file. You
2846         * have to call Save() to make this persistent to the file.
2847         *
2848         * @param pInstrument - instrument to delete
2849         * @throws gig::Excption if given instrument could not be found
2850         */
2851        void File::DeleteInstrument(Instrument* pInstrument) {
2852            if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2853            InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2854            if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2855            pInstruments->erase(iter);
2856            delete pInstrument;
2857        }
2858    
2859        void File::LoadInstruments() {
2860            LoadInstruments(NULL);
2861        }
2862    
2863      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
2864            if (!pInstruments) pInstruments = new InstrumentList;
2865          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2866          if (lstInstruments) {          if (lstInstruments) {
2867              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 1907  namespace { Line 2876  namespace {
2876                      progress_t subprogress;                      progress_t subprogress;
2877                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2878    
                     if (!pInstruments) pInstruments = new InstrumentList;  
2879                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2880    
2881                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 1916  namespace { Line 2884  namespace {
2884              }              }
2885              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
2886          }          }
         else throw gig::Exception("Mandatory <lins> list chunk not found.");  
2887      }      }
2888    
2889    

Legend:
Removed from v.728  
changed lines
  Added in v.902

  ViewVC Help
Powered by ViewVC