/[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 823 by schoenebeck, Fri Dec 23 01:38:50 2005 UTC revision 1179 by persson, Sat May 12 11:25:04 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            pInfo->UseFixedLengthStrings = true;
307          Instances++;          Instances++;
308          FileNo = fileNo;          FileNo = fileNo;
309    
310          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
311          if (pCk3gix) {          if (pCk3gix) {
312              SampleGroup = pCk3gix->ReadInt16();              uint16_t iSampleGroup = pCk3gix->ReadInt16();
313                pGroup = pFile->GetGroup(iSampleGroup);
314          } else { // '3gix' chunk missing          } else { // '3gix' chunk missing
315              // use default value(s)              // by default assigned to that mandatory "Default Group"
316              SampleGroup = 0;              pGroup = pFile->GetGroup(0);
317          }          }
318    
319          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = waveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 327  namespace { Line 337  namespace {
337              // use default values              // use default values
338              Manufacturer  = 0;              Manufacturer  = 0;
339              Product       = 0;              Product       = 0;
340              SamplePeriod  = 1 / SamplesPerSecond;              SamplePeriod  = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
341              MIDIUnityNote = 64;              MIDIUnityNote = 64;
342              FineTune      = 0;              FineTune      = 0;
343              SMPTEOffset   = 0;              SMPTEOffset   = 0;
# Line 368  namespace { Line 378  namespace {
378          }          }
379          FrameOffset = 0; // just for streaming compressed samples          FrameOffset = 0; // just for streaming compressed samples
380    
381          LoopSize = LoopEnd - LoopStart;          LoopSize = LoopEnd - LoopStart + 1;
382      }      }
383    
384      /**      /**
# Line 378  namespace { Line 388  namespace {
388       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
389       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
390       *       *
391       * @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
392       *                        was provided yet       *                        was provided yet
393       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
394       */       */
# Line 391  namespace { Line 401  namespace {
401          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);          if (!pCkSmpl) pCkSmpl = pWaveList->AddSubChunk(CHUNK_ID_SMPL, 60);
402          // update 'smpl' chunk          // update 'smpl' chunk
403          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();          uint8_t* pData = (uint8_t*) pCkSmpl->LoadChunkData();
404          SamplePeriod = 1 / SamplesPerSecond;          SamplePeriod = uint32_t(1000000000.0 / SamplesPerSecond + 0.5);
405          memcpy(&pData[0], &Manufacturer, 4);          store32(&pData[0], Manufacturer);
406          memcpy(&pData[4], &Product, 4);          store32(&pData[4], Product);
407          memcpy(&pData[8], &SamplePeriod, 4);          store32(&pData[8], SamplePeriod);
408          memcpy(&pData[12], &MIDIUnityNote, 4);          store32(&pData[12], MIDIUnityNote);
409          memcpy(&pData[16], &FineTune, 4);          store32(&pData[16], FineTune);
410          memcpy(&pData[20], &SMPTEFormat, 4);          store32(&pData[20], SMPTEFormat);
411          memcpy(&pData[24], &SMPTEOffset, 4);          store32(&pData[24], SMPTEOffset);
412          memcpy(&pData[28], &Loops, 4);          store32(&pData[28], Loops);
413    
414          // we skip 'manufByt' for now (4 bytes)          // we skip 'manufByt' for now (4 bytes)
415    
416          memcpy(&pData[36], &LoopID, 4);          store32(&pData[36], LoopID);
417          memcpy(&pData[40], &LoopType, 4);          store32(&pData[40], LoopType);
418          memcpy(&pData[44], &LoopStart, 4);          store32(&pData[44], LoopStart);
419          memcpy(&pData[48], &LoopEnd, 4);          store32(&pData[48], LoopEnd);
420          memcpy(&pData[52], &LoopFraction, 4);          store32(&pData[52], LoopFraction);
421          memcpy(&pData[56], &LoopPlayCount, 4);          store32(&pData[56], LoopPlayCount);
422    
423          // make sure '3gix' chunk exists          // make sure '3gix' chunk exists
424          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = pWaveList->GetSubChunk(CHUNK_ID_3GIX);
425          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);          if (!pCk3gix) pCk3gix = pWaveList->AddSubChunk(CHUNK_ID_3GIX, 4);
426            // determine appropriate sample group index (to be stored in chunk)
427            uint16_t iSampleGroup = 0; // 0 refers to default sample group
428            File* pFile = static_cast<File*>(pParent);
429            if (pFile->pGroups) {
430                std::list<Group*>::iterator iter = pFile->pGroups->begin();
431                std::list<Group*>::iterator end  = pFile->pGroups->end();
432                for (int i = 0; iter != end; i++, iter++) {
433                    if (*iter == pGroup) {
434                        iSampleGroup = i;
435                        break; // found
436                    }
437                }
438            }
439          // update '3gix' chunk          // update '3gix' chunk
440          pData = (uint8_t*) pCk3gix->LoadChunkData();          pData = (uint8_t*) pCk3gix->LoadChunkData();
441          memcpy(&pData[0], &SampleGroup, 2);          store16(&pData[0], iSampleGroup);
442      }      }
443    
444      /// 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 659  namespace {
659       * enlarged samples before calling File::Save() as this might exceed the       * enlarged samples before calling File::Save() as this might exceed the
660       * current sample's boundary!       * current sample's boundary!
661       *       *
662       * Also note: only WAVE_FORMAT_PCM is currently supported, that is       * Also note: only DLS_WAVE_FORMAT_PCM is currently supported, that is
663       * FormatTag must be WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
664       * other formats will fail!       * other formats will fail!
665       *       *
666       * @param iNewSize - new sample wave data size in sample points (must be       * @param iNewSize - new sample wave data size in sample points (must be
667       *                   greater than zero)       *                   greater than zero)
668       * @throws DLS::Excecption if FormatTag != WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
669       *                         or if \a iNewSize is less than 1       *                         or if \a iNewSize is less than 1
670       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
671       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
# Line 742  namespace { Line 765  namespace {
765       * @param SampleCount      number of sample points to read       * @param SampleCount      number of sample points to read
766       * @param pPlaybackState   will be used to store and reload the playback       * @param pPlaybackState   will be used to store and reload the playback
767       *                         state for the next ReadAndLoop() call       *                         state for the next ReadAndLoop() call
768         * @param pDimRgn          dimension region with looping information
769       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
770       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
771       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
772       */       */
773      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,
774                                          DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
775          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
776          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
777    
778          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
779    
780          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
781    
782              switch (this->LoopType) {              const DLS::sample_loop_t& loop = pDimRgn->pSampleLoops[0];
783                const uint32_t loopEnd = loop.LoopStart + loop.LoopLength;
784    
785                  case loop_type_bidirectional: { //TODO: not tested yet!              if (GetPos() <= loopEnd) {
786                      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  
787    
788                              // as we can only read forward from disk, we have to                      case loop_type_bidirectional: { //TODO: not tested yet!
789                              // determine the end position within the loop first,                          do {
790                              // read forward from that 'end' and finally after                              // if not endless loop check if max. number of loop cycles have been passed
791                              // reading, swap all sample frames so it reflects                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
792                              // backward playback  
793                                if (!pPlaybackState->reverse) { // forward playback
794                              unsigned long swapareastart       = totalreadsamples;                                  do {
795                              unsigned long loopoffset          = GetPos() - this->LoopStart;                                      samplestoloopend  = loopEnd - GetPos();
796                              unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                      readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
797                              unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                      samplestoread    -= readsamples;
798                                        totalreadsamples += readsamples;
799                              SetPos(reverseplaybackend);                                      if (readsamples == samplestoloopend) {
800                                            pPlaybackState->reverse = true;
801                              // read samples for backward playback                                          break;
802                              do {                                      }
803                                  readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);                                  } while (samplestoread && readsamples);
804                                  samplestoreadinloop -= readsamples;                              }
805                                  samplestoread       -= readsamples;                              else { // backward playback
                                 totalreadsamples    += readsamples;  
                             } while (samplestoreadinloop && readsamples);  
806    
807                              SetPos(reverseplaybackend); // pretend we really read backwards                                  // as we can only read forward from disk, we have to
808                                    // determine the end position within the loop first,
809                                    // read forward from that 'end' and finally after
810                                    // reading, swap all sample frames so it reflects
811                                    // backward playback
812    
813                                    unsigned long swapareastart       = totalreadsamples;
814                                    unsigned long loopoffset          = GetPos() - loop.LoopStart;
815                                    unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);
816                                    unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;
817    
818                                    SetPos(reverseplaybackend);
819    
820                                    // read samples for backward playback
821                                    do {
822                                        readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], samplestoreadinloop, pExternalDecompressionBuffer);
823                                        samplestoreadinloop -= readsamples;
824                                        samplestoread       -= readsamples;
825                                        totalreadsamples    += readsamples;
826                                    } while (samplestoreadinloop && readsamples);
827    
828                                    SetPos(reverseplaybackend); // pretend we really read backwards
829    
830                                    if (reverseplaybackend == loop.LoopStart) {
831                                        pPlaybackState->loop_cycles_left--;
832                                        pPlaybackState->reverse = false;
833                                    }
834    
835                              if (reverseplaybackend == this->LoopStart) {                                  // reverse the sample frames for backward playback
836                                  pPlaybackState->loop_cycles_left--;                                  SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
                                 pPlaybackState->reverse = false;  
837                              }                              }
838                            } while (samplestoread && readsamples);
839                            break;
840                        }
841    
842                              // reverse the sample frames for backward playback                      case loop_type_backward: { // TODO: not tested yet!
843                              SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          // forward playback (not entered the loop yet)
844                          }                          if (!pPlaybackState->reverse) do {
845                      } while (samplestoread && readsamples);                              samplestoloopend  = loopEnd - GetPos();
846                      break;                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
847                  }                              samplestoread    -= readsamples;
848                                totalreadsamples += readsamples;
849                  case loop_type_backward: { // TODO: not tested yet!                              if (readsamples == samplestoloopend) {
850                      // forward playback (not entered the loop yet)                                  pPlaybackState->reverse = true;
851                      if (!pPlaybackState->reverse) do {                                  break;
852                          samplestoloopend  = this->LoopEnd - GetPos();                              }
853                          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);  
854    
855                      if (!samplestoread) break;                          if (!samplestoread) break;
856    
857                      // as we can only read forward from disk, we have to                          // as we can only read forward from disk, we have to
858                      // determine the end position within the loop first,                          // determine the end position within the loop first,
859                      // read forward from that 'end' and finally after                          // read forward from that 'end' and finally after
860                      // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
861                      // backward playback                          // backward playback
862    
863                      unsigned long swapareastart       = totalreadsamples;                          unsigned long swapareastart       = totalreadsamples;
864                      unsigned long loopoffset          = GetPos() - this->LoopStart;                          unsigned long loopoffset          = GetPos() - loop.LoopStart;
865                      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)
866                                                                                : samplestoread;                                                                                    : samplestoread;
867                      unsigned long reverseplaybackend  = this->LoopStart + Abs((loopoffset - samplestoreadinloop) % this->LoopSize);                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
868    
869                      SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
870    
871                      // read samples for backward playback                          // read samples for backward playback
872                      do {                          do {
873                          // if not endless loop check if max. number of loop cycles have been passed                              // if not endless loop check if max. number of loop cycles have been passed
874                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
875                          samplestoloopend     = this->LoopEnd - GetPos();                              samplestoloopend     = loopEnd - GetPos();
876                          readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);                              readsamples          = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoreadinloop, samplestoloopend), pExternalDecompressionBuffer);
877                          samplestoreadinloop -= readsamples;                              samplestoreadinloop -= readsamples;
878                          samplestoread       -= readsamples;                              samplestoread       -= readsamples;
879                          totalreadsamples    += readsamples;                              totalreadsamples    += readsamples;
880                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
881                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
882                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
883                          }                              }
884                      } while (samplestoreadinloop && readsamples);                          } while (samplestoreadinloop && readsamples);
885    
886                      SetPos(reverseplaybackend); // pretend we really read backwards                          SetPos(reverseplaybackend); // pretend we really read backwards
887    
888                      // reverse the sample frames for backward playback                          // reverse the sample frames for backward playback
889                      SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);                          SwapMemoryArea(&pDst[swapareastart * this->FrameSize], (totalreadsamples - swapareastart) * this->FrameSize, this->FrameSize);
890                      break;                          break;
891                  }                      }
892    
893                  default: case loop_type_normal: {                      default: case loop_type_normal: {
894                      do {                          do {
895                          // 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
896                          if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;                              if (this->LoopPlayCount && !pPlaybackState->loop_cycles_left) break;
897                          samplestoloopend  = this->LoopEnd - GetPos();                              samplestoloopend  = loopEnd - GetPos();
898                          readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);                              readsamples       = Read(&pDst[totalreadsamples * this->FrameSize], Min(samplestoread, samplestoloopend), pExternalDecompressionBuffer);
899                          samplestoread    -= readsamples;                              samplestoread    -= readsamples;
900                          totalreadsamples += readsamples;                              totalreadsamples += readsamples;
901                          if (readsamples == samplestoloopend) {                              if (readsamples == samplestoloopend) {
902                              pPlaybackState->loop_cycles_left--;                                  pPlaybackState->loop_cycles_left--;
903                              SetPos(this->LoopStart);                                  SetPos(loop.LoopStart);
904                          }                              }
905                      } while (samplestoread && readsamples);                          } while (samplestoread && readsamples);
906                      break;                          break;
907                        }
908                  }                  }
909              }              }
910          }          }
# Line 904  namespace { Line 934  namespace {
934       * have to use an external decompression buffer for <b>EACH</b>       * have to use an external decompression buffer for <b>EACH</b>
935       * streaming thread to avoid race conditions and crashes!       * streaming thread to avoid race conditions and crashes!
936       *       *
937         * For 16 bit samples, the data in the buffer will be int16_t
938         * (using native endianness). For 24 bit, the buffer will
939         * contain three bytes per sample, little-endian.
940         *
941       * @param pBuffer      destination buffer       * @param pBuffer      destination buffer
942       * @param SampleCount  number of sample points to read       * @param SampleCount  number of sample points to read
943       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression       * @param pExternalDecompressionBuffer  (optional) external buffer to use for decompression
# Line 914  namespace { Line 948  namespace {
948          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
949          if (!Compressed) {          if (!Compressed) {
950              if (BitDepth == 24) {              if (BitDepth == 24) {
951                  // 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);  
                 }  
952              }              }
953              else { // 16 bit              else { // 16 bit
954                  // (pCkData->Read does endian correction)                  // (pCkData->Read does endian correction)
# Line 964  namespace { Line 978  namespace {
978    
979              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;              unsigned char* pSrc = (unsigned char*) pDecompressionBuffer->pStart;
980              int16_t* pDst = static_cast<int16_t*>(pBuffer);              int16_t* pDst = static_cast<int16_t*>(pBuffer);
981                uint8_t* pDst24 = static_cast<uint8_t*>(pBuffer);
982              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
983    
984              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
# Line 1045  namespace { Line 1060  namespace {
1060                              const unsigned char* const param_r = pSrc;                              const unsigned char* const param_r = pSrc;
1061                              if (mode_r != 2) pSrc += 12;                              if (mode_r != 2) pSrc += 12;
1062    
1063                              Decompress24(mode_l, param_l, 2, pSrc, pDst,                              Decompress24(mode_l, param_l, 6, pSrc, pDst24,
1064                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1065                              Decompress24(mode_r, param_r, 2, pSrc + rightChannelOffset, pDst + 1,                              Decompress24(mode_r, param_r, 6, pSrc + rightChannelOffset, pDst24 + 3,
1066                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1067                              pDst += copysamples << 1;                              pDst24 += copysamples * 6;
1068                          }                          }
1069                          else { // Mono                          else { // Mono
1070                              Decompress24(mode_l, param_l, 1, pSrc, pDst,                              Decompress24(mode_l, param_l, 3, pSrc, pDst24,
1071                                           skipsamples, copysamples, TruncatedBits);                                           skipsamples, copysamples, TruncatedBits);
1072                              pDst += copysamples;                              pDst24 += copysamples * 3;
1073                          }                          }
1074                      }                      }
1075                      else { // 16 bit                      else { // 16 bit
# Line 1161  namespace { Line 1176  namespace {
1176          }          }
1177      }      }
1178    
1179        /**
1180         * Returns pointer to the Group this Sample belongs to. In the .gig
1181         * format a sample always belongs to one group. If it wasn't explicitly
1182         * assigned to a certain group, it will be automatically assigned to a
1183         * default group.
1184         *
1185         * @returns Sample's Group (never NULL)
1186         */
1187        Group* Sample::GetGroup() const {
1188            return pGroup;
1189        }
1190    
1191      Sample::~Sample() {      Sample::~Sample() {
1192          Instances--;          Instances--;
1193          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1190  namespace { Line 1217  namespace {
1217    
1218          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);          RIFF::Chunk* _3ewa = _3ewl->GetSubChunk(CHUNK_ID_3EWA);
1219          if (_3ewa) { // if '3ewa' chunk exists          if (_3ewa) { // if '3ewa' chunk exists
1220              _3ewa->ReadInt32(); // unknown, always 0x0000008C ?              _3ewa->ReadInt32(); // unknown, always == chunk size ?
1221              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              LFO3Frequency = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1222              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());              EG3Attack     = (double) GIG_EXP_DECODE(_3ewa->ReadInt32());
1223              _3ewa->ReadInt16(); // unknown              _3ewa->ReadInt16(); // unknown
# Line 1335  namespace { Line 1362  namespace {
1362                  if (lfo3ctrl & 0x40) // bit 6                  if (lfo3ctrl & 0x40) // bit 6
1363                      VCFType = vcf_type_lowpassturbo;                      VCFType = vcf_type_lowpassturbo;
1364              }              }
1365                if (_3ewa->RemainingBytes() >= 8) {
1366                    _3ewa->Read(DimensionUpperLimits, 1, 8);
1367                } else {
1368                    memset(DimensionUpperLimits, 0, 8);
1369                }
1370          } else { // '3ewa' chunk does not exist yet          } else { // '3ewa' chunk does not exist yet
1371              // use default values              // use default values
1372              LFO3Frequency                   = 1.0;              LFO3Frequency                   = 1.0;
# Line 1415  namespace { Line 1447  namespace {
1447              VCFVelocityDynamicRange         = 0x04;              VCFVelocityDynamicRange         = 0x04;
1448              VCFVelocityCurve                = curve_type_linear;              VCFVelocityCurve                = curve_type_linear;
1449              VCFType                         = vcf_type_lowpass;              VCFType                         = vcf_type_lowpass;
1450                memset(DimensionUpperLimits, 0, 8);
1451          }          }
1452    
1453          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,          pVelocityAttenuationTable = GetVelocityTable(VelocityResponseCurve,
# Line 1449  namespace { Line 1482  namespace {
1482                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);                                                  VCFCutoffController <= vcf_cutoff_ctrl_none2 ? VCFVelocityScale : 0);
1483    
1484          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));          SampleAttenuation = pow(10.0, -Gain / (20.0 * 655360));
1485            VelocityTable = 0;
1486      }      }
1487    
1488      /**      /**
# Line 1469  namespace { Line 1503  namespace {
1503    
1504          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1505    
1506          const uint32_t unknown = 0x0000008C; // unknown, always 0x0000008C ?          const uint32_t chunksize = _3ewa->GetSize();
1507          memcpy(&pData[0], &unknown, 4);          store32(&pData[0], chunksize); // unknown, always chunk size?
1508    
1509          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
1510          memcpy(&pData[4], &lfo3freq, 4);          store32(&pData[4], lfo3freq);
1511    
1512          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);          const int32_t eg3attack = (int32_t) GIG_EXP_ENCODE(EG3Attack);
1513          memcpy(&pData[4], &eg3attack, 4);          store32(&pData[8], eg3attack);
1514    
1515          // next 2 bytes unknown          // next 2 bytes unknown
1516    
1517          memcpy(&pData[10], &LFO1InternalDepth, 2);          store16(&pData[14], LFO1InternalDepth);
1518    
1519          // next 2 bytes unknown          // next 2 bytes unknown
1520    
1521          memcpy(&pData[14], &LFO3InternalDepth, 2);          store16(&pData[18], LFO3InternalDepth);
1522    
1523          // next 2 bytes unknown          // next 2 bytes unknown
1524    
1525          memcpy(&pData[18], &LFO1ControlDepth, 2);          store16(&pData[22], LFO1ControlDepth);
1526    
1527          // next 2 bytes unknown          // next 2 bytes unknown
1528    
1529          memcpy(&pData[22], &LFO3ControlDepth, 2);          store16(&pData[26], LFO3ControlDepth);
1530    
1531          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);          const int32_t eg1attack = (int32_t) GIG_EXP_ENCODE(EG1Attack);
1532          memcpy(&pData[24], &eg1attack, 4);          store32(&pData[28], eg1attack);
1533    
1534          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);          const int32_t eg1decay1 = (int32_t) GIG_EXP_ENCODE(EG1Decay1);
1535          memcpy(&pData[28], &eg1decay1, 4);          store32(&pData[32], eg1decay1);
1536    
1537          // next 2 bytes unknown          // next 2 bytes unknown
1538    
1539          memcpy(&pData[34], &EG1Sustain, 2);          store16(&pData[38], EG1Sustain);
1540    
1541          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);          const int32_t eg1release = (int32_t) GIG_EXP_ENCODE(EG1Release);
1542          memcpy(&pData[36], &eg1release, 4);          store32(&pData[40], eg1release);
1543    
1544          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);          const uint8_t eg1ctl = (uint8_t) EncodeLeverageController(EG1Controller);
1545          memcpy(&pData[40], &eg1ctl, 1);          pData[44] = eg1ctl;
1546    
1547          const uint8_t eg1ctrloptions =          const uint8_t eg1ctrloptions =
1548              (EG1ControllerInvert) ? 0x01 : 0x00 |              (EG1ControllerInvert) ? 0x01 : 0x00 |
1549              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG1ControllerAttackInfluence) |
1550              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG1ControllerDecayInfluence) |
1551              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG1ControllerReleaseInfluence);
1552          memcpy(&pData[41], &eg1ctrloptions, 1);          pData[45] = eg1ctrloptions;
1553    
1554          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);          const uint8_t eg2ctl = (uint8_t) EncodeLeverageController(EG2Controller);
1555          memcpy(&pData[42], &eg2ctl, 1);          pData[46] = eg2ctl;
1556    
1557          const uint8_t eg2ctrloptions =          const uint8_t eg2ctrloptions =
1558              (EG2ControllerInvert) ? 0x01 : 0x00 |              (EG2ControllerInvert) ? 0x01 : 0x00 |
1559              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |              GIG_EG_CTR_ATTACK_INFLUENCE_ENCODE(EG2ControllerAttackInfluence) |
1560              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |              GIG_EG_CTR_DECAY_INFLUENCE_ENCODE(EG2ControllerDecayInfluence) |
1561              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);              GIG_EG_CTR_RELEASE_INFLUENCE_ENCODE(EG2ControllerReleaseInfluence);
1562          memcpy(&pData[43], &eg2ctrloptions, 1);          pData[47] = eg2ctrloptions;
1563    
1564          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);          const int32_t lfo1freq = (int32_t) GIG_EXP_ENCODE(LFO1Frequency);
1565          memcpy(&pData[44], &lfo1freq, 4);          store32(&pData[48], lfo1freq);
1566    
1567          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);          const int32_t eg2attack = (int32_t) GIG_EXP_ENCODE(EG2Attack);
1568          memcpy(&pData[48], &eg2attack, 4);          store32(&pData[52], eg2attack);
1569    
1570          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);          const int32_t eg2decay1 = (int32_t) GIG_EXP_ENCODE(EG2Decay1);
1571          memcpy(&pData[52], &eg2decay1, 4);          store32(&pData[56], eg2decay1);
1572    
1573          // next 2 bytes unknown          // next 2 bytes unknown
1574    
1575          memcpy(&pData[58], &EG2Sustain, 2);          store16(&pData[62], EG2Sustain);
1576    
1577          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);          const int32_t eg2release = (int32_t) GIG_EXP_ENCODE(EG2Release);
1578          memcpy(&pData[60], &eg2release, 4);          store32(&pData[64], eg2release);
1579    
1580          // next 2 bytes unknown          // next 2 bytes unknown
1581    
1582          memcpy(&pData[66], &LFO2ControlDepth, 2);          store16(&pData[70], LFO2ControlDepth);
1583    
1584          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);          const int32_t lfo2freq = (int32_t) GIG_EXP_ENCODE(LFO2Frequency);
1585          memcpy(&pData[68], &lfo2freq, 4);          store32(&pData[72], lfo2freq);
1586    
1587          // next 2 bytes unknown          // next 2 bytes unknown
1588    
1589          memcpy(&pData[72], &LFO2InternalDepth, 2);          store16(&pData[78], LFO2InternalDepth);
1590    
1591          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);
1592          memcpy(&pData[74], &eg1decay2, 4);          store32(&pData[80], eg1decay2);
1593    
1594          // next 2 bytes unknown          // next 2 bytes unknown
1595    
1596          memcpy(&pData[80], &EG1PreAttack, 2);          store16(&pData[86], EG1PreAttack);
1597    
1598          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);
1599          memcpy(&pData[82], &eg2decay2, 4);          store32(&pData[88], eg2decay2);
1600    
1601          // next 2 bytes unknown          // next 2 bytes unknown
1602    
1603          memcpy(&pData[88], &EG2PreAttack, 2);          store16(&pData[94], EG2PreAttack);
1604    
1605          {          {
1606              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 1584  namespace { Line 1618  namespace {
1618                  default:                  default:
1619                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown VelocityResponseCurve selected");
1620              }              }
1621              memcpy(&pData[90], &velocityresponse, 1);              pData[96] = velocityresponse;
1622          }          }
1623    
1624          {          {
# Line 1603  namespace { Line 1637  namespace {
1637                  default:                  default:
1638                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown ReleaseVelocityResponseCurve selected");
1639              }              }
1640              memcpy(&pData[91], &releasevelocityresponse, 1);              pData[97] = releasevelocityresponse;
1641          }          }
1642    
1643          memcpy(&pData[92], &VelocityResponseCurveScaling, 1);          pData[98] = VelocityResponseCurveScaling;
1644    
1645          memcpy(&pData[93], &AttenuationControllerThreshold, 1);          pData[99] = AttenuationControllerThreshold;
1646    
1647          // next 4 bytes unknown          // next 4 bytes unknown
1648    
1649          memcpy(&pData[98], &SampleStartOffset, 2);          store16(&pData[104], SampleStartOffset);
1650    
1651          // next 2 bytes unknown          // next 2 bytes unknown
1652    
# Line 1631  namespace { Line 1665  namespace {
1665                  default:                  default:
1666                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");                      throw Exception("Could not update DimensionRegion's chunk, unknown DimensionBypass selected");
1667              }              }
1668              memcpy(&pData[102], &pitchTrackDimensionBypass, 1);              pData[108] = pitchTrackDimensionBypass;
1669          }          }
1670    
1671          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
1672          memcpy(&pData[103], &pan, 1);          pData[109] = pan;
1673    
1674          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;          const uint8_t selfmask = (SelfMask) ? 0x01 : 0x00;
1675          memcpy(&pData[104], &selfmask, 1);          pData[110] = selfmask;
1676    
1677          // next byte unknown          // next byte unknown
1678    
# Line 1647  namespace { Line 1681  namespace {
1681              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5              if (LFO3Sync) lfo3ctrl |= 0x20; // bit 5
1682              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7              if (InvertAttenuationController) lfo3ctrl |= 0x80; // bit 7
1683              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6              if (VCFType == vcf_type_lowpassturbo) lfo3ctrl |= 0x40; // bit 6
1684              memcpy(&pData[106], &lfo3ctrl, 1);              pData[112] = lfo3ctrl;
1685          }          }
1686    
1687          const uint8_t attenctl = EncodeLeverageController(AttenuationController);          const uint8_t attenctl = EncodeLeverageController(AttenuationController);
1688          memcpy(&pData[107], &attenctl, 1);          pData[113] = attenctl;
1689    
1690          {          {
1691              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits              uint8_t lfo2ctrl = LFO2Controller & 0x07; // lower 3 bits
1692              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7              if (LFO2FlipPhase) lfo2ctrl |= 0x80; // bit 7
1693              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5              if (LFO2Sync)      lfo2ctrl |= 0x20; // bit 5
1694              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6              if (VCFResonanceController != vcf_res_ctrl_none) lfo2ctrl |= 0x40; // bit 6
1695              memcpy(&pData[108], &lfo2ctrl, 1);              pData[114] = lfo2ctrl;
1696          }          }
1697    
1698          {          {
# Line 1667  namespace { Line 1701  namespace {
1701              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6              if (LFO1Sync)      lfo1ctrl |= 0x40; // bit 6
1702              if (VCFResonanceController != vcf_res_ctrl_none)              if (VCFResonanceController != vcf_res_ctrl_none)
1703                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);                  lfo1ctrl |= GIG_VCF_RESONANCE_CTRL_ENCODE(VCFResonanceController);
1704              memcpy(&pData[109], &lfo1ctrl, 1);              pData[115] = lfo1ctrl;
1705          }          }
1706    
1707          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth          const uint16_t eg3depth = (EG3Depth >= 0) ? EG3Depth
1708                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */                                                    : uint16_t(((-EG3Depth) - 1) ^ 0xffff); /* binary complementary for negatives */
1709          memcpy(&pData[110], &eg3depth, 1);          pData[116] = eg3depth;
1710    
1711          // next 2 bytes unknown          // next 2 bytes unknown
1712    
1713          const uint8_t channeloffset = ChannelOffset * 4;          const uint8_t channeloffset = ChannelOffset * 4;
1714          memcpy(&pData[113], &channeloffset, 1);          pData[120] = channeloffset;
1715    
1716          {          {
1717              uint8_t regoptions = 0;              uint8_t regoptions = 0;
1718              if (MSDecode)      regoptions |= 0x01; // bit 0              if (MSDecode)      regoptions |= 0x01; // bit 0
1719              if (SustainDefeat) regoptions |= 0x02; // bit 1              if (SustainDefeat) regoptions |= 0x02; // bit 1
1720              memcpy(&pData[114], &regoptions, 1);              pData[121] = regoptions;
1721          }          }
1722    
1723          // next 2 bytes unknown          // next 2 bytes unknown
1724    
1725          memcpy(&pData[117], &VelocityUpperLimit, 1);          pData[124] = VelocityUpperLimit;
1726    
1727          // next 3 bytes unknown          // next 3 bytes unknown
1728    
1729          memcpy(&pData[121], &ReleaseTriggerDecay, 1);          pData[128] = ReleaseTriggerDecay;
1730    
1731          // next 2 bytes unknown          // next 2 bytes unknown
1732    
1733          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7          const uint8_t eg1hold = (EG1Hold) ? 0x80 : 0x00; // bit 7
1734          memcpy(&pData[124], &eg1hold, 1);          pData[131] = eg1hold;
1735    
1736          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */          const uint8_t vcfcutoff = (VCFEnabled) ? 0x80 : 0x00 |  /* bit 7 */
1737                                    (VCFCutoff)  ? 0x7f : 0x00;   /* lower 7 bits */                                    (VCFCutoff & 0x7f);   /* lower 7 bits */
1738          memcpy(&pData[125], &vcfcutoff, 1);          pData[132] = vcfcutoff;
1739    
1740          memcpy(&pData[126], &VCFCutoffController, 1);          pData[133] = VCFCutoffController;
1741    
1742          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfvelscale = (VCFCutoffControllerInvert) ? 0x80 : 0x00 | /* bit 7 */
1743                                      (VCFVelocityScale) ? 0x7f : 0x00; /* lower 7 bits */                                      (VCFVelocityScale & 0x7f); /* lower 7 bits */
1744          memcpy(&pData[127], &vcfvelscale, 1);          pData[134] = vcfvelscale;
1745    
1746          // next byte unknown          // next byte unknown
1747    
1748          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */          const uint8_t vcfresonance = (VCFResonanceDynamic) ? 0x00 : 0x80 | /* bit 7 */
1749                                       (VCFResonance) ? 0x7f : 0x00; /* lower 7 bits */                                       (VCFResonance & 0x7f); /* lower 7 bits */
1750          memcpy(&pData[129], &vcfresonance, 1);          pData[136] = vcfresonance;
1751    
1752          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */          const uint8_t vcfbreakpoint = (VCFKeyboardTracking) ? 0x80 : 0x00 | /* bit 7 */
1753                                        (VCFKeyboardTrackingBreakpoint) ? 0x7f : 0x00; /* lower 7 bits */                                        (VCFKeyboardTrackingBreakpoint & 0x7f); /* lower 7 bits */
1754          memcpy(&pData[130], &vcfbreakpoint, 1);          pData[137] = vcfbreakpoint;
1755    
1756          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |          const uint8_t vcfvelocity = VCFVelocityDynamicRange % 5 |
1757                                      VCFVelocityCurve * 5;                                      VCFVelocityCurve * 5;
1758          memcpy(&pData[131], &vcfvelocity, 1);          pData[138] = vcfvelocity;
1759    
1760          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;          const uint8_t vcftype = (VCFType == vcf_type_lowpassturbo) ? vcf_type_lowpass : VCFType;
1761          memcpy(&pData[132], &vcftype, 1);          pData[139] = vcftype;
1762    
1763            if (chunksize >= 148) {
1764                memcpy(&pData[140], DimensionUpperLimits, 8);
1765            }
1766      }      }
1767    
1768      // 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 1968  namespace { Line 2006  namespace {
2006              delete pVelocityTables;              delete pVelocityTables;
2007              pVelocityTables = NULL;              pVelocityTables = NULL;
2008          }          }
2009            if (VelocityTable) delete[] VelocityTable;
2010      }      }
2011    
2012      /**      /**
# Line 2065  namespace { Line 2104  namespace {
2104  // *  // *
2105    
2106      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {      Region::Region(Instrument* pInstrument, RIFF::List* rgnList) : DLS::Region((DLS::Instrument*) pInstrument, rgnList) {
2107            pInfo->UseFixedLengthStrings = true;
2108    
2109          // Initialization          // Initialization
2110          Dimensions = 0;          Dimensions = 0;
2111          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
# Line 2092  namespace { Line 2133  namespace {
2133                      pDimensionDefinitions[i].bits       = 0;                      pDimensionDefinitions[i].bits       = 0;
2134                      pDimensionDefinitions[i].zones      = 0;                      pDimensionDefinitions[i].zones      = 0;
2135                      pDimensionDefinitions[i].split_type = split_type_bit;                      pDimensionDefinitions[i].split_type = split_type_bit;
                     pDimensionDefinitions[i].ranges     = NULL;  
2136                      pDimensionDefinitions[i].zone_size  = 0;                      pDimensionDefinitions[i].zone_size  = 0;
2137                  }                  }
2138                  else { // active dimension                  else { // active dimension
2139                      pDimensionDefinitions[i].dimension = dimension;                      pDimensionDefinitions[i].dimension = dimension;
2140                      pDimensionDefinitions[i].bits      = bits;                      pDimensionDefinitions[i].bits      = bits;
2141                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)                      pDimensionDefinitions[i].zones     = zones ? zones : 0x01 << bits; // = pow(2,bits)
2142                      pDimensionDefinitions[i].split_type = (dimension == dimension_layer ||                      pDimensionDefinitions[i].split_type = __resolveSplitType(dimension);
2143                                                             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;  
2144                      Dimensions++;                      Dimensions++;
2145    
2146                      // if this is a layer dimension, remember the amount of layers                      // if this is a layer dimension, remember the amount of layers
# Line 2116  namespace { Line 2148  namespace {
2148                  }                  }
2149                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition                  _3lnk->SetPos(3, RIFF::stream_curpos); // jump forward to next dimension definition
2150              }              }
2151                for (int i = dimensionBits ; i < 8 ; i++) pDimensionDefinitions[i].bits = 0;
2152    
2153              // 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,
2154              for (uint i = 0; i < Dimensions; i++) {              // update the VelocityTables in the dimension regions
2155                  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);  
                     }  
                 }  
             }  
2156    
2157              // 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();  
2158              if (file->pVersion && file->pVersion->major == 3)              if (file->pVersion && file->pVersion->major == 3)
2159                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure                  _3lnk->SetPos(68); // version 3 has a different 3lnk structure
2160              else              else
# Line 2144  namespace { Line 2163  namespace {
2163              // load sample references              // load sample references
2164              for (uint i = 0; i < DimensionRegions; i++) {              for (uint i = 0; i < DimensionRegions; i++) {
2165                  uint32_t wavepoolindex = _3lnk->ReadUint32();                  uint32_t wavepoolindex = _3lnk->ReadUint32();
2166                  pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);                  if (file->pWavePoolTable) pDimensionRegions[i]->pSample = GetSampleFromWavePool(wavepoolindex);
2167              }              }
2168                GetSample(); // load global region sample reference
2169            } else {
2170                DimensionRegions = 0;
2171          }          }
2172    
2173          // make sure there is at least one dimension region          // make sure there is at least one dimension region
# Line 2168  namespace { Line 2190  namespace {
2190       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
2191       */       */
2192      void Region::UpdateChunks() {      void Region::UpdateChunks() {
2193            // in the gig format we don't care about the Region's sample reference
2194            // but we still have to provide some existing one to not corrupt the
2195            // file, so to avoid the latter we simply always assign the sample of
2196            // the first dimension region of this region
2197            pSample = pDimensionRegions[0]->pSample;
2198    
2199          // first update base class's chunks          // first update base class's chunks
2200          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks();
2201    
# Line 2189  namespace { Line 2217  namespace {
2217    
2218          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
2219          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();          uint8_t* pData = (uint8_t*) _3lnk->LoadChunkData();
2220            store32(&pData[0], DimensionRegions);
2221          for (int i = 0; i < iMaxDimensions; i++) {          for (int i = 0; i < iMaxDimensions; i++) {
2222              pData[i * 8]     = (uint8_t) pDimensionDefinitions[i].dimension;              pData[4 + i * 8] = (uint8_t) pDimensionDefinitions[i].dimension;
2223              pData[i * 8 + 1] = pDimensionDefinitions[i].bits;              pData[5 + i * 8] = pDimensionDefinitions[i].bits;
2224              // next 2 bytes unknown              // next 2 bytes unknown
2225              pData[i * 8 + 4] = pDimensionDefinitions[i].zones;              pData[8 + i * 8] = pDimensionDefinitions[i].zones;
2226              // next 3 bytes unknown              // next 3 bytes unknown
2227          }          }
2228    
# Line 2213  namespace { Line 2242  namespace {
2242                  }                  }
2243                  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");
2244              }              }
2245              memcpy(&pData[iWavePoolOffset + i * 4], &iWaveIndex, 4);              store32(&pData[iWavePoolOffset + i * 4], iWaveIndex);
2246          }          }
2247      }      }
2248    
# Line 2233  namespace { Line 2262  namespace {
2262          }          }
2263      }      }
2264    
2265      void Region::UpdateVelocityTable(dimension_def_t* pDimDef) {      void Region::UpdateVelocityTable() {
2266          // get dimension's index          // get velocity dimension's index
2267          int iDimensionNr = -1;          int veldim = -1;
2268          for (int i = 0; i < Dimensions; i++) {          for (int i = 0 ; i < Dimensions ; i++) {
2269              if (&pDimensionDefinitions[i] == pDimDef) {              if (pDimensionDefinitions[i].dimension == gig::dimension_velocity) {
2270                  iDimensionNr = i;                  veldim = i;
2271                  break;                  break;
2272              }              }
2273          }          }
2274          if (iDimensionNr < 0) throw gig::Exception("Invalid dimension_def_t pointer");          if (veldim == -1) return;
2275    
2276            int step = 1;
2277            for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
2278            int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
2279            int end = step * pDimensionDefinitions[veldim].zones;
2280    
2281            // loop through all dimension regions for all dimensions except the velocity dimension
2282            int dim[8] = { 0 };
2283            for (int i = 0 ; i < DimensionRegions ; i++) {
2284    
2285                if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
2286                    pDimensionRegions[i]->VelocityUpperLimit) {
2287                    // create the velocity table
2288                    uint8_t* table = pDimensionRegions[i]->VelocityTable;
2289                    if (!table) {
2290                        table = new uint8_t[128];
2291                        pDimensionRegions[i]->VelocityTable = table;
2292                    }
2293                    int tableidx = 0;
2294                    int velocityZone = 0;
2295                    if (pDimensionRegions[i]->DimensionUpperLimits[veldim]) { // gig3
2296                        for (int k = i ; k < end ; k += step) {
2297                            DimensionRegion *d = pDimensionRegions[k];
2298                            for (; tableidx <= d->DimensionUpperLimits[veldim] ; tableidx++) table[tableidx] = velocityZone;
2299                            velocityZone++;
2300                        }
2301                    } else { // gig2
2302                        for (int k = i ; k < end ; k += step) {
2303                            DimensionRegion *d = pDimensionRegions[k];
2304                            for (; tableidx <= d->VelocityUpperLimit ; tableidx++) table[tableidx] = velocityZone;
2305                            velocityZone++;
2306                        }
2307                    }
2308                } else {
2309                    if (pDimensionRegions[i]->VelocityTable) {
2310                        delete[] pDimensionRegions[i]->VelocityTable;
2311                        pDimensionRegions[i]->VelocityTable = 0;
2312                    }
2313                }
2314    
2315          uint8_t bits[8] = { 0 };              int j;
2316          int previousUpperLimit = -1;              int shift = 0;
2317          for (int velocityZone = 0; velocityZone < pDimDef->zones; velocityZone++) {              for (j = 0 ; j < Dimensions ; j++) {
2318              bits[iDimensionNr] = velocityZone;                  if (j == veldim) i += skipveldim; // skip velocity dimension
2319              DimensionRegion* pDimRegion = GetDimensionRegionByBit(bits);                  else {
2320                        dim[j]++;
2321              pDimDef->ranges[velocityZone].low  = previousUpperLimit + 1;                      if (dim[j] < pDimensionDefinitions[j].zones) break;
2322              pDimDef->ranges[velocityZone].high = pDimRegion->VelocityUpperLimit;                      else {
2323              previousUpperLimit = pDimDef->ranges[velocityZone].high;                          // skip unused dimension regions
2324              // fill velocity table                          dim[j] = 0;
2325              for (int i = pDimDef->ranges[velocityZone].low; i <= pDimDef->ranges[velocityZone].high; i++) {                          i += ((1 << pDimensionDefinitions[j].bits) -
2326                  VelocityTable[i] = velocityZone;                                pDimensionDefinitions[j].zones) << shift;
2327                        }
2328                    }
2329                    shift += pDimensionDefinitions[j].bits;
2330              }              }
2331                if (j == Dimensions) break;
2332          }          }
2333      }      }
2334    
# Line 2298  namespace { Line 2370  namespace {
2370          // assign definition of new dimension          // assign definition of new dimension
2371          pDimensionDefinitions[Dimensions] = *pDimDef;          pDimensionDefinitions[Dimensions] = *pDimDef;
2372    
2373            // auto correct certain dimension definition fields (where possible)
2374            pDimensionDefinitions[Dimensions].split_type  =
2375                __resolveSplitType(pDimensionDefinitions[Dimensions].dimension);
2376            pDimensionDefinitions[Dimensions].zone_size =
2377                __resolveZoneSize(pDimensionDefinitions[Dimensions]);
2378    
2379          // create new dimension region(s) for this new dimension          // create new dimension region(s) for this new dimension
2380          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {          for (int i = 1 << iCurrentBits; i < 1 << iNewBits; i++) {
2381              //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 2311  namespace { Line 2389  namespace {
2389          // if this is a layer dimension, update 'Layers' attribute          // if this is a layer dimension, update 'Layers' attribute
2390          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;          if (pDimDef->dimension == dimension_layer) Layers = pDimDef->zones;
2391    
2392          // 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);  
         }  
2393      }      }
2394    
2395      /** @brief Delete an existing dimension.      /** @brief Delete an existing dimension.
# Line 2385  namespace { Line 2459  namespace {
2459          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;          pDimensionDefinitions[Dimensions - 1].dimension = dimension_none;
2460          pDimensionDefinitions[Dimensions - 1].bits      = 0;          pDimensionDefinitions[Dimensions - 1].bits      = 0;
2461          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;  
         }  
2462    
2463          Dimensions--;          Dimensions--;
2464    
# Line 2397  namespace { Line 2467  namespace {
2467      }      }
2468    
2469      Region::~Region() {      Region::~Region() {
         for (uint i = 0; i < Dimensions; i++) {  
             if (pDimensionDefinitions[i].ranges) delete[] pDimensionDefinitions[i].ranges;  
         }  
2470          for (int i = 0; i < 256; i++) {          for (int i = 0; i < 256; i++) {
2471              if (pDimensionRegions[i]) delete pDimensionRegions[i];              if (pDimensionRegions[i]) delete pDimensionRegions[i];
2472          }          }
# Line 2424  namespace { Line 2491  namespace {
2491       * @see             Dimensions       * @see             Dimensions
2492       */       */
2493      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
2494          uint8_t bits[8] = { 0 };          uint8_t bits;
2495            int veldim = -1;
2496            int velbitpos;
2497            int bitpos = 0;
2498            int dimregidx = 0;
2499          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
2500              bits[i] = DimValues[i];              if (pDimensionDefinitions[i].dimension == dimension_velocity) {
2501              switch (pDimensionDefinitions[i].split_type) {                  // the velocity dimension must be handled after the other dimensions
2502                  case split_type_normal:                  veldim = i;
2503                      bits[i] = uint8_t(bits[i] / pDimensionDefinitions[i].zone_size);                  velbitpos = bitpos;
2504                      break;              } else {
2505                  case split_type_customvelocity:                  switch (pDimensionDefinitions[i].split_type) {
2506                      bits[i] = VelocityTable[bits[i]];                      case split_type_normal:
2507                      break;                          if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
2508                  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
2509                      const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;                              for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
2510                      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;
2511                      break;                              }
2512                            } else {
2513                                // gig2: evenly sized zones
2514                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
2515                            }
2516                            break;
2517                        case split_type_bit: // the value is already the sought dimension bit number
2518                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
2519                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
2520                            break;
2521                    }
2522                    dimregidx |= bits << bitpos;
2523              }              }
2524                bitpos += pDimensionDefinitions[i].bits;
2525            }
2526            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
2527            if (veldim != -1) {
2528                // (dimreg is now the dimension region for the lowest velocity)
2529                if (dimreg->VelocityTable) // custom defined zone ranges
2530                    bits = dimreg->VelocityTable[DimValues[veldim]];
2531                else // normal split type
2532                    bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);
2533    
2534                dimregidx |= bits << velbitpos;
2535                dimreg = pDimensionRegions[dimregidx];
2536          }          }
2537          return GetDimensionRegionByBit(bits);          return dimreg;
2538      }      }
2539    
2540      /**      /**
# Line 2480  namespace { Line 2574  namespace {
2574      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {      Sample* Region::GetSampleFromWavePool(unsigned int WavePoolTableIndex, progress_t* pProgress) {
2575          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
2576          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
2577            if (!file->pWavePoolTable) return NULL;
2578          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
2579          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
2580          Sample* sample = file->GetFirstSample(pProgress);          Sample* sample = file->GetFirstSample(pProgress);
2581          while (sample) {          while (sample) {
2582              if (sample->ulWavePoolOffset == soughtoffset &&              if (sample->ulWavePoolOffset == soughtoffset &&
2583                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(pSample = sample);                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
2584              sample = file->GetNextSample();              sample = file->GetNextSample();
2585          }          }
2586          return NULL;          return NULL;
# Line 2497  namespace { Line 2592  namespace {
2592  // *  // *
2593    
2594      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) {
2595            pInfo->UseFixedLengthStrings = true;
2596    
2597          // Initialization          // Initialization
2598          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;          for (int i = 0; i < 128; i++) RegionKeyTable[i] = NULL;
2599    
# Line 2577  namespace { Line 2674  namespace {
2674          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);          if (!_3ewg)  _3ewg = lart->AddSubChunk(CHUNK_ID_3EWG, 12);
2675          // update '3ewg' RIFF chunk          // update '3ewg' RIFF chunk
2676          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();          uint8_t* pData = (uint8_t*) _3ewg->LoadChunkData();
2677          memcpy(&pData[0], &EffectSend, 2);          store16(&pData[0], EffectSend);
2678          memcpy(&pData[2], &Attenuation, 4);          store32(&pData[2], Attenuation);
2679          memcpy(&pData[6], &FineTune, 2);          store16(&pData[6], FineTune);
2680          memcpy(&pData[8], &PitchbendRange, 2);          store16(&pData[8], PitchbendRange);
2681          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |          const uint8_t dimkeystart = (PianoReleaseMode) ? 0x01 : 0x00 |
2682                                      DimensionKeyRange.low << 1;                                      DimensionKeyRange.low << 1;
2683          memcpy(&pData[10], &dimkeystart, 1);          pData[10] = dimkeystart;
2684          memcpy(&pData[11], &DimensionKeyRange.high, 1);          pData[11] = DimensionKeyRange.high;
2685      }      }
2686    
2687      /**      /**
# Line 2655  namespace { Line 2752  namespace {
2752    
2753    
2754    
2755    // *************** Group ***************
2756    // *
2757    
2758        /** @brief Constructor.
2759         *
2760         * @param file   - pointer to the gig::File object
2761         * @param ck3gnm - pointer to 3gnm chunk associated with this group or
2762         *                 NULL if this is a new Group
2763         */
2764        Group::Group(File* file, RIFF::Chunk* ck3gnm) {
2765            pFile      = file;
2766            pNameChunk = ck3gnm;
2767            ::LoadString(pNameChunk, Name);
2768        }
2769    
2770        Group::~Group() {
2771            // remove the chunk associated with this group (if any)
2772            if (pNameChunk) pNameChunk->GetParent()->DeleteSubChunk(pNameChunk);
2773        }
2774    
2775        /** @brief Update chunks with current group settings.
2776         *
2777         * Apply current Group field values to the respective chunks. You have
2778         * to call File::Save() to make changes persistent.
2779         *
2780         * Usually there is absolutely no need to call this method explicitly.
2781         * It will be called automatically when File::Save() was called.
2782         */
2783        void Group::UpdateChunks() {
2784            // make sure <3gri> and <3gnl> list chunks exist
2785            RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
2786            if (!_3gri) _3gri = pFile->pRIFF->AddSubList(LIST_TYPE_3GRI);
2787            RIFF::List* _3gnl = _3gri->GetSubList(LIST_TYPE_3GNL);
2788            if (!_3gnl) _3gnl = pFile->pRIFF->AddSubList(LIST_TYPE_3GNL);
2789            // now store the name of this group as <3gnm> chunk as subchunk of the <3gnl> list chunk
2790            ::SaveString(CHUNK_ID_3GNM, pNameChunk, _3gnl, Name, String("Unnamed Group"), true, 64);
2791        }
2792    
2793        /**
2794         * Returns the first Sample of this Group. You have to call this method
2795         * once before you use GetNextSample().
2796         *
2797         * <b>Notice:</b> this method might block for a long time, in case the
2798         * samples of this .gig file were not scanned yet
2799         *
2800         * @returns  pointer address to first Sample or NULL if there is none
2801         *           applied to this Group
2802         * @see      GetNextSample()
2803         */
2804        Sample* Group::GetFirstSample() {
2805            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2806            for (Sample* pSample = pFile->GetFirstSample(); pSample; pSample = pFile->GetNextSample()) {
2807                if (pSample->GetGroup() == this) return pSample;
2808            }
2809            return NULL;
2810        }
2811    
2812        /**
2813         * Returns the next Sample of the Group. You have to call
2814         * GetFirstSample() once before you can use this method. By calling this
2815         * method multiple times it iterates through the Samples assigned to
2816         * this Group.
2817         *
2818         * @returns  pointer address to the next Sample of this Group or NULL if
2819         *           end reached
2820         * @see      GetFirstSample()
2821         */
2822        Sample* Group::GetNextSample() {
2823            // FIXME: lazy und unsafe implementation, should be an autonomous iterator
2824            for (Sample* pSample = pFile->GetNextSample(); pSample; pSample = pFile->GetNextSample()) {
2825                if (pSample->GetGroup() == this) return pSample;
2826            }
2827            return NULL;
2828        }
2829    
2830        /**
2831         * Move Sample given by \a pSample from another Group to this Group.
2832         */
2833        void Group::AddSample(Sample* pSample) {
2834            pSample->pGroup = this;
2835        }
2836    
2837        /**
2838         * Move all members of this group to another group (preferably the 1st
2839         * one except this). This method is called explicitly by
2840         * File::DeleteGroup() thus when a Group was deleted. This code was
2841         * intentionally not placed in the destructor!
2842         */
2843        void Group::MoveAll() {
2844            // get "that" other group first
2845            Group* pOtherGroup = NULL;
2846            for (pOtherGroup = pFile->GetFirstGroup(); pOtherGroup; pOtherGroup = pFile->GetNextGroup()) {
2847                if (pOtherGroup != this) break;
2848            }
2849            if (!pOtherGroup) throw Exception(
2850                "Could not move samples to another group, since there is no "
2851                "other Group. This is a bug, report it!"
2852            );
2853            // now move all samples of this group to the other group
2854            for (Sample* pSample = GetFirstSample(); pSample; pSample = GetNextSample()) {
2855                pOtherGroup->AddSample(pSample);
2856            }
2857        }
2858    
2859    
2860    
2861  // *************** File ***************  // *************** File ***************
2862  // *  // *
2863    
2864      File::File() : DLS::File() {      File::File() : DLS::File() {
2865            pGroups = NULL;
2866            pInfo->UseFixedLengthStrings = true;
2867      }      }
2868    
2869      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
2870            pGroups = NULL;
2871            pInfo->UseFixedLengthStrings = true;
2872      }      }
2873    
2874      File::~File() {      File::~File() {
2875          // free extension files          if (pGroups) {
2876          for (std::list<RIFF::File*>::iterator i = ExtensionFiles.begin() ; i != ExtensionFiles.end() ; i++)              std::list<Group*>::iterator iter = pGroups->begin();
2877              delete *i;              std::list<Group*>::iterator end  = pGroups->end();
2878                while (iter != end) {
2879                    delete *iter;
2880                    ++iter;
2881                }
2882                delete pGroups;
2883            }
2884      }      }
2885    
2886      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 2713  namespace { Line 2926  namespace {
2926          if (!pSamples || !pSamples->size()) 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");
2927          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);          SampleList::iterator iter = find(pSamples->begin(), pSamples->end(), (DLS::Sample*) pSample);
2928          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");
2929            if (SamplesIterator != pSamples->end() && *SamplesIterator == pSample) ++SamplesIterator; // avoid iterator invalidation
2930          pSamples->erase(iter);          pSamples->erase(iter);
2931          delete pSample;          delete pSample;
2932      }      }
# Line 2722  namespace { Line 2936  namespace {
2936      }      }
2937    
2938      void File::LoadSamples(progress_t* pProgress) {      void File::LoadSamples(progress_t* pProgress) {
2939            // Groups must be loaded before samples, because samples will try
2940            // to resolve the group they belong to
2941            if (!pGroups) LoadGroups();
2942    
2943          if (!pSamples) pSamples = new SampleList;          if (!pSamples) pSamples = new SampleList;
2944    
2945          RIFF::File* file = pRIFF;          RIFF::File* file = pRIFF;
# Line 2845  namespace { Line 3063  namespace {
3063       * have to call Save() to make this persistent to the file.       * have to call Save() to make this persistent to the file.
3064       *       *
3065       * @param pInstrument - instrument to delete       * @param pInstrument - instrument to delete
3066       * @throws gig::Excption if given instrument could not be found       * @throws gig::Exception if given instrument could not be found
3067       */       */
3068      void File::DeleteInstrument(Instrument* pInstrument) {      void File::DeleteInstrument(Instrument* pInstrument) {
3069          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");
# Line 2885  namespace { Line 3103  namespace {
3103          }          }
3104      }      }
3105    
3106        Group* File::GetFirstGroup() {
3107            if (!pGroups) LoadGroups();
3108            // there must always be at least one group
3109            GroupsIterator = pGroups->begin();
3110            return *GroupsIterator;
3111        }
3112    
3113        Group* File::GetNextGroup() {
3114            if (!pGroups) return NULL;
3115            ++GroupsIterator;
3116            return (GroupsIterator == pGroups->end()) ? NULL : *GroupsIterator;
3117        }
3118    
3119        /**
3120         * Returns the group with the given index.
3121         *
3122         * @param index - number of the sought group (0..n)
3123         * @returns sought group or NULL if there's no such group
3124         */
3125        Group* File::GetGroup(uint index) {
3126            if (!pGroups) LoadGroups();
3127            GroupsIterator = pGroups->begin();
3128            for (uint i = 0; GroupsIterator != pGroups->end(); i++) {
3129                if (i == index) return *GroupsIterator;
3130                ++GroupsIterator;
3131            }
3132            return NULL;
3133        }
3134    
3135        Group* File::AddGroup() {
3136            if (!pGroups) LoadGroups();
3137            // there must always be at least one group
3138            __ensureMandatoryChunksExist();
3139            Group* pGroup = new Group(this, NULL);
3140            pGroups->push_back(pGroup);
3141            return pGroup;
3142        }
3143    
3144        /** @brief Delete a group and its samples.
3145         *
3146         * This will delete the given Group object and all the samples that
3147         * belong to this group from the gig file. You have to call Save() to
3148         * make this persistent to the file.
3149         *
3150         * @param pGroup - group to delete
3151         * @throws gig::Exception if given group could not be found
3152         */
3153        void File::DeleteGroup(Group* pGroup) {
3154            if (!pGroups) LoadGroups();
3155            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3156            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3157            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3158            // delete all members of this group
3159            for (Sample* pSample = pGroup->GetFirstSample(); pSample; pSample = pGroup->GetNextSample()) {
3160                DeleteSample(pSample);
3161            }
3162            // now delete this group object
3163            pGroups->erase(iter);
3164            delete pGroup;
3165        }
3166    
3167        /** @brief Delete a group.
3168         *
3169         * This will delete the given Group object from the gig file. All the
3170         * samples that belong to this group will not be deleted, but instead
3171         * be moved to another group. You have to call Save() to make this
3172         * persistent to the file.
3173         *
3174         * @param pGroup - group to delete
3175         * @throws gig::Exception if given group could not be found
3176         */
3177        void File::DeleteGroupOnly(Group* pGroup) {
3178            if (!pGroups) LoadGroups();
3179            std::list<Group*>::iterator iter = find(pGroups->begin(), pGroups->end(), pGroup);
3180            if (iter == pGroups->end()) throw gig::Exception("Could not delete group, could not find given group");
3181            if (pGroups->size() == 1) throw gig::Exception("Cannot delete group, there must be at least one default group!");
3182            // move all members of this group to another group
3183            pGroup->MoveAll();
3184            pGroups->erase(iter);
3185            delete pGroup;
3186        }
3187    
3188        void File::LoadGroups() {
3189            if (!pGroups) pGroups = new std::list<Group*>;
3190            // try to read defined groups from file
3191            RIFF::List* lst3gri = pRIFF->GetSubList(LIST_TYPE_3GRI);
3192            if (lst3gri) {
3193                RIFF::List* lst3gnl = lst3gri->GetSubList(LIST_TYPE_3GNL);
3194                if (lst3gnl) {
3195                    RIFF::Chunk* ck = lst3gnl->GetFirstSubChunk();
3196                    while (ck) {
3197                        if (ck->GetChunkID() == CHUNK_ID_3GNM) {
3198                            pGroups->push_back(new Group(this, ck));
3199                        }
3200                        ck = lst3gnl->GetNextSubChunk();
3201                    }
3202                }
3203            }
3204            // if there were no group(s), create at least the mandatory default group
3205            if (!pGroups->size()) {
3206                Group* pGroup = new Group(this, NULL);
3207                pGroup->Name = "Default Group";
3208                pGroups->push_back(pGroup);
3209            }
3210        }
3211    
3212        /**
3213         * Apply all the gig file's current instruments, samples, groups and settings
3214         * to the respective RIFF chunks. You have to call Save() to make changes
3215         * persistent.
3216         *
3217         * Usually there is absolutely no need to call this method explicitly.
3218         * It will be called automatically when File::Save() was called.
3219         *
3220         * @throws Exception - on errors
3221         */
3222        void File::UpdateChunks() {
3223            // first update base class's chunks
3224            DLS::File::UpdateChunks();
3225    
3226            // update group's chunks
3227            if (pGroups) {
3228                std::list<Group*>::iterator iter = pGroups->begin();
3229                std::list<Group*>::iterator end  = pGroups->end();
3230                for (; iter != end; ++iter) {
3231                    (*iter)->UpdateChunks();
3232                }
3233            }
3234        }
3235    
3236    
3237    
3238  // *************** Exception ***************  // *************** Exception ***************

Legend:
Removed from v.823  
changed lines
  Added in v.1179

  ViewVC Help
Powered by ViewVC