/[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 1180 by persson, Sat May 12 12:39:25 2007 UTC
# Line 1  Line 1 
1  /***************************************************************************  /***************************************************************************
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file loader library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2005 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2007 by Christian Schoenebeck                      *
6   *                              <cuse@users.sourceforge.net>               *   *                              <cuse@users.sourceforge.net>               *
7   *                                                                         *   *                                                                         *
8   *   This library is free software; you can redistribute it and/or modify  *   *   This library is free software; you can redistribute it and/or modify  *
# Line 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 270  namespace { Line 254  namespace {
254  }  }
255    
256    
257    
258    // *************** Other Internal functions  ***************
259    // *
260    
261        static split_type_t __resolveSplitType(dimension_t dimension) {
262            return (
263                dimension == dimension_layer ||
264                dimension == dimension_samplechannel ||
265                dimension == dimension_releasetrigger ||
266                dimension == dimension_keyboard ||
267                dimension == dimension_roundrobin ||
268                dimension == dimension_random ||
269                dimension == dimension_smartmidi ||
270                dimension == dimension_roundrobinkeyboard
271            ) ? split_type_bit : split_type_normal;
272        }
273    
274        static int __resolveZoneSize(dimension_def_t& dimension_definition) {
275            return (dimension_definition.split_type == split_type_normal)
276            ? int(128.0 / dimension_definition.zones) : 0;
277        }
278    
279    
280    
281  // *************** Sample ***************  // *************** Sample ***************
282  // *  // *
283    
# Line 295  namespace { Line 303  namespace {
303       *                         is located, 0 otherwise       *                         is located, 0 otherwise
304       */       */
305      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
306            static const DLS::Info::FixedStringLength fixedStringLengths[] = {
307                { CHUNK_ID_INAM, 64 },
308                { 0, 0 }
309            };
310            pInfo->FixedStringLengths = fixedStringLengths;
311          Instances++;          Instances++;
312          FileNo = fileNo;          FileNo = fileNo;
313    
314          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
315          if (pCk3gix) {          if (pCk3gix) {
316              SampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
317                pGroup = pFile->GetGroup(iSampleGroup);
318          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
319              // use default value(s)              // by default assigned to that mandatory "Default Group"
320              SampleGroup = 0;              pGroup = pFile->GetGroup(0);
321          }          }
322    
323          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 327  namespace { Line 341  namespace {
341              // use default values              // use default values
342              Manufacturer  = 0;              Manufacturer  = 0;
343              Product       = 0;              Product       = 0;
344              SamplePeriod  = 1 / SamplesPerSecond;              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
345              MIDIUnityNote = 64;              MIDIUnityNote = 64;
346              FineTune      = 0;              FineTune      = 0;
347              SMPTEOffset   = 0;              SMPTEOffset   = 0;
# Line 368  namespace { Line 382  namespace {
382          }          }
383          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
384    
385          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
386      }      }
387    
388      /**      /**
# Line 378  namespace { Line 392  namespace {
392       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
393       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
394       *       *
395       * @throws DLS::Exception if FormatTag != WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
396       *                        was provided yet       *                        was provided yet
397       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
398       */       */
# Line 391  namespace { Line 405  namespace {
405          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
406          // update 'smpl' chunk          // update 'smpl' chunk
407          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
408          SamplePeriod = 1 / SamplesPerSecond;          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
409          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
410          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
411          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
412          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
413          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
414          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
415          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
416          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
417    
418          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
419    
420          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
421          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
422          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
423          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
424          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
425          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
426    
427          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
428          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
429          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
430            // determine appropriate sample group index (to be stored in chunk)
431            uint16_t iSampleGroup = 0; // 0 refers to default sample group
432            File* pFile = static_cast<File*>(pParent);
433            if (pFile->pGroups) {
434                std::list<Group*>::iterator iter = pFile->pGroups->begin();
435                std::list<Group*>::iterator end  = pFile->pGroups->end();
436                for (int i = 0; iter != end; i++, iter++) {
437                    if (*iter == pGroup) {
438                        iSampleGroup = i;
439                        break; // found
440                    }
441                }
442            }
443          // update '3gix' chunk          // update '3gix' chunk
444          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
445          memcpy(&pData[0], &SampleGroup, 2);          store16(&pData[0], iSampleGroup);
446      }      }
447    
448      /// 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 636  namespace { Line 663  namespace {
663       * enlarged samples before calling File::Save() as this might exceed the       * enlarged samples before calling File::Save() as this might exceed the
664       * current sample's boundary!       * current sample's boundary!
665       *       *
666       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
667       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
668       * other formats will fail!       * other formats will fail!
669       *       *
670       * @param iNewSize - new sample wave data size in sample points (must be       * @param iNewSize - new sample wave data size in sample points (must be
671       *                   greater than zero)       *                   greater than zero)
672       * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
673       *                         or if \a iNewSize is less than 1       *                         or if \a iNewSize is less than 1
674       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
675       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
# Line 742  namespace { Line 769  namespace {
769       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
770       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
771       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
772         * @param pDimRgn          dimension region with looping information
773       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
774       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
775       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
776       */       */
777      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,
778                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
779          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
780          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
781    
782          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
783    
784          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
785    
786              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
787                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
788    
789                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
790                      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  
791    
792                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
793                              // determine the end position within the loop first,                          do {
794                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
795                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
796                              // backward playback  
797                                if (!pPlaybackState->reverse) { // forward playback
798                              unsigned long swapareastart       = totalreadsamples;                                  do {
799                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
800                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
801                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
802                                        totalreadsamples += readsamples;
803                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
804                                            pPlaybackState->reverse = true;
805                              // read samples for backward playback                                          break;
806                              do {                                      }
807                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
808                                  samplestoreadinloop -= readsamples;                              }
809                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
810    
811                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
812                                    // determine the end position within the loop first,
813                                    // read forward from that 'end' and finally after
814                                    // reading, swap all sample frames so it reflects
815                                    // backward playback
816    
817                                    unsigned long swapareastart       = totalreadsamples;
818                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
819                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
820                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
821    
822                                    SetPos(reverseplaybackend);
823    
824                                    // read samples for backward playback
825                                    do {
826                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
827                                        samplestoreadinloop -= readsamples;
828                                        samplestoread       -= readsamples;
829                                        totalreadsamples    += readsamples;
830                                    } while (samplestoreadinloop && readsamples);
831    
832                                    SetPos(reverseplaybackend); // pretend we really read backwards
833    
834                                    if (reverseplaybackend == loop.LoopStart) {
835                                        pPlaybackState->loop_cycles_left--;
836                                        pPlaybackState->reverse = false;
837                                    }
838    
839                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
840                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
841                              }                              }
842                            } while (samplestoread && readsamples);
843                            break;
844                        }
845    
846                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
847                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
848                          }                          if (!pPlaybackState->reverse) do {
849                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
850                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
851                  }                              samplestoread    -= readsamples;
852                                totalreadsamples += readsamples;
853                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
854                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
855                      if (!pPlaybackState->reverse) do {                                  break;
856                          samplestoloopend  = this->LoopEnd - GetPos();                              }
857                          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);  
858    
859                      if (!samplestoread) break;                          if (!samplestoread) break;
860    
861                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
862                      // determine the end position within the loop first,                          // determine the end position within the loop first,
863                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
864                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
865                      // backward playback                          // backward playback
866    
867                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
868                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
869                      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)
870                                                                                : samplestoread;                                                                                    : samplestoread;
871                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
872    
873                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
874    
875                      // read samples for backward playback                          // read samples for backward playback
876                      do {                          do {
877                          // 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
878                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
879                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
880                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
881                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
882                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
883                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
884                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
885                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
886                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
887                          }                              }
888                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
889    
890                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
891    
892                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
893                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
894                      break;                          break;
895                  }                      }
896    
897                  default: case loop_type_normal: {                      default: case loop_type_normal: {
898                      do {                          do {
899                          // 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
900                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
901                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
902                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
903                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
904                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
905                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
906                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
907                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
908                          }                              }
909                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
910                      break;                          break;
911                        }
912                  }                  }
913              }              }
914          }          }
# Line 904  namespace { Line 938  namespace {
938       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
939       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
940       *       *
941         * For 16 bit samples, the data in the buffer will be int16_t
942         * (using native endianness). For 24 bit, the buffer will
943         * contain three bytes per sample, little-endian.
944         *
945       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
946       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
947       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 914  namespace { Line 952  namespace {
952          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
953          if (!Compressed) {          if (!Compressed) {
954              if (BitDepth == 24) {              if (BitDepth == 24) {
955                  // 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);  
                 }  
956              }              }
957              else { // 16 bit              else { // 16 bit
958                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 964  namespace { Line 982  namespace {
982    
983              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
984              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
985                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
986              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
987    
988              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 1045  namespace { Line 1064  namespace {
1064                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1065                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1066    
1067                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1068                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1069                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1070                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1071                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1072                          }                          }
1073                          else { // Mono                          else { // Mono
1074                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1075                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1076                              pDst += copysamples;                              pDst24 += copysamples * 3;
1077                          }                          }
1078                      }                      }
1079                      else { // 16 bit                      else { // 16 bit
# Line 1161  namespace { Line 1180  namespace {
1180          }          }
1181      }      }
1182    
1183        /**
1184         * Returns pointer to the Group this Sample belongs to. In the .gig
1185         * format a sample always belongs to one group. If it wasn't explicitly
1186         * assigned to a certain group, it will be automatically assigned to a
1187         * default group.
1188         *
1189         * @returns Sample's Group (never NULL)
1190         */
1191        Group* Sample::GetGroup() const {
1192            return pGroup;
1193        }
1194    
1195      Sample::~Sample() {      Sample::~Sample() {
1196          Instances--;          Instances--;
1197          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1183  namespace { Line 1214  namespace {
1214      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
1215          Instances++;          Instances++;
1216    
1217            pSample = NULL;
1218    
1219          memcpy(&Crossfade, &SamplerOptions, 4);          memcpy(&Crossfade, &SamplerOptions, 4);
1220          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;          if (!pVelocityTables) pVelocityTables = new VelocityTableMap;
1221    
1222          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1223          if (_3ewa) { // if '3ewa' chunk exists          if (_3ewa) { // if '3ewa' chunk exists
1224              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1225              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1226              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1227              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
# Line 1333  namespace { Line 1366  namespace {
1366                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1367                      VCFType = vcf_type_lowpassturbo;                      VCFType = vcf_type_lowpassturbo;
1368              }              }
1369                if (_3ewa->RemainingBytes() >= 8) {
1370                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1371                } else {
1372                    memset(DimensionUpperLimits, 0, 8);
1373                }
1374          } else { // '3ewa' chunk does not exist yet          } else { // '3ewa' chunk does not exist yet
1375              // use default values              // use default values
1376              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1413  namespace { Line 1451  namespace {
1451              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1452              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1453              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1454                memset(DimensionUpperLimits, 0, 8);
1455          }          }
1456    
1457          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
# Line 1447  namespace { Line 1486  namespace {
1486                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1487    
1488          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1489            VelocityTable = 0;
1490      }      }
1491    
1492      /**      /**
# Line 1467  namespace { Line 1507  namespace {
1507    
1508          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1509    
1510          const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?          const uint32_t chunksize = _3ewa->GetSize();
1511          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1512    
1513          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1514          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1515    
1516          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1517          memcpy(&pData[4], &eg3attack, 4);          store32(&pData[8], eg3attack);
1518    
1519          // next 2 bytes unknown          // next 2 bytes unknown
1520    
1521          memcpy(&pData[10], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1522    
1523          // next 2 bytes unknown          // next 2 bytes unknown
1524    
1525          memcpy(&pData[14], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1526    
1527          // next 2 bytes unknown          // next 2 bytes unknown
1528    
1529          memcpy(&pData[18], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1530    
1531          // next 2 bytes unknown          // next 2 bytes unknown
1532    
1533          memcpy(&pData[22], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1534    
1535          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1536          memcpy(&pData[24], &eg1attack, 4);          store32(&pData[28], eg1attack);
1537    
1538          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1539          memcpy(&pData[28], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1540    
1541          // next 2 bytes unknown          // next 2 bytes unknown
1542    
1543          memcpy(&pData[34], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1544    
1545          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1546          memcpy(&pData[36], &eg1release, 4);          store32(&pData[40], eg1release);
1547    
1548          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1549          memcpy(&pData[40], &eg1ctl, 1);          pData[44] = eg1ctl;
1550    
1551          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1552              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert) ? 0x01 : 0x00 |
1553              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1554              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1555              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1556          memcpy(&pData[41], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1557    
1558          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1559          memcpy(&pData[42], &eg2ctl, 1);          pData[46] = eg2ctl;
1560    
1561          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1562              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert) ? 0x01 : 0x00 |
1563              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1564              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1565              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1566          memcpy(&pData[43], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1567    
1568          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1569          memcpy(&pData[44], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1570    
1571          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1572          memcpy(&pData[48], &eg2attack, 4);          store32(&pData[52], eg2attack);
1573    
1574          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1575          memcpy(&pData[52], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1576    
1577          // next 2 bytes unknown          // next 2 bytes unknown
1578    
1579          memcpy(&pData[58], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1580    
1581          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1582          memcpy(&pData[60], &eg2release, 4);          store32(&pData[64], eg2release);
1583    
1584          // next 2 bytes unknown          // next 2 bytes unknown
1585    
1586          memcpy(&pData[66], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1587    
1588          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1589          memcpy(&pData[68], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1590    
1591          // next 2 bytes unknown          // next 2 bytes unknown
1592    
1593          memcpy(&pData[72], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1594    
1595          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);
1596          memcpy(&pData[74], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1597    
1598          // next 2 bytes unknown          // next 2 bytes unknown
1599    
1600          memcpy(&pData[80], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1601    
1602          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);
1603          memcpy(&pData[82], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1604    
1605          // next 2 bytes unknown          // next 2 bytes unknown
1606    
1607          memcpy(&pData[88], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1608    
1609          {          {
1610              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 1622  namespace {
1622                  default:                  default:
1623                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1624              }              }
1625              memcpy(&pData[90], &velocityresponse, 1);              pData[96] = velocityresponse;
1626          }          }
1627    
1628          {          {
# Line 1601  namespace { Line 1641  namespace {
1641                  default:                  default:
1642                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1643              }              }
1644              memcpy(&pData[91], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1645          }          }
1646    
1647          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1648    
1649          memcpy(&pData[93], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1650    
1651          // next 4 bytes unknown          // next 4 bytes unknown
1652    
1653          memcpy(&pData[98], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1654    
1655          // next 2 bytes unknown          // next 2 bytes unknown
1656    
# Line 1629  namespace { Line 1669  namespace {
1669                  default:                  default:
1670                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1671              }              }
1672              memcpy(&pData[102], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1673          }          }
1674    
1675          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
1676          memcpy(&pData[103], &pan, 1);          pData[109] = pan;
1677    
1678          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1679          memcpy(&pData[104], &selfmask, 1);          pData[110] = selfmask;
1680    
1681          // next byte unknown          // next byte unknown
1682    
# Line 1645  namespace { Line 1685  namespace {
1685              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1686              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1687              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1688              memcpy(&pData[106], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1689          }          }
1690    
1691          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1692          memcpy(&pData[107], &attenctl, 1);          pData[113] = attenctl;
1693    
1694          {          {
1695              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1696              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1697              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1698              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1699              memcpy(&pData[108], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1700          }          }
1701    
1702          {          {
# Line 1665  namespace { Line 1705  namespace {
1705              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1706              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1707                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1708              memcpy(&pData[109], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1709          }          }
1710    
1711          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1712                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1713          memcpy(&pData[110], &eg3depth, 1);          pData[116] = eg3depth;
1714    
1715          // next 2 bytes unknown          // next 2 bytes unknown
1716    
1717          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1718          memcpy(&pData[113], &channeloffset, 1);          pData[120] = channeloffset;
1719    
1720          {          {
1721              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1722              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1723              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1724              memcpy(&pData[114], &regoptions, 1);              pData[121] = regoptions;
1725          }          }
1726    
1727          // next 2 bytes unknown          // next 2 bytes unknown
1728    
1729          memcpy(&pData[117], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
1730    
1731          // next 3 bytes unknown          // next 3 bytes unknown
1732    
1733          memcpy(&pData[121], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
1734    
1735          // next 2 bytes unknown          // next 2 bytes unknown
1736    
1737          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1738          memcpy(&pData[124], &eg1hold, 1);          pData[131] = eg1hold;
1739    
1740          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1741                                    (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1742          memcpy(&pData[125], &vcfcutoff, 1);          pData[132] = vcfcutoff;
1743    
1744          memcpy(&pData[126], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
1745    
1746          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1747                                      (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1748          memcpy(&pData[127], &vcfvelscale, 1);          pData[134] = vcfvelscale;
1749    
1750          // next byte unknown          // next byte unknown
1751    
1752          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1753                                       (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
1754          memcpy(&pData[129], &vcfresonance, 1);          pData[136] = vcfresonance;
1755    
1756          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1757                                        (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1758          memcpy(&pData[130], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
1759    
1760          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1761                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
1762          memcpy(&pData[131], &vcfvelocity, 1);          pData[138] = vcfvelocity;
1763    
1764          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1765          memcpy(&pData[132], &vcftype, 1);          pData[139] = vcftype;
1766    
1767            if (chunksize >= 148) {
1768                memcpy(&pData[140], DimensionUpperLimits, 8);
1769            }
1770      }      }
1771    
1772      // 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 2010  namespace {
2010              delete pVelocityTables;              delete pVelocityTables;
2011              pVelocityTables = NULL;              pVelocityTables = NULL;
2012          }          }
2013            if (VelocityTable) delete[] VelocityTable;
2014      }      }
2015    
2016      /**      /**
# Line 2090  namespace { Line 2135  namespace {
2135                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2136                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2137                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2138                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2139                  }                  }
2140                  else { // active dimension                  else { // active dimension
2141                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2142                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2143                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2144                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2145                                                             dimension == dimension_samplechannel ||                      pDimensionDefinitions[i].zone_size  = __resolveZoneSize(pDimensionDefinitions[i]);
                                                            dimension == dimension_releasetrigger ||  
                                                            dimension == dimension_roundrobin ||  
                                                            dimension == dimension_random) ? split_type_bit  
                                                                                           : split_type_normal;  
                     pDimensionDefinitions[i].ranges = NULL; // it's not possible to check velocity dimensions for custom defined ranges at this point  
                     pDimensionDefinitions[i].zone_size  =  
                         (pDimensionDefinitions[i].split_type == split_type_normal) ? 128.0 / pDimensionDefinitions[i].zones  
                                                                                    : 0;  
2146                      Dimensions++;                      Dimensions++;
2147    
2148                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2114  namespace { Line 2150  namespace {
2150                  }                  }
2151                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2152              }              }
2153                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2154    
2155              // 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,
2156              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2157                  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);  
                     }  
                 }  
             }  
2158    
2159              // 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();  
2160              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2161                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2162              else              else
# Line 2142  namespace { Line 2165  namespace {
2165              // load sample references              // load sample references
2166              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2167                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2168                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2169              }              }
2170                GetSample(); // load global region sample reference
2171            } else {
2172                DimensionRegions = 0;
2173            }
2174    
2175            // make sure there is at least one dimension region
2176            if (!DimensionRegions) {
2177                RIFF::List* _3prg = rgnList->GetSubList(LIST_TYPE_3PRG);
2178                if (!_3prg) _3prg = rgnList->AddSubList(LIST_TYPE_3PRG);
2179                RIFF::List* _3ewl = _3prg->AddSubList(LIST_TYPE_3EWL);
2180                pDimensionRegions[0] = new DimensionRegion(_3ewl);
2181                DimensionRegions = 1;
2182          }          }
2183      }      }
2184    
# Line 2157  namespace { Line 2192  namespace {
2192       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
2193       */       */
2194      void Region::UpdateChunks() {      void Region::UpdateChunks() {
2195            // in the gig format we don't care about the Region's sample reference
2196            // but we still have to provide some existing one to not corrupt the
2197            // file, so to avoid the latter we simply always assign the sample of
2198            // the first dimension region of this region
2199            pSample = pDimensionRegions[0]->pSample;
2200    
2201          // first update base class's chunks          // first update base class's chunks
2202          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
2203    
2204          // update dimension region's chunks          // update dimension region's chunks
2205          for (int i = 0; i < Dimensions; i++)          for (int i = 0; i < DimensionRegions; i++) {
2206              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks();
2207            }
2208    
2209          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
2210          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 2219  namespace {
2219    
2220          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
2221          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2222            store32(&pData[0], DimensionRegions);
2223          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2224              pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2225              pData[i * 8 + 1] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2226              // next 2 bytes unknown              // next 2 bytes unknown
2227              pData[i * 8 + 4] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2228              // next 3 bytes unknown              // next 3 bytes unknown
2229          }          }
2230    
# Line 2190  namespace { Line 2233  namespace {
2233          for (uint i = 0; i < iMaxDimensionRegions; i++) {          for (uint i = 0; i < iMaxDimensionRegions; i++) {
2234              int iWaveIndex = -1;              int iWaveIndex = -1;
2235              if (i < DimensionRegions) {              if (i < DimensionRegions) {
2236                  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");
2237                  std::list<Sample*>::iterator iter = pFile->pSamples->begin();                  File::SampleList::iterator iter = pFile->pSamples->begin();
2238                  std::list<Sample*>::iterator end  = pFile->pSamples->end();                  File::SampleList::iterator end  = pFile->pSamples->end();
2239                  for (int index = 0; iter != end; ++iter, ++index) {                  for (int index = 0; iter != end; ++iter, ++index) {
2240                      if (*iter == pDimensionRegions[i]->pSample) iWaveIndex = index;                      if (*iter == pDimensionRegions[i]->pSample) {
2241                      break;                          iWaveIndex = index;
2242                            break;
2243                        }
2244                  }                  }
2245                  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");
2246              }              }
2247              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2248          }          }
2249      }      }
2250    
# Line 2219  namespace { Line 2264  namespace {
2264          }          }
2265      }      }
2266    
2267      void Region::UpdateVelocityTable(dimension_def_t* pDimDef) {      void Region::UpdateVelocityTable() {
2268          // get dimension's index          // get velocity dimension's index
2269          int iDimensionNr = -1;          int veldim = -1;
2270          for (int i = 0; i < Dimensions; i++) {          for (int i = 0 ; i < Dimensions ; i++) {
2271              if (&pDimensionDefinitions[i] == pDimDef) {              if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2272                  iDimensionNr = i;                  veldim = i;
2273                  break;                  break;
2274              }              }
2275          }          }
2276          if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");          if (veldim == -1) return;
2277    
2278            int step = 1;
2279            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2280            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2281            int end = step * pDimensionDefinitions[veldim].zones;
2282    
2283            // loop through all dimension regions for all dimensions except the velocity dimension
2284            int dim[8] = { 0 };
2285            for (int i = 0 ; i < DimensionRegions ; i++) {
2286    
2287                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2288                    pDimensionRegions[i]->VelocityUpperLimit) {
2289                    // create the velocity table
2290                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2291                    if (!table) {
2292                        table = new uint8_t[128];
2293                        pDimensionRegions[i]->VelocityTable = table;
2294                    }
2295                    int tableidx = 0;
2296                    int velocityZone = 0;
2297                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2298                        for (int k = i ; k < end ; k += step) {
2299                            DimensionRegion *d = pDimensionRegions[k];
2300                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2301                            velocityZone++;
2302                        }
2303                    } else { // gig2
2304                        for (int k = i ; k < end ; k += step) {
2305                            DimensionRegion *d = pDimensionRegions[k];
2306                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2307                            velocityZone++;
2308                        }
2309                    }
2310                } else {
2311                    if (pDimensionRegions[i]->VelocityTable) {
2312                        delete[] pDimensionRegions[i]->VelocityTable;
2313                        pDimensionRegions[i]->VelocityTable = 0;
2314                    }
2315                }
2316    
2317          uint8_t bits[8] = { 0 };              int j;
2318          int previousUpperLimit = -1;              int shift = 0;
2319          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {              for (j = 0 ; j < Dimensions ; j++) {
2320              bits[iDimensionNr] = velocityZone;                  if (j == veldim) i += skipveldim; // skip velocity dimension
2321              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);                  else {
2322                        dim[j]++;
2323              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;                      if (dim[j] < pDimensionDefinitions[j].zones) break;
2324              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;                      else {
2325              previousUpperLimit = pDimDef->ranges[velocityZone].high;                          // skip unused dimension regions
2326              // fill velocity table                          dim[j] = 0;
2327              for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {                          i += ((1 << pDimensionDefinitions[j].bits) -
2328                  VelocityTable[i] = velocityZone;                                pDimensionDefinitions[j].zones) << shift;
2329                        }
2330                    }
2331                    shift += pDimensionDefinitions[j].bits;
2332              }              }
2333                if (j == Dimensions) break;
2334          }          }
2335      }      }
2336    
# Line 2284  namespace { Line 2372  namespace {
2372          // assign definition of new dimension          // assign definition of new dimension
2373          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[Dimensions] = *pDimDef;
2374    
2375            // auto correct certain dimension definition fields (where possible)
2376            pDimensionDefinitions[Dimensions].split_type  =
2377                __resolveSplitType(pDimensionDefinitions[Dimensions].dimension);
2378            pDimensionDefinitions[Dimensions].zone_size =
2379                __resolveZoneSize(pDimensionDefinitions[Dimensions]);
2380    
2381          // create new dimension region(s) for this new dimension          // create new dimension region(s) for this new dimension
2382          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2383              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values              //TODO: maybe we should copy existing dimension regions if possible instead of simply creating new ones with default values
# Line 2297  namespace { Line 2391  namespace {
2391          // if this is a layer dimension, update 'Layers' attribute          // if this is a layer dimension, update 'Layers' attribute
2392          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2393    
2394          // 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);  
         }  
2395      }      }
2396    
2397      /** @brief Delete an existing dimension.      /** @brief Delete an existing dimension.
# Line 2371  namespace { Line 2461  namespace {
2461          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2462          pDimensionDefinitions[Dimensions - 1].bits      = 0;          pDimensionDefinitions[Dimensions - 1].bits      = 0;
2463          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;  
         }  
2464    
2465          Dimensions--;          Dimensions--;
2466    
# Line 2383  namespace { Line 2469  namespace {
2469      }      }
2470    
2471      Region::~Region() {      Region::~Region() {
         for (uint i = 0; i < Dimensions; i++) {  
             if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;  
         }  
2472          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2473              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2474          }          }
# Line 2410  namespace { Line 2493  namespace {
2493       * @see             Dimensions       * @see             Dimensions
2494       */       */
2495      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2496          uint8_t bits[8] = { 0 };          uint8_t bits;
2497            int veldim = -1;
2498            int velbitpos;
2499            int bitpos = 0;
2500            int dimregidx = 0;
2501          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2502              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2503              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2504                  case split_type_normal:                  veldim = i;
2505                      bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size);                  velbitpos = bitpos;
2506                      break;              } else {
2507                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2508                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2509                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2510                  case split_type_bit: // the value is already the sought dimension bit number                              // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
2511                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2512                      bits[i] = bits[i] & limiter_mask; // just make sure the value don't uses more bits than allowed                                  if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
2513                      break;                              }
2514                            } else {
2515                                // gig2: evenly sized zones
2516                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2517                            }
2518                            break;
2519                        case split_type_bit: // the value is already the sought dimension bit number
2520                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2521                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2522                            break;
2523                    }
2524                    dimregidx |= bits << bitpos;
2525              }              }
2526                bitpos += pDimensionDefinitions[i].bits;
2527            }
2528            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2529            if (veldim != -1) {
2530                // (dimreg is now the dimension region for the lowest velocity)
2531                if (dimreg->VelocityTable) // custom defined zone ranges
2532                    bits = dimreg->VelocityTable[DimValues[veldim]];
2533                else // normal split type
2534                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2535    
2536                dimregidx |= bits << velbitpos;
2537                dimreg = pDimensionRegions[dimregidx];
2538          }          }
2539          return GetDimensionRegionByBit(bits);          return dimreg;
2540      }      }
2541    
2542      /**      /**
# Line 2466  namespace { Line 2576  namespace {
2576      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2577          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2578          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2579            if (!file->pWavePoolTable) return NULL;
2580          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2581          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2582          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
2583          while (sample) {          while (sample) {
2584              if (sample->ulWavePoolOffset == soughtoffset &&              if (sample->ulWavePoolOffset == soughtoffset &&
2585                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2586              sample = file->GetNextSample();              sample = file->GetNextSample();
2587          }          }
2588          return NULL;          return NULL;
# Line 2483  namespace { Line 2594  namespace {
2594  // *  // *
2595    
2596      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) {
2597            static const DLS::Info::FixedStringLength fixedStringLengths[] = {
2598                { CHUNK_ID_INAM, 64 },
2599                { CHUNK_ID_ISFT, 12 },
2600                { 0, 0 }
2601            };
2602            pInfo->FixedStringLengths = fixedStringLengths;
2603    
2604          // Initialization          // Initialization
2605          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
         RegionIndex = -1;  
2606    
2607          // Loading          // Loading
2608          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 2503  namespace { Line 2620  namespace {
2620              }              }
2621          }          }
2622    
2623          pRegions = new Region*[Regions];          if (!pRegions) pRegions = new RegionList;
2624          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);          RIFF::List* lrgn = insList->GetSubList(LIST_TYPE_LRGN);
2625          if (lrgn) {          if (lrgn) {
             for (uint i = 0; i < Regions; i++) pRegions[i] = NULL;  
2626              RIFF::List* rgn = lrgn->GetFirstSubList();              RIFF::List* rgn = lrgn->GetFirstSubList();
             unsigned int iRegion = 0;  
2627              while (rgn) {              while (rgn) {
2628                  if (rgn->GetListType() == LIST_TYPE_RGN) {                  if (rgn->GetListType() == LIST_TYPE_RGN) {
2629                      __notify_progress(pProgress, (float) iRegion / (float) Regions);                      __notify_progress(pProgress, (float) pRegions->size() / (float) Regions);
2630                      pRegions[iRegion] = new Region(this, rgn);                      pRegions->push_back(new Region(this, rgn));
                     iRegion++;  
2631                  }                  }
2632                  rgn = lrgn->GetNextSubList();                  rgn = lrgn->GetNextSubList();
2633              }              }
# Line 2525  namespace { Line 2639  namespace {
2639      }      }
2640    
2641      void Instrument::UpdateRegionKeyTable() {      void Instrument::UpdateRegionKeyTable() {
2642          for (uint iReg = 0; iReg < Regions; iReg++) {          RegionList::iterator iter = pRegions->begin();
2643              for (int iKey = pRegions[iReg]->KeyRange.low; iKey <= pRegions[iReg]->KeyRange.high; iKey++) {          RegionList::iterator end  = pRegions->end();
2644                  RegionKeyTable[iKey] = pRegions[iReg];          for (; iter != end; ++iter) {
2645                gig::Region* pRegion = static_cast<gig::Region*>(*iter);
2646                for (int iKey = pRegion->KeyRange.low; iKey <= pRegion->KeyRange.high; iKey++) {
2647                    RegionKeyTable[iKey] = pRegion;
2648              }              }
2649          }          }
2650      }      }
2651    
2652      Instrument::~Instrument() {      Instrument::~Instrument() {
         for (uint i = 0; i < Regions; i++) {  
             if (pRegions) {  
                 if (pRegions[i]) delete (pRegions[i]);  
             }  
         }  
         if (pRegions) delete[] pRegions;  
2653      }      }
2654    
2655      /**      /**
# Line 2555  namespace { Line 2666  namespace {
2666          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks();
2667    
2668          // update Regions' chunks          // update Regions' chunks
2669          for (int i = 0; i < Regions; i++)          {
2670              pRegions[i]->UpdateChunks();              RegionList::iterator iter = pRegions->begin();
2671                RegionList::iterator end  = pRegions->end();
2672                for (; iter != end; ++iter)
2673                    (*iter)->UpdateChunks();
2674            }
2675    
2676          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
2677          RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = pCkInstrument->GetSubList(LIST_TYPE_LART);
# Line 2566  namespace { Line 2681  namespace {
2681          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2682          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
2683          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2684          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
2685          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
2686          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
2687          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
2688          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2689                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
2690          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
2691          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
2692      }      }
2693    
2694      /**      /**
# Line 2584  namespace { Line 2699  namespace {
2699       *             there is no Region defined for the given \a Key       *             there is no Region defined for the given \a Key
2700       */       */
2701      Region* Instrument::GetRegion(unsigned int Key) {      Region* Instrument::GetRegion(unsigned int Key) {
2702          if (!pRegions || Key > 127) return NULL;          if (!pRegions || !pRegions->size() || Key > 127) return NULL;
2703          return RegionKeyTable[Key];          return RegionKeyTable[Key];
2704    
2705          /*for (int i = 0; i < Regions; i++) {          /*for (int i = 0; i < Regions; i++) {
2706              if (Key <= pRegions[i]->KeyRange.high &&              if (Key <= pRegions[i]->KeyRange.high &&
2707                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];                  Key >= pRegions[i]->KeyRange.low) return pRegions[i];
# Line 2601  namespace { Line 2717  namespace {
2717       * @see      GetNextRegion()       * @see      GetNextRegion()
2718       */       */
2719      Region* Instrument::GetFirstRegion() {      Region* Instrument::GetFirstRegion() {
2720          if (!Regions) return NULL;          if (!pRegions) return NULL;
2721          RegionIndex = 1;          RegionsIterator = pRegions->begin();
2722          return pRegions[0];          return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2723      }      }
2724    
2725      /**      /**
# Line 2615  namespace { Line 2731  namespace {
2731       * @see      GetFirstRegion()       * @see      GetFirstRegion()
2732       */       */
2733      Region* Instrument::GetNextRegion() {      Region* Instrument::GetNextRegion() {
2734          if (RegionIndex < 0 || uint32_t(RegionIndex) >= Regions) return NULL;          if (!pRegions) return NULL;
2735          return pRegions[RegionIndex++];          RegionsIterator++;
2736            return static_cast<gig::Region*>( (RegionsIterator != pRegions->end()) ? *RegionsIterator : NULL );
2737      }      }
2738    
2739      Region* Instrument::AddRegion() {      Region* Instrument::AddRegion() {
# Line 2625  namespace { Line 2742  namespace {
2742          if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);          if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
2743          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
2744          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
2745          // resize 'pRegions' array (increase by one)          pRegions->push_back(pNewRegion);
2746          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++;  
2747          // update Region key table for fast lookup          // update Region key table for fast lookup
2748          UpdateRegionKeyTable();          UpdateRegionKeyTable();
2749          // done          // done
# Line 2642  namespace { Line 2752  namespace {
2752    
2753      void Instrument::DeleteRegion(Region* pRegion) {      void Instrument::DeleteRegion(Region* pRegion) {
2754          if (!pRegions) return;          if (!pRegions) return;
2755          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--;  
2756          // update Region key table for fast lookup          // update Region key table for fast lookup
2757          UpdateRegionKeyTable();          UpdateRegionKeyTable();
2758      }      }
2759    
2760    
2761    
2762    // *************** Group ***************
2763    // *
2764    
2765        /** @brief Constructor.
2766         *
2767         * @param file   - pointer to the gig::File object
2768         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
2769         *                 NULL if this is a new Group
2770         */
2771        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
2772            pFile      = file;
2773            pNameChunk = ck3gnm;
2774            ::LoadString(pNameChunk, Name);
2775        }
2776    
2777        Group::~Group() {
2778            // remove the chunk associated with this group (if any)
2779            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
2780        }
2781    
2782        /** @brief Update chunks with current group settings.
2783         *
2784         * Apply current Group field values to the respective chunks. You have
2785         * to call File::Save() to make changes persistent.
2786         *
2787         * Usually there is absolutely no need to call this method explicitly.
2788         * It will be called automatically when File::Save() was called.
2789         */
2790        void Group::UpdateChunks() {
2791            // make sure <3gri> and <3gnl> list chunks exist
2792            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
2793            if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
2794            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
2795            if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);
2796            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
2797            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
2798        }
2799    
2800        /**
2801         * Returns the first Sample of this Group. You have to call this method
2802         * once before you use GetNextSample().
2803         *
2804         * <b>Notice:</b> this method might block for a long time, in case the
2805         * samples of this .gig file were not scanned yet
2806         *
2807         * @returns  pointer address to first Sample or NULL if there is none
2808         *           applied to this Group
2809         * @see      GetNextSample()
2810         */
2811        Sample* Group::GetFirstSample() {
2812            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2813            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
2814                if (pSample->GetGroup() == this) return pSample;
2815            }
2816            return NULL;
2817        }
2818    
2819        /**
2820         * Returns the next Sample of the Group. You have to call
2821         * GetFirstSample() once before you can use this method. By calling this
2822         * method multiple times it iterates through the Samples assigned to
2823         * this Group.
2824         *
2825         * @returns  pointer address to the next Sample of this Group or NULL if
2826         *           end reached
2827         * @see      GetFirstSample()
2828         */
2829        Sample* Group::GetNextSample() {
2830            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2831            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
2832                if (pSample->GetGroup() == this) return pSample;
2833            }
2834            return NULL;
2835        }
2836    
2837        /**
2838         * Move Sample given by \a pSample from another Group to this Group.
2839         */
2840        void Group::AddSample(Sample* pSample) {
2841            pSample->pGroup = this;
2842        }
2843    
2844        /**
2845         * Move all members of this group to another group (preferably the 1st
2846         * one except this). This method is called explicitly by
2847         * File::DeleteGroup() thus when a Group was deleted. This code was
2848         * intentionally not placed in the destructor!
2849         */
2850        void Group::MoveAll() {
2851            // get "that" other group first
2852            Group* pOtherGroup = NULL;
2853            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
2854                if (pOtherGroup != this) break;
2855            }
2856            if (!pOtherGroup) throw Exception(
2857                "Could not move samples to another group, since there is no "
2858                "other Group. This is a bug, report it!"
2859            );
2860            // now move all samples of this group to the other group
2861            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
2862                pOtherGroup->AddSample(pSample);
2863            }
2864        }
2865    
2866    
2867    
2868  // *************** File ***************  // *************** File ***************
2869  // *  // *
2870    
2871        const DLS::Info::FixedStringLength File::FixedStringLengths[] = {
2872            { CHUNK_ID_IARL, 256 },
2873            { CHUNK_ID_IART, 128 },
2874            { CHUNK_ID_ICMS, 128 },
2875            { CHUNK_ID_ICMT, 1024 },
2876            { CHUNK_ID_ICOP, 128 },
2877            { CHUNK_ID_ICRD, 128 },
2878            { CHUNK_ID_IENG, 128 },
2879            { CHUNK_ID_IGNR, 128 },
2880            { CHUNK_ID_IKEY, 128 },
2881            { CHUNK_ID_IMED, 128 },
2882            { CHUNK_ID_INAM, 128 },
2883            { CHUNK_ID_IPRD, 128 },
2884            { CHUNK_ID_ISBJ, 128 },
2885            { CHUNK_ID_ISFT, 128 },
2886            { CHUNK_ID_ISRC, 128 },
2887            { CHUNK_ID_ISRF, 128 },
2888            { CHUNK_ID_ITCH, 128 },
2889            { 0, 0 }
2890        };
2891    
2892      File::File() : DLS::File() {      File::File() : DLS::File() {
2893          pSamples     = NULL;          pGroups = NULL;
2894          pInstruments = NULL;          pInfo->FixedStringLengths = FixedStringLengths;
2895      }      }
2896    
2897      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2898          pSamples     = NULL;          pGroups = NULL;
2899          pInstruments = NULL;          pInfo->FixedStringLengths = FixedStringLengths;
2900      }      }
2901    
2902      File::~File() {      File::~File() {
2903          // free samples          if (pGroups) {
2904          if (pSamples) {              std::list<Group*>::iterator iter = pGroups->begin();
2905              SamplesIterator = pSamples->begin();              std::list<Group*>::iterator end  = pGroups->end();
2906              while (SamplesIterator != pSamples->end() ) {              while (iter != end) {
2907                  delete (*SamplesIterator);                  delete *iter;
2908                  SamplesIterator++;                  ++iter;
2909              }              }
2910              pSamples->clear();              delete pGroups;
2911              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;  
2912      }      }
2913    
2914      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2728  namespace { Line 2936  namespace {
2936         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
2937         RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);         RIFF::List* wvpl = pRIFF->GetSubList(LIST_TYPE_WVPL);
2938         // 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;  
2939         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);         RIFF::List* wave = wvpl->AddSubList(LIST_TYPE_WAVE);
2940         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*/);
2941         pSamples->push_back(pSample);         pSamples->push_back(pSample);
# Line 2744  namespace { Line 2951  namespace {
2951       * @throws gig::Exception if given sample could not be found       * @throws gig::Exception if given sample could not be found
2952       */       */
2953      void File::DeleteSample(Sample* pSample) {      void File::DeleteSample(Sample* pSample) {
2954          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");
2955          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2956          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");
2957            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
2958          pSamples->erase(iter);          pSamples->erase(iter);
2959          delete pSample;          delete pSample;
2960      }      }
2961    
2962        void File::LoadSamples() {
2963            LoadSamples(NULL);
2964        }
2965    
2966      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
2967            // Groups must be loaded before samples, because samples will try
2968            // to resolve the group they belong to
2969            if (!pGroups) LoadGroups();
2970    
2971            if (!pSamples) pSamples = new SampleList;
2972    
2973          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
2974    
2975          // just for progress calculation          // just for progress calculation
# Line 2779  namespace { Line 2997  namespace {
2997                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
2998                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
2999    
                         if (!pSamples) pSamples = new SampleList;  
3000                          unsigned long waveFileOffset = wave->GetFilePos();                          unsigned long waveFileOffset = wave->GetFilePos();
3001                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
3002    
# Line 2796  namespace { Line 3013  namespace {
3013                  name.replace(nameLen, 5, suffix);                  name.replace(nameLen, 5, suffix);
3014                  file = new RIFF::File(name);                  file = new RIFF::File(name);
3015                  ExtensionFiles.push_back(file);                  ExtensionFiles.push_back(file);
3016              }              } else break;
             else throw gig::Exception("Mandatory <wvpl> chunk not found.");  
3017          }          }
3018    
3019          __notify_progress(pProgress, 1.0); // notify done          __notify_progress(pProgress, 1.0); // notify done
# Line 2807  namespace { Line 3023  namespace {
3023          if (!pInstruments) LoadInstruments();          if (!pInstruments) LoadInstruments();
3024          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3025          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3026          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3027      }      }
3028    
3029      Instrument* File::GetNextInstrument() {      Instrument* File::GetNextInstrument() {
3030          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3031          InstrumentsIterator++;          InstrumentsIterator++;
3032          return (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL;          return static_cast<gig::Instrument*>( (InstrumentsIterator != pInstruments->end()) ? *InstrumentsIterator : NULL );
3033      }      }
3034    
3035      /**      /**
# Line 2846  namespace { Line 3062  namespace {
3062          if (!pInstruments) return NULL;          if (!pInstruments) return NULL;
3063          InstrumentsIterator = pInstruments->begin();          InstrumentsIterator = pInstruments->begin();
3064          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {          for (uint i = 0; InstrumentsIterator != pInstruments->end(); i++) {
3065              if (i == index) return *InstrumentsIterator;              if (i == index) return static_cast<gig::Instrument*>( *InstrumentsIterator );
3066              InstrumentsIterator++;              InstrumentsIterator++;
3067          }          }
3068          return NULL;          return NULL;
# Line 2862  namespace { Line 3078  namespace {
3078      Instrument* File::AddInstrument() {      Instrument* File::AddInstrument() {
3079         if (!pInstruments) LoadInstruments();         if (!pInstruments) LoadInstruments();
3080         __ensureMandatoryChunksExist();         __ensureMandatoryChunksExist();
        if (!pInstruments) pInstruments = new InstrumentList;  
3081         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);         RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3082         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);         RIFF::List* lstInstr = lstInstruments->AddSubList(LIST_TYPE_INS);
3083         Instrument* pInstrument = new Instrument(this, lstInstr);         Instrument* pInstrument = new Instrument(this, lstInstr);
# Line 2876  namespace { Line 3091  namespace {
3091       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
3092       *       *
3093       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
3094       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
3095       */       */
3096      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
3097          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");
3098          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), pInstrument);          InstrumentList::iterator iter = find(pInstruments->begin(), pInstruments->end(), (DLS::Instrument*) pInstrument);
3099          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");
3100          pInstruments->erase(iter);          pInstruments->erase(iter);
3101          delete pInstrument;          delete pInstrument;
3102      }      }
3103    
3104        void File::LoadInstruments() {
3105            LoadInstruments(NULL);
3106        }
3107    
3108      void File::LoadInstruments(progress_t* pProgress) {      void File::LoadInstruments(progress_t* pProgress) {
3109            if (!pInstruments) pInstruments = new InstrumentList;
3110          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);          RIFF::List* lstInstruments = pRIFF->GetSubList(LIST_TYPE_LINS);
3111          if (lstInstruments) {          if (lstInstruments) {
3112              int iInstrumentIndex = 0;              int iInstrumentIndex = 0;
# Line 2901  namespace { Line 3121  namespace {
3121                      progress_t subprogress;                      progress_t subprogress;
3122                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);                      __divide_progress(pProgress, &subprogress, Instruments, iInstrumentIndex);
3123    
                     if (!pInstruments) pInstruments = new InstrumentList;  
3124                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));                      pInstruments->push_back(new Instrument(this, lstInstr, &subprogress));
3125    
3126                      iInstrumentIndex++;                      iInstrumentIndex++;
# Line 2910  namespace { Line 3129  namespace {
3129              }              }
3130              __notify_progress(pProgress, 1.0); // notify done              __notify_progress(pProgress, 1.0); // notify done
3131          }          }
3132          else throw gig::Exception("Mandatory <lins> list chunk not found.");      }
3133    
3134        Group* File::GetFirstGroup() {
3135            if (!pGroups) LoadGroups();
3136            // there must always be at least one group
3137            GroupsIterator = pGroups->begin();
3138            return *GroupsIterator;
3139        }
3140    
3141        Group* File::GetNextGroup() {
3142            if (!pGroups) return NULL;
3143            ++GroupsIterator;
3144            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
3145        }
3146    
3147        /**
3148         * Returns the group with the given index.
3149         *
3150         * @param index - number of the sought group (0..n)
3151         * @returns sought group or NULL if there's no such group
3152         */
3153        Group* File::GetGroup(uint index) {
3154            if (!pGroups) LoadGroups();
3155            GroupsIterator = pGroups->begin();
3156            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
3157                if (i == index) return *GroupsIterator;
3158                ++GroupsIterator;
3159            }
3160            return NULL;
3161        }
3162    
3163        Group* File::AddGroup() {
3164            if (!pGroups) LoadGroups();
3165            // there must always be at least one group
3166            __ensureMandatoryChunksExist();
3167            Group* pGroup = new Group(this, NULL);
3168            pGroups->push_back(pGroup);
3169            return pGroup;
3170        }
3171    
3172        /** @brief Delete a group and its samples.
3173         *
3174         * This will delete the given Group object and all the samples that
3175         * belong to this group from the gig file. You have to call Save() to
3176         * make this persistent to the file.
3177         *
3178         * @param pGroup - group to delete
3179         * @throws gig::Exception if given group could not be found
3180         */
3181        void File::DeleteGroup(Group* pGroup) {
3182            if (!pGroups) LoadGroups();
3183            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3184            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3185            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3186            // delete all members of this group
3187            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
3188                DeleteSample(pSample);
3189            }
3190            // now delete this group object
3191            pGroups->erase(iter);
3192            delete pGroup;
3193        }
3194    
3195        /** @brief Delete a group.
3196         *
3197         * This will delete the given Group object from the gig file. All the
3198         * samples that belong to this group will not be deleted, but instead
3199         * be moved to another group. You have to call Save() to make this
3200         * persistent to the file.
3201         *
3202         * @param pGroup - group to delete
3203         * @throws gig::Exception if given group could not be found
3204         */
3205        void File::DeleteGroupOnly(Group* pGroup) {
3206            if (!pGroups) LoadGroups();
3207            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3208            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3209            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3210            // move all members of this group to another group
3211            pGroup->MoveAll();
3212            pGroups->erase(iter);
3213            delete pGroup;
3214        }
3215    
3216        void File::LoadGroups() {
3217            if (!pGroups) pGroups = new std::list<Group*>;
3218            // try to read defined groups from file
3219            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
3220            if (lst3gri) {
3221                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
3222                if (lst3gnl) {
3223                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3224                    while (ck) {
3225                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3226                            pGroups->push_back(new Group(this, ck));
3227                        }
3228                        ck = lst3gnl->GetNextSubChunk();
3229                    }
3230                }
3231            }
3232            // if there were no group(s), create at least the mandatory default group
3233            if (!pGroups->size()) {
3234                Group* pGroup = new Group(this, NULL);
3235                pGroup->Name = "Default Group";
3236                pGroups->push_back(pGroup);
3237            }
3238        }
3239    
3240        /**
3241         * Apply all the gig file's current instruments, samples, groups and settings
3242         * to the respective RIFF chunks. You have to call Save() to make changes
3243         * persistent.
3244         *
3245         * Usually there is absolutely no need to call this method explicitly.
3246         * It will be called automatically when File::Save() was called.
3247         *
3248         * @throws Exception - on errors
3249         */
3250        void File::UpdateChunks() {
3251            // first update base class's chunks
3252            DLS::File::UpdateChunks();
3253    
3254            // update group's chunks
3255            if (pGroups) {
3256                std::list<Group*>::iterator iter = pGroups->begin();
3257                std::list<Group*>::iterator end  = pGroups->end();
3258                for (; iter != end; ++iter) {
3259                    (*iter)->UpdateChunks();
3260                }
3261            }
3262      }      }
3263    
3264    

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

  ViewVC Help
Powered by ViewVC