/[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 809 by schoenebeck, Tue Nov 22 11:26:55 2005 UTC revision 929 by schoenebeck, Tue Oct 24 22:24:45 2006 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file loader library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2006 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 51  Line 51 
51    
52  namespace gig {  namespace gig {
53    
 // *************** dimension_def_t ***************  
 // *  
   
     dimension_def_t& dimension_def_t::operator=(const dimension_def_t& arg) {  
         dimension  = arg.dimension;  
         bits       = arg.bits;  
         zones      = arg.zones;  
         split_type = arg.split_type;  
         ranges     = arg.ranges;  
         zone_size  = arg.zone_size;  
         if (ranges) {  
             ranges = new range_t[zones];  
             for (int i = 0; i < zones; i++)  
                 ranges[i] = arg.ranges[i];  
         }  
         return *this;  
     }  
   
   
   
54  // *************** progress_t ***************  // *************** progress_t ***************
55  // *  // *
56    
# Line 131  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 170  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 193  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 295  namespace { Line 279  namespace {
279       *                         is located, 0 otherwise       *                         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            pInfo->UseFixedLengthStrings = true;
283          Instances++;          Instances++;
284          FileNo = fileNo;          FileNo = fileNo;
285    
286          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
287          if (pCk3gix) {          if (pCk3gix) {
288              SampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
289                // caution: sample groups in .gig files are indexed (1..n) whereas Groups in libgig (0..n-1)
290                pGroup = pFile->GetGroup(iSampleGroup - 1);
291          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
292              // use default value(s)              // not assigned to a group by default
293              SampleGroup = 0;              pGroup = NULL;
294          }          }
295    
296          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 327  namespace { Line 314  namespace {
314              // use default values              // use default values
315              Manufacturer  = 0;              Manufacturer  = 0;
316              Product       = 0;              Product       = 0;
317              SamplePeriod  = 1 / SamplesPerSecond;              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
318              MIDIUnityNote = 64;              MIDIUnityNote = 64;
319              FineTune      = 0;              FineTune      = 0;
320              SMPTEOffset   = 0;              SMPTEOffset   = 0;
# Line 368  namespace { Line 355  namespace {
355          }          }
356          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
357    
358          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
359      }      }
360    
361      /**      /**
# Line 391  namespace { Line 378  namespace {
378          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
379          // update 'smpl' chunk          // update 'smpl' chunk
380          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
381          SamplePeriod = 1 / SamplesPerSecond;          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
382          memcpy(&pData[0], &Manufacturer, 4);          memcpy(&pData[0], &Manufacturer, 4);
383          memcpy(&pData[4], &Product, 4);          memcpy(&pData[4], &Product, 4);
384          memcpy(&pData[8], &SamplePeriod, 4);          memcpy(&pData[8], &SamplePeriod, 4);
# Line 413  namespace { Line 400  namespace {
400          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
401          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
402          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
403            // determine appropriate sample group index (to be stored in chunk)
404            uint16_t iSampleGroup = 0; // no sample group by default
405            File* pFile = static_cast<File*>(pParent);
406            if (pFile->pGroups) {
407                std::list<Group*>::iterator iter = pFile->pGroups->begin();
408                std::list<Group*>::iterator end  = pFile->pGroups->end();
409                // caution: sample groups in .gig files are indexed (1..n) whereas Groups in libgig (0..n-1)
410                for (int i = 1; iter != end; i++, iter++) {
411                    if (*iter == pGroup) {
412                        iSampleGroup = i;
413                        break; // found
414                    }
415                }
416            }
417          // update '3gix' chunk          // update '3gix' chunk
418          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
419          memcpy(&pData[0], &SampleGroup, 2);          memcpy(&pData[0], &iSampleGroup, 2);
420      }      }
421    
422      /// 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 742  namespace { Line 743  namespace {
743       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
744       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
745       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
746         * @param pDimRgn          dimension region with looping information
747       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
748       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
749       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
750       */       */
751      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,
752                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
753          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
754          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
755    
756          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
757    
758          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
759    
760              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
761                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
762    
763                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
764                      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  
765    
766                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
767                              // determine the end position within the loop first,                          do {
768                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
769                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
770                              // backward playback  
771                                if (!pPlaybackState->reverse) { // forward playback
772                              unsigned long swapareastart       = totalreadsamples;                                  do {
773                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
774                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
775                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
776                                        totalreadsamples += readsamples;
777                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
778                                            pPlaybackState->reverse = true;
779                              // read samples for backward playback                                          break;
780                              do {                                      }
781                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
782                                  samplestoreadinloop -= readsamples;                              }
783                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
784    
785                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
786                                    // determine the end position within the loop first,
787                                    // read forward from that 'end' and finally after
788                                    // reading, swap all sample frames so it reflects
789                                    // backward playback
790    
791                                    unsigned long swapareastart       = totalreadsamples;
792                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
793                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
794                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
795    
796                                    SetPos(reverseplaybackend);
797    
798                                    // read samples for backward playback
799                                    do {
800                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
801                                        samplestoreadinloop -= readsamples;
802                                        samplestoread       -= readsamples;
803                                        totalreadsamples    += readsamples;
804                                    } while (samplestoreadinloop && readsamples);
805    
806                                    SetPos(reverseplaybackend); // pretend we really read backwards
807    
808                                    if (reverseplaybackend == loop.LoopStart) {
809                                        pPlaybackState->loop_cycles_left--;
810                                        pPlaybackState->reverse = false;
811                                    }
812    
813                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
814                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
815                              }                              }
816                            } while (samplestoread && readsamples);
817                            break;
818                        }
819    
820                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
821                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
822                          }                          if (!pPlaybackState->reverse) do {
823                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
824                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
825                  }                              samplestoread    -= readsamples;
826                                totalreadsamples += readsamples;
827                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
828                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
829                      if (!pPlaybackState->reverse) do {                                  break;
830                          samplestoloopend  = this->LoopEnd - GetPos();                              }
831                          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);  
832    
833                      if (!samplestoread) break;                          if (!samplestoread) break;
834    
835                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
836                      // determine the end position within the loop first,                          // determine the end position within the loop first,
837                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
838                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
839                      // backward playback                          // backward playback
840    
841                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
842                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
843                      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)
844                                                                                : samplestoread;                                                                                    : samplestoread;
845                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
846    
847                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
848    
849                      // read samples for backward playback                          // read samples for backward playback
850                      do {                          do {
851                          // 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
852                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
853                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
854                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
855                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
856                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
857                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
858                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
859                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
860                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
861                          }                              }
862                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
863    
864                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
865    
866                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
867                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
868                      break;                          break;
869                  }                      }
870    
871                  default: case loop_type_normal: {                      default: case loop_type_normal: {
872                      do {                          do {
873                          // 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
874                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
875                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
876                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
877                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
878                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
879                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
880                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
881                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
882                          }                              }
883                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
884                      break;                          break;
885                        }
886                  }                  }
887              }              }
888          }          }
# Line 904  namespace { Line 912  namespace {
912       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
913       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
914       *       *
915         * For 16 bit samples, the data in the buffer will be int16_t
916         * (using native endianness). For 24 bit, the buffer will
917         * contain three bytes per sample, little-endian.
918         *
919       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
920       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
921       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 914  namespace { Line 926  namespace {
926          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
927          if (!Compressed) {          if (!Compressed) {
928              if (BitDepth == 24) {              if (BitDepth == 24) {
929                  // 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);  
                 }  
930              }              }
931              else { // 16 bit              else { // 16 bit
932                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 964  namespace { Line 956  namespace {
956    
957              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
958              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
959                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
960              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
961    
962              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 1045  namespace { Line 1038  namespace {
1038                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1039                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1040    
1041                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1042                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1043                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1044                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1045                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1046                          }                          }
1047                          else { // Mono                          else { // Mono
1048                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1049                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1050                              pDst += copysamples;                              pDst24 += copysamples * 3;
1051                          }                          }
1052                      }                      }
1053                      else { // 16 bit                      else { // 16 bit
# Line 1183  namespace { Line 1176  namespace {
1176      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1177          Instances++;          Instances++;
1178    
1179            pSample = NULL;
1180    
1181          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1182          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1183    
1184          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1185          if (_3ewa) { // if '3ewa' chunk exists          if (_3ewa) { // if '3ewa' chunk exists
1186              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1187              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1188              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1189              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
# Line 1447  namespace { Line 1442  namespace {
1442                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1443    
1444          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1445            VelocityTable = 0;
1446      }      }
1447    
1448      /**      /**
# Line 1467  namespace { Line 1463  namespace {
1463    
1464          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1465    
1466          const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?          const uint32_t unknown = _3ewa->GetSize(); // unknown, always chunk size ?
1467          memcpy(&pData[0], &unknown, 4);          memcpy(&pData[0], &unknown, 4);
1468    
1469          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1470          memcpy(&pData[4], &lfo3freq, 4);          memcpy(&pData[4], &lfo3freq, 4);
1471    
1472          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1473          memcpy(&pData[4], &eg3attack, 4);          memcpy(&pData[8], &eg3attack, 4);
1474    
1475          // next 2 bytes unknown          // next 2 bytes unknown
1476    
1477          memcpy(&pData[10], &LFO1InternalDepth, 2);          memcpy(&pData[14], &LFO1InternalDepth, 2);
1478    
1479          // next 2 bytes unknown          // next 2 bytes unknown
1480    
1481          memcpy(&pData[14], &LFO3InternalDepth, 2);          memcpy(&pData[18], &LFO3InternalDepth, 2);
1482    
1483          // next 2 bytes unknown          // next 2 bytes unknown
1484    
1485          memcpy(&pData[18], &LFO1ControlDepth, 2);          memcpy(&pData[22], &LFO1ControlDepth, 2);
1486    
1487          // next 2 bytes unknown          // next 2 bytes unknown
1488    
1489          memcpy(&pData[22], &LFO3ControlDepth, 2);          memcpy(&pData[26], &LFO3ControlDepth, 2);
1490    
1491          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1492          memcpy(&pData[24], &eg1attack, 4);          memcpy(&pData[28], &eg1attack, 4);
1493    
1494          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1495          memcpy(&pData[28], &eg1decay1, 4);          memcpy(&pData[32], &eg1decay1, 4);
1496    
1497          // next 2 bytes unknown          // next 2 bytes unknown
1498    
1499          memcpy(&pData[34], &EG1Sustain, 2);          memcpy(&pData[38], &EG1Sustain, 2);
1500    
1501          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1502          memcpy(&pData[36], &eg1release, 4);          memcpy(&pData[40], &eg1release, 4);
1503    
1504          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1505          memcpy(&pData[40], &eg1ctl, 1);          memcpy(&pData[44], &eg1ctl, 1);
1506    
1507          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1508              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert) ? 0x01 : 0x00 |
1509              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1510              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1511              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1512          memcpy(&pData[41], &eg1ctrloptions, 1);          memcpy(&pData[45], &eg1ctrloptions, 1);
1513    
1514          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1515          memcpy(&pData[42], &eg2ctl, 1);          memcpy(&pData[46], &eg2ctl, 1);
1516    
1517          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1518              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert) ? 0x01 : 0x00 |
1519              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1520              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1521              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1522          memcpy(&pData[43], &eg2ctrloptions, 1);          memcpy(&pData[47], &eg2ctrloptions, 1);
1523    
1524          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1525          memcpy(&pData[44], &lfo1freq, 4);          memcpy(&pData[48], &lfo1freq, 4);
1526    
1527          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1528          memcpy(&pData[48], &eg2attack, 4);          memcpy(&pData[52], &eg2attack, 4);
1529    
1530          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1531          memcpy(&pData[52], &eg2decay1, 4);          memcpy(&pData[56], &eg2decay1, 4);
1532    
1533          // next 2 bytes unknown          // next 2 bytes unknown
1534    
1535          memcpy(&pData[58], &EG2Sustain, 2);          memcpy(&pData[62], &EG2Sustain, 2);
1536    
1537          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1538          memcpy(&pData[60], &eg2release, 4);          memcpy(&pData[64], &eg2release, 4);
1539    
1540          // next 2 bytes unknown          // next 2 bytes unknown
1541    
1542          memcpy(&pData[66], &LFO2ControlDepth, 2);          memcpy(&pData[70], &LFO2ControlDepth, 2);
1543    
1544          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1545          memcpy(&pData[68], &lfo2freq, 4);          memcpy(&pData[72], &lfo2freq, 4);
1546    
1547          // next 2 bytes unknown          // next 2 bytes unknown
1548    
1549          memcpy(&pData[72], &LFO2InternalDepth, 2);          memcpy(&pData[78], &LFO2InternalDepth, 2);
1550    
1551          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);          const int32_t eg1decay2 = (int32_t) (EG1InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG1Decay2);
1552          memcpy(&pData[74], &eg1decay2, 4);          memcpy(&pData[80], &eg1decay2, 4);
1553    
1554          // next 2 bytes unknown          // next 2 bytes unknown
1555    
1556          memcpy(&pData[80], &EG1PreAttack, 2);          memcpy(&pData[86], &EG1PreAttack, 2);
1557    
1558          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);          const int32_t eg2decay2 = (int32_t) (EG2InfiniteSustain) ? 0x7fffffff : (int32_t) GIG_EXP_ENCODE(EG2Decay2);
1559          memcpy(&pData[82], &eg2decay2, 4);          memcpy(&pData[88], &eg2decay2, 4);
1560    
1561          // next 2 bytes unknown          // next 2 bytes unknown
1562    
1563          memcpy(&pData[88], &EG2PreAttack, 2);          memcpy(&pData[94], &EG2PreAttack, 2);
1564    
1565          {          {
1566              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");              if (VelocityResponseDepth > 4) throw Exception("VelocityResponseDepth must be between 0 and 4");
# Line 1582  namespace { Line 1578  namespace {
1578                  default:                  default:
1579                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1580              }              }
1581              memcpy(&pData[90], &velocityresponse, 1);              memcpy(&pData[96], &velocityresponse, 1);
1582          }          }
1583    
1584          {          {
# Line 1601  namespace { Line 1597  namespace {
1597                  default:                  default:
1598                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1599              }              }
1600              memcpy(&pData[91], &releasevelocityresponse, 1);              memcpy(&pData[97], &releasevelocityresponse, 1);
1601          }          }
1602    
1603          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);          memcpy(&pData[98], &VelocityResponseCurveScaling, 1);
1604    
1605          memcpy(&pData[93], &AttenuationControllerThreshold, 1);          memcpy(&pData[99], &AttenuationControllerThreshold, 1);
1606    
1607          // next 4 bytes unknown          // next 4 bytes unknown
1608    
1609          memcpy(&pData[98], &SampleStartOffset, 2);          memcpy(&pData[104], &SampleStartOffset, 2);
1610    
1611          // next 2 bytes unknown          // next 2 bytes unknown
1612    
# Line 1629  namespace { Line 1625  namespace {
1625                  default:                  default:
1626                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1627              }              }
1628              memcpy(&pData[102], &pitchTrackDimensionBypass, 1);              memcpy(&pData[108], &pitchTrackDimensionBypass, 1);
1629          }          }
1630    
1631          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit          const uint8_t pan = (Pan >= 0) ? Pan : ((-Pan) + 63); // signed 8 bit -> signed 7 bit
1632          memcpy(&pData[103], &pan, 1);          memcpy(&pData[109], &pan, 1);
1633    
1634          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1635          memcpy(&pData[104], &selfmask, 1);          memcpy(&pData[110], &selfmask, 1);
1636    
1637          // next byte unknown          // next byte unknown
1638    
# Line 1645  namespace { Line 1641  namespace {
1641              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1642              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1643              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1644              memcpy(&pData[106], &lfo3ctrl, 1);              memcpy(&pData[112], &lfo3ctrl, 1);
1645          }          }
1646    
1647          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1648          memcpy(&pData[107], &attenctl, 1);          memcpy(&pData[113], &attenctl, 1);
1649    
1650          {          {
1651              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1652              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1653              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1654              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1655              memcpy(&pData[108], &lfo2ctrl, 1);              memcpy(&pData[114], &lfo2ctrl, 1);
1656          }          }
1657    
1658          {          {
# Line 1665  namespace { Line 1661  namespace {
1661              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1662              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1663                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1664              memcpy(&pData[109], &lfo1ctrl, 1);              memcpy(&pData[115], &lfo1ctrl, 1);
1665          }          }
1666    
1667          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1668                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1669          memcpy(&pData[110], &eg3depth, 1);          memcpy(&pData[116], &eg3depth, 1);
1670    
1671          // next 2 bytes unknown          // next 2 bytes unknown
1672    
1673          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1674          memcpy(&pData[113], &channeloffset, 1);          memcpy(&pData[120], &channeloffset, 1);
1675    
1676          {          {
1677              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1678              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1679              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1680              memcpy(&pData[114], &regoptions, 1);              memcpy(&pData[121], &regoptions, 1);
1681          }          }
1682    
1683          // next 2 bytes unknown          // next 2 bytes unknown
1684    
1685          memcpy(&pData[117], &VelocityUpperLimit, 1);          memcpy(&pData[124], &VelocityUpperLimit, 1);
1686    
1687          // next 3 bytes unknown          // next 3 bytes unknown
1688    
1689          memcpy(&pData[121], &ReleaseTriggerDecay, 1);          memcpy(&pData[128], &ReleaseTriggerDecay, 1);
1690    
1691          // next 2 bytes unknown          // next 2 bytes unknown
1692    
1693          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1694          memcpy(&pData[124], &eg1hold, 1);          memcpy(&pData[131], &eg1hold, 1);
1695    
1696          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1697                                    (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1698          memcpy(&pData[125], &vcfcutoff, 1);          memcpy(&pData[132], &vcfcutoff, 1);
1699    
1700          memcpy(&pData[126], &VCFCutoffController, 1);          memcpy(&pData[133], &VCFCutoffController, 1);
1701    
1702          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1703                                      (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1704          memcpy(&pData[127], &vcfvelscale, 1);          memcpy(&pData[134], &vcfvelscale, 1);
1705    
1706          // next byte unknown          // next byte unknown
1707    
1708          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1709                                       (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
1710          memcpy(&pData[129], &vcfresonance, 1);          memcpy(&pData[136], &vcfresonance, 1);
1711    
1712          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1713                                        (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1714          memcpy(&pData[130], &vcfbreakpoint, 1);          memcpy(&pData[137], &vcfbreakpoint, 1);
1715    
1716          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1717                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
1718          memcpy(&pData[131], &vcfvelocity, 1);          memcpy(&pData[138], &vcfvelocity, 1);
1719    
1720          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1721          memcpy(&pData[132], &vcftype, 1);          memcpy(&pData[139], &vcftype, 1);
1722      }      }
1723    
1724      // 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 1966  namespace { Line 1962  namespace {
1962              delete pVelocityTables;              delete pVelocityTables;
1963              pVelocityTables = NULL;              pVelocityTables = NULL;
1964          }          }
1965            if (VelocityTable) delete[] VelocityTable;
1966      }      }
1967    
1968      /**      /**
# Line 2063  namespace { Line 2060  namespace {
2060  // *  // *
2061    
2062      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2063            pInfo->UseFixedLengthStrings = true;
2064    
2065          // Initialization          // Initialization
2066          Dimensions = 0;          Dimensions = 0;
2067          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 2090  namespace { Line 2089  namespace {
2089                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2090                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2091                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2092                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2093                  }                  }
2094                  else { // active dimension                  else { // active dimension
# Line 2100  namespace { Line 2098  namespace {
2098                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||
2099                                                             dimension == dimension_samplechannel ||                                                             dimension == dimension_samplechannel ||
2100                                                             dimension == dimension_releasetrigger ||                                                             dimension == dimension_releasetrigger ||
2101                                                               dimension == dimension_keyboard ||
2102                                                             dimension == dimension_roundrobin ||                                                             dimension == dimension_roundrobin ||
2103                                                             dimension == dimension_random) ? split_type_bit                                                             dimension == dimension_random) ? split_type_bit
2104                                                                                            : 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  
2105                      pDimensionDefinitions[i].zone_size  =                      pDimensionDefinitions[i].zone_size  =
2106                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones                          (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones
2107                                                                                     : 0;                                                                                     : 0;
# Line 2114  namespace { Line 2112  namespace {
2112                  }                  }
2113                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2114              }              }
2115                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2116    
2117              // 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,
2118              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2119                  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];  
                         UpdateVelocityTable(pDimDef);  
                     }  
                 }  
             }  
2120    
2121              // 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();  
2122              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2123                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2124              else              else
# Line 2142  namespace { Line 2127  namespace {
2127              // load sample references              // load sample references
2128              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2129                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2130                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2131              }              }
2132                GetSample(); // load global region sample reference
2133            }
2134    
2135            // make sure there is at least one dimension region
2136            if (!DimensionRegions) {
2137                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2138                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2139                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2140                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2141                DimensionRegions = 1;
2142          }          }
2143      }      }
2144    
# Line 2161  namespace { Line 2156  namespace {
2156          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
2157    
2158          // update dimension region's chunks          // update dimension region's chunks
2159          for (int i = 0; i < Dimensions; i++)          for (int i = 0; i < DimensionRegions; i++) {
2160              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks();
2161            }
2162    
2163          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
2164          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;          const int iMaxDimensions = (pFile->pVersion && pFile->pVersion->major == 3) ? 8 : 5;
# Line 2177  namespace { Line 2173  namespace {
2173    
2174          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
2175          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2176            memcpy(&pData[0], &DimensionRegions, 4);
2177          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2178              pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2179              pData[i * 8 + 1] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2180              // next 2 bytes unknown              // next 2 bytes unknown
2181              pData[i * 8 + 4] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2182              // next 3 bytes unknown              // next 3 bytes unknown
2183          }          }
2184    
# Line 2190  namespace { Line 2187  namespace {
2187          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
2188              int iWaveIndex = -1;              int iWaveIndex = -1;
2189              if (i < DimensionRegions) {              if (i < DimensionRegions) {
2190                  if (!pFile->pSamples) throw gig::Exception("Could not update gig::Region, there are no samples");                  if (!pFile->pSamples || !pFile->pSamples->size()) throw gig::Exception("Could not update gig::Region, there are no samples");
2191                  std::list<Sample*>::iterator iter = pFile->pSamples->begin();                  File::SampleList::iterator iter = pFile->pSamples->begin();
2192                  std::list<Sample*>::iterator end  = pFile->pSamples->end();                  File::SampleList::iterator end  = pFile->pSamples->end();
2193                  for (int index = 0; iter != end; ++iter, ++index) {                  for (int index = 0; iter != end; ++iter, ++index) {
2194                      if (*iter == pDimensionRegions[i]->pSample) iWaveIndex = index;                      if (*iter == pDimensionRegions[i]->pSample) {
2195                      break;                          iWaveIndex = index;
2196                            break;
2197                        }
2198                  }                  }
2199                  if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");                  if (iWaveIndex < 0) throw gig::Exception("Could not update gig::Region, could not find DimensionRegion's sample");
2200              }              }
# Line 2219  namespace { Line 2218  namespace {
2218          }          }
2219      }      }
2220    
2221      void Region::UpdateVelocityTable(dimension_def_t* pDimDef) {      void Region::UpdateVelocityTable() {
2222          // get dimension's index          // get velocity dimension's index
2223          int iDimensionNr = -1;          int veldim = -1;
2224          for (int i = 0; i < Dimensions; i++) {          for (int i = 0 ; i < Dimensions ; i++) {
2225              if (&pDimensionDefinitions[i] == pDimDef) {              if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2226                  iDimensionNr = i;                  veldim = i;
2227                  break;                  break;
2228              }              }
2229          }          }
2230          if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");          if (veldim == -1) return;
2231    
2232            int step = 1;
2233            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2234            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2235            int end = step * pDimensionDefinitions[veldim].zones;
2236    
2237            // loop through all dimension regions for all dimensions except the velocity dimension
2238            int dim[8] = { 0 };
2239            for (int i = 0 ; i < DimensionRegions ; i++) {
2240    
2241                if (pDimensionRegions[i]->VelocityUpperLimit) {
2242                    // create the velocity table
2243                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2244                    if (!table) {
2245                        table = new uint8_t[128];
2246                        pDimensionRegions[i]->VelocityTable = table;
2247                    }
2248                    int tableidx = 0;
2249                    int velocityZone = 0;
2250                    for (int k = i ; k < end ; k += step) {
2251                        DimensionRegion *d = pDimensionRegions[k];
2252                        for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2253                        velocityZone++;
2254                    }
2255                } else {
2256                    if (pDimensionRegions[i]->VelocityTable) {
2257                        delete[] pDimensionRegions[i]->VelocityTable;
2258                        pDimensionRegions[i]->VelocityTable = 0;
2259                    }
2260                }
2261    
2262          uint8_t bits[8] = { 0 };              int j;
2263          int previousUpperLimit = -1;              int shift = 0;
2264          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {              for (j = 0 ; j < Dimensions ; j++) {
2265              bits[iDimensionNr] = velocityZone;                  if (j == veldim) i += skipveldim; // skip velocity dimension
2266              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);                  else {
2267                        dim[j]++;
2268              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;                      if (dim[j] < pDimensionDefinitions[j].zones) break;
2269              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;                      else {
2270              previousUpperLimit = pDimDef->ranges[velocityZone].high;                          // skip unused dimension regions
2271              // fill velocity table                          dim[j] = 0;
2272              for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {                          i += ((1 << pDimensionDefinitions[j].bits) -
2273                  VelocityTable[i] = velocityZone;                                pDimensionDefinitions[j].zones) << shift;
2274                        }
2275                    }
2276                    shift += pDimensionDefinitions[j].bits;
2277              }              }
2278                if (j == Dimensions) break;
2279          }          }
2280      }      }
2281    
# Line 2297  namespace { Line 2330  namespace {
2330          // if this is a layer dimension, update 'Layers' attribute          // if this is a layer dimension, update 'Layers' attribute
2331          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2332    
2333          // if this is velocity dimension and got custom defined ranges, update velocity table          UpdateVelocityTable();
         if (pDimDef->dimension  == dimension_velocity &&  
             pDimDef->split_type == split_type_customvelocity) {  
             UpdateVelocityTable(pDimDef);  
         }  
2334      }      }
2335    
2336      /** @brief Delete an existing dimension.      /** @brief Delete an existing dimension.
# Line 2371  namespace { Line 2400  namespace {
2400          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2401          pDimensionDefinitions[Dimensions - 1].bits      = 0;          pDimensionDefinitions[Dimensions - 1].bits      = 0;
2402          pDimensionDefinitions[Dimensions - 1].zones     = 0;          pDimensionDefinitions[Dimensions - 1].zones     = 0;
         if (pDimensionDefinitions[Dimensions - 1].ranges) {  
             delete[] pDimensionDefinitions[Dimensions - 1].ranges;  
             pDimensionDefinitions[Dimensions - 1].ranges = NULL;  
         }  
2403    
2404          Dimensions--;          Dimensions--;
2405    
# Line 2383  namespace { Line 2408  namespace {
2408      }      }
2409    
2410      Region::~Region() {      Region::~Region() {
         for (uint i = 0; i < Dimensions; i++) {  
             if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;  
         }  
2411          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2412              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2413          }          }
# Line 2410  namespace { Line 2432  namespace {
2432       * @see             Dimensions       * @see             Dimensions
2433       */       */
2434      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2435          uint8_t bits[8] = { 0 };          uint8_t bits;
2436            int veldim = -1;
2437            int velbitpos;
2438            int bitpos = 0;
2439            int dimregidx = 0;
2440          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2441              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2442              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2443                  case split_type_normal:                  veldim = i;
2444                      bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size);                  velbitpos = bitpos;
2445                      break;              } else {
2446                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2447                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2448                      break;                          bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2449                  case split_type_bit: // the value is already the sought dimension bit number                          break;
2450                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                      case split_type_bit: // the value is already the sought dimension bit number
2451                      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;
2452                      break;                          bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2453                            break;
2454                    }
2455                    dimregidx |= bits << bitpos;
2456              }              }
2457                bitpos += pDimensionDefinitions[i].bits;
2458          }          }
2459          return GetDimensionRegionByBit(bits);          DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2460            if (veldim != -1) {
2461                // (dimreg is now the dimension region for the lowest velocity)
2462                if (dimreg->VelocityUpperLimit) // custom defined zone ranges
2463                    bits = dimreg->VelocityTable[DimValues[veldim]];
2464                else // normal split type
2465                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2466    
2467                dimregidx |= bits << velbitpos;
2468                dimreg = pDimensionRegions[dimregidx];
2469            }
2470            return dimreg;
2471      }      }
2472    
2473      /**      /**
# Line 2466  namespace { Line 2507  namespace {
2507      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2508          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2509          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2510            if (!file->pWavePoolTable) return NULL;
2511          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2512          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2513          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
2514          while (sample) {          while (sample) {
2515              if (sample->ulWavePoolOffset == soughtoffset &&              if (sample->ulWavePoolOffset == soughtoffset &&
2516                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2517              sample = file->GetNextSample();              sample = file->GetNextSample();
2518          }          }
2519          return NULL;          return NULL;
# Line 2483  namespace { Line 2525  namespace {
2525  // *  // *
2526    
2527      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) {
2528            pInfo->UseFixedLengthStrings = true;
2529    
2530          // Initialization          // Initialization
2531          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2532    
2533          // Loading          // Loading
2534          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2503  namespace { Line 2546  namespace {
2546              }              }
2547          }          }
2548    
2549          pRegions = new Region*[Regions];          if (!pRegions) pRegions = new RegionList;
2550          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2551          if (lrgn) {          if (lrgn) {
             for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;  
2552              RIFF::List* rgn = lrgn->GetFirstSubList();              RIFF::List* rgn = lrgn->GetFirstSubList();
             unsigned int iRegion = 0;  
2553              while (rgn) {              while (rgn) {
2554                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2555                      __notify_progress(pProgress, (float) iRegion / (float) Regions);                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2556                      pRegions[iRegion] = new Region(this, rgn);                      pRegions->push_back(new Region(this, rgn));
                     iRegion++;  
2557                  }                  }
2558                  rgn = lrgn->GetNextSubList();                  rgn = lrgn->GetNextSubList();
2559              }              }
# Line 2525  namespace { Line 2565  namespace {
2565      }      }
2566    
2567      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
2568          for (uint iReg = 0; iReg < Regions; iReg++) {          RegionList::iterator iter = pRegions->begin();
2569              for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {          RegionList::iterator end  = pRegions->end();
2570                  RegionKeyTable[iKey] = pRegions[iReg];          for (; iter != end; ++iter) {
2571                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2572                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2573                    RegionKeyTable[iKey] = pRegion;
2574              }              }
2575          }          }
2576      }      }
2577    
2578      Instrument::~Instrument() {      Instrument::~Instrument() {
         for (uint i = 0; i < Regions; i++) {  
             if (pRegions) {  
                 if (pRegions[i]) delete (pRegions[i]);  
             }  
         }  
         if (pRegions) delete[] pRegions;  
2579      }      }
2580    
2581      /**      /**
# Line 2555  namespace { Line 2592  namespace {
2592          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks();
2593    
2594          // update Regions' chunks          // update Regions' chunks
2595          for (int i = 0; i < Regions; i++)          {
2596              pRegions[i]->UpdateChunks();              RegionList::iterator iter = pRegions->begin();
2597                RegionList::iterator end  = pRegions->end();
2598                for (; iter != end; ++iter)
2599                    (*iter)->UpdateChunks();
2600            }
2601    
2602          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
2603          RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
# Line 2584  namespace { Line 2625  namespace {
2625       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2626       */       */
2627      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2628          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2629          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2630    
2631          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2632              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2633                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 2601  namespace { Line 2643  namespace {
2643       * @see      GetNextRegion()       * @see      GetNextRegion()
2644       */       */
2645      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2646          if (!Regions) return NULL;          if (!pRegions) return NULL;
2647          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2648          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2649      }      }
2650    
2651      /**      /**
# Line 2615  namespace { Line 2657  namespace {
2657       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2658       */       */
2659      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2660          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2661          return pRegions[RegionIndex++];          RegionsIterator++;
2662            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2663      }      }
2664    
2665      Region* Instrument::AddRegion() {      Region* Instrument::AddRegion() {
# Line 2625  namespace { Line 2668  namespace {
2668          if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);          if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2669          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2670          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
2671          // resize 'pRegions' array (increase by one)          pRegions->push_back(pNewRegion);
2672          Region** pNewRegions = new Region*[Regions + 1];          Regions = pRegions->size();
         memcpy(pNewRegions, pRegions, Regions * sizeof(Region*));  
         // add new Region object  
         pNewRegions[Regions] = pNewRegion;  
         // replace old 'pRegions' array by the new increased array  
         if (pRegions) delete[] pRegions;  
         pRegions = pNewRegions;  
         Regions++;  
2673          // update Region key table for fast lookup          // update Region key table for fast lookup
2674          UpdateRegionKeyTable();          UpdateRegionKeyTable();
2675          // done          // done
# Line 2642  namespace { Line 2678  namespace {
2678    
2679      void Instrument::DeleteRegion(Region* pRegion) {      void Instrument::DeleteRegion(Region* pRegion) {
2680          if (!pRegions) return;          if (!pRegions) return;
2681          int iOffset = 0;          DLS::Instrument::DeleteRegion((DLS::Region*) pRegion);
         // resize 'pRegions' array (decrease by one)  
         Region** pNewRegions = new Region*[Regions - 1];  
         for (int i = 0; i < Regions; i++) {  
             if (pRegions[i] == pRegion) { // found Region to delete  
                 iOffset = 1;  
                 delete pRegion;  
             }  
             if (i < Regions - 1) pNewRegions[i] = pRegions[i + iOffset];  
         }  
         if (!iOffset) throw gig::Exception("There is no such gig::Region to delete");  
         // replace old 'pRegions' array by the new decreased array  
         if (pRegions) delete[] pRegions;  
         pRegions = pNewRegions;  
         Regions--;  
2682          // update Region key table for fast lookup          // update Region key table for fast lookup
2683          UpdateRegionKeyTable();          UpdateRegionKeyTable();
2684      }      }
2685    
2686    
2687    
2688    // *************** Group ***************
2689    // *
2690    
2691        /** @brief Constructor.
2692         *
2693         * @param file   - pointer to the RIFF::File object of this .gig file
2694         * @param ck3gnm - pointer to 3gnm chunk associated with this group
2695         */
2696        Group::Group(RIFF::File* file, RIFF::Chunk* ck3gnm) {
2697            pFile      = file;
2698            pNameChunk = ck3gnm;
2699            ::LoadString(pNameChunk, Name);
2700        }
2701    
2702        Group::~Group() {
2703        }
2704    
2705        /** @brief Update chunks with current group settings.
2706         *
2707         * Apply current Group field values to the respective. You have to call
2708         * File::Save() to make changes persistent.
2709         */
2710        void Group::UpdateChunks() {
2711            // make sure <3gri> and <3gnl> list chunks exist
2712            RIFF::List* _3gri = pFile->GetSubList(LIST_TYPE_3GRI);
2713            if (!_3gri) _3gri = pFile->AddSubList(LIST_TYPE_3GRI);
2714            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
2715            if (!_3gnl) _3gnl = pFile->AddSubList(LIST_TYPE_3GNL);
2716            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
2717            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
2718        }
2719    
2720    
2721    
2722  // *************** File ***************  // *************** File ***************
2723  // *  // *
2724    
2725      File::File() : DLS::File() {      File::File() : DLS::File() {
2726          pSamples     = NULL;          pGroups = NULL;
2727          pInstruments = NULL;          pInfo->UseFixedLengthStrings = true;
2728      }      }
2729    
2730      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2731          pSamples     = NULL;          pGroups = NULL;
2732          pInstruments = NULL;          pInfo->UseFixedLengthStrings = true;
2733      }      }
2734    
2735      File::~File() {      File::~File() {
2736          // free samples          if (pGroups) {
2737          if (pSamples) {              std::list<Group*>::iterator iter = pGroups->begin();
2738              SamplesIterator = pSamples->begin();              std::list<Group*>::iterator end  = pGroups->end();
2739              while (SamplesIterator != pSamples->end() ) {              while (iter != end) {
2740                  delete (*SamplesIterator);                  delete *iter;
2741                  SamplesIterator++;                  ++iter;
2742              }              }
2743              pSamples->clear();              delete pGroups;
2744              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;  
2745      }      }
2746    
2747      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2728  namespace { Line 2769  namespace {
2769         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
2770         RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);         RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2771         // create new Sample object and its respective 'wave' list chunk         // create new Sample object and its respective 'wave' list chunk
        if (!pSamples) pSamples = new SampleList;  
2772         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2773         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);         Sample* pSample = new Sample(this, wave, 0 /*arbitrary value, we update offsets when we save*/);
2774         pSamples->push_back(pSample);         pSamples->push_back(pSample);
# Line 2744  namespace { Line 2784  namespace {
2784       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
2785       */       */
2786      void File::DeleteSample(Sample* pSample) {      void File::DeleteSample(Sample* pSample) {
2787          if (!pSamples) throw gig::Exception("Could not delete sample as there are no samples");          if (!pSamples || !pSamples->size()) throw gig::Exception("Could not delete sample as there are no samples");
2788          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2789          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");          if (iter == pSamples->end()) throw gig::Exception("Could not delete sample, could not find given sample");
2790          pSamples->erase(iter);          pSamples->erase(iter);
2791          delete pSample;          delete pSample;
2792      }      }
2793    
2794        void File::LoadSamples() {
2795            LoadSamples(NULL);
2796        }
2797    
2798      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
2799            if (!pSamples) pSamples = new SampleList;
2800    
2801          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
2802    
2803          // just for progress calculation          // just for progress calculation
# Line 2779  namespace { Line 2825  namespace {
2825                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2826                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
2827    
                         if (!pSamples) pSamples = new SampleList;  
2828                          unsigned long waveFileOffset = wave->GetFilePos();                          unsigned long waveFileOffset = wave->GetFilePos();
2829                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
2830    
# Line 2796  namespace { Line 2841  namespace {
2841                  name.replace(nameLen, 5, suffix);                  name.replace(nameLen, 5, suffix);
2842                  file = new RIFF::File(name);                  file = new RIFF::File(name);
2843                  ExtensionFiles.push_back(file);                  ExtensionFiles.push_back(file);
2844              }              } else break;
             else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
2845          }          }
2846    
2847          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
# Line 2807  namespace { Line 2851  namespace {
2851          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
2852          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2853          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2854          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2855      }      }
2856    
2857      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
2858          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2859          InstrumentsIterator++;          InstrumentsIterator++;
2860          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
2861      }      }
2862    
2863      /**      /**
# Line 2846  namespace { Line 2890  namespace {
2890          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
2891          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
2892          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
2893              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
2894              InstrumentsIterator++;              InstrumentsIterator++;
2895          }          }
2896          return NULL;          return NULL;
# Line 2862  namespace { Line 2906  namespace {
2906      Instrument* File::AddInstrument() {      Instrument* File::AddInstrument() {
2907         if (!pInstruments) LoadInstruments();         if (!pInstruments) LoadInstruments();
2908         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
        if (!pInstruments) pInstruments = new InstrumentList;  
2909         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2910         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
2911         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
# Line 2880  namespace { Line 2923  namespace {
2923       */       */
2924      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
2925          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");          if (!pInstruments) throw gig::Exception("Could not delete instrument as there are no instruments");
2926          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
2927          if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");          if (iter == pInstruments->end()) throw gig::Exception("Could not delete instrument, could not find given instrument");
2928          pInstruments->erase(iter);          pInstruments->erase(iter);
2929          delete pInstrument;          delete pInstrument;
2930      }      }
2931    
2932        void File::LoadInstruments() {
2933            LoadInstruments(NULL);
2934        }
2935    
2936      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
2937            if (!pInstruments) pInstruments = new InstrumentList;
2938          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
2939          if (lstInstruments) {          if (lstInstruments) {
2940              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 2901  namespace { Line 2949  namespace {
2949                      progress_t subprogress;                      progress_t subprogress;
2950                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
2951    
                     if (!pInstruments) pInstruments = new InstrumentList;  
2952                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
2953    
2954                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 2910  namespace { Line 2957  namespace {
2957              }              }
2958              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
2959          }          }
2960          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
2961    
2962        Group* File::GetFirstGroup() {
2963            if (!pGroups) LoadGroups();
2964            if (!pGroups) return NULL;
2965            GroupsIterator = pGroups->begin();
2966            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
2967        }
2968    
2969        Group* File::GetNextGroup() {
2970            if (!pGroups) return NULL;
2971            ++GroupsIterator;
2972            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
2973        }
2974    
2975        /**
2976         * Returns the group with the given index.
2977         *
2978         * @param index - number of the sought group (0..n)
2979         * @returns sought group or NULL if there's no such group
2980         */
2981        Group* File::GetGroup(uint index) {
2982            if (!pGroups) LoadGroups();
2983            if (!pGroups) return NULL;
2984            GroupsIterator = pGroups->begin();
2985            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
2986                if (i == index) return *GroupsIterator;
2987                ++GroupsIterator;
2988            }
2989            return NULL;
2990        }
2991    
2992        Group* File::AddGroup() {
2993            if (!pGroups) LoadGroups();
2994            if (!pGroups) pGroups = new std::list<Group*>;
2995            __ensureMandatoryChunksExist();
2996            Group* pGroup = new Group(pRIFF, NULL);
2997            pGroups->push_back(pGroup);
2998            return pGroup;
2999        }
3000    
3001        void File::DeleteGroup(Group* pGroup) {
3002            if (!pGroups) throw gig::Exception("Could not delete group as there are no groups");
3003            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3004            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3005            pGroups->erase(iter);
3006            delete pGroup;
3007        }
3008    
3009        void File::LoadGroups() {
3010            if (!pGroups) pGroups = new std::list<Group*>;
3011            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
3012            if (!lst3gri) return;
3013            RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
3014            if (!lst3gnl) return;
3015            {
3016                RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3017                while (ck) {
3018                    if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3019                        pGroups->push_back(new Group(pRIFF, ck));
3020                    }
3021                    ck = lst3gnl->GetNextSubChunk();
3022                }
3023            }
3024      }      }
3025    
3026    

Legend:
Removed from v.809  
changed lines
  Added in v.929

  ViewVC Help
Powered by ViewVC