/[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 2547 by schoenebeck, Tue May 13 11:17:24 2014 UTC revision 2923 by schoenebeck, Sat May 21 08:54:32 2016 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   libgig - C++ cross-platform Gigasampler format file access library    *   *   libgig - C++ cross-platform Gigasampler format file access library    *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003-2014 by Christian Schoenebeck                      *   *   Copyright (C) 2003-2016 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 28  Line 28 
28  #include <algorithm>  #include <algorithm>
29  #include <math.h>  #include <math.h>
30  #include <iostream>  #include <iostream>
31    #include <assert.h>
32    
33    /// libgig's current file format version (for extending the original Giga file
34    /// format with libgig's own custom data / custom features).
35    #define GIG_FILE_EXT_VERSION    2
36    
37  /// Initial size of the sample buffer which is used for decompression of  /// Initial size of the sample buffer which is used for decompression of
38  /// compressed sample wave streams - this value should always be bigger than  /// compressed sample wave streams - this value should always be bigger than
# Line 52  Line 57 
57    
58  namespace gig {  namespace gig {
59    
 // *************** progress_t ***************  
 // *  
   
     progress_t::progress_t() {  
         callback    = NULL;  
         custom      = NULL;  
         __range_min = 0.0f;  
         __range_max = 1.0f;  
     }  
   
     // private helper function to convert progress of a subprocess into the global progress  
     static void __notify_progress(progress_t* pProgress, float subprogress) {  
         if (pProgress && pProgress->callback) {  
             const float totalrange    = pProgress->__range_max - pProgress->__range_min;  
             const float totalprogress = pProgress->__range_min + subprogress * totalrange;  
             pProgress->factor         = totalprogress;  
             pProgress->callback(pProgress); // now actually notify about the progress  
         }  
     }  
   
     // private helper function to divide a progress into subprogresses  
     static void __divide_progress(progress_t* pParentProgress, progress_t* pSubProgress, float totalTasks, float currentTask) {  
         if (pParentProgress && pParentProgress->callback) {  
             const float totalrange    = pParentProgress->__range_max - pParentProgress->__range_min;  
             pSubProgress->callback    = pParentProgress->callback;  
             pSubProgress->custom      = pParentProgress->custom;  
             pSubProgress->__range_min = pParentProgress->__range_min + totalrange * currentTask / totalTasks;  
             pSubProgress->__range_max = pSubProgress->__range_min + totalrange / totalTasks;  
         }  
     }  
   
   
60  // *************** Internal functions for sample decompression ***************  // *************** Internal functions for sample decompression ***************
61  // *  // *
62    
# Line 122  namespace { Line 95  namespace {
95      void Decompress16(int compressionmode, const unsigned char* params,      void Decompress16(int compressionmode, const unsigned char* params,
96                        int srcStep, int dstStep,                        int srcStep, int dstStep,
97                        const unsigned char* pSrc, int16_t* pDst,                        const unsigned char* pSrc, int16_t* pDst,
98                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
99                        unsigned long copysamples)                        file_offset_t copysamples)
100      {      {
101          switch (compressionmode) {          switch (compressionmode) {
102              case 0: // 16 bit uncompressed              case 0: // 16 bit uncompressed
# Line 159  namespace { Line 132  namespace {
132    
133      void Decompress24(int compressionmode, const unsigned char* params,      void Decompress24(int compressionmode, const unsigned char* params,
134                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,                        int dstStep, const unsigned char* pSrc, uint8_t* pDst,
135                        unsigned long currentframeoffset,                        file_offset_t currentframeoffset,
136                        unsigned long copysamples, int truncatedBits)                        file_offset_t copysamples, int truncatedBits)
137      {      {
138          int y, dy, ddy, dddy;          int y, dy, ddy, dddy;
139    
# Line 345  namespace { Line 318  namespace {
318  // *************** Sample ***************  // *************** Sample ***************
319  // *  // *
320    
321      unsigned int Sample::Instances = 0;      size_t       Sample::Instances = 0;
322      buffer_t     Sample::InternalDecompressionBuffer;      buffer_t     Sample::InternalDecompressionBuffer;
323    
324      /** @brief Constructor.      /** @brief Constructor.
# Line 366  namespace { Line 339  namespace {
339       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
340       *                         is located, 0 otherwise       *                         is located, 0 otherwise
341       */       */
342      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, file_offset_t WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
343          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
344              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
345              { 0, 0 }              { 0, 0 }
# Line 508  namespace { Line 481  namespace {
481          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
482          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
483          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
484          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
485          pOrig->SetPos(0);          pOrig->SetPos(0);
486          SetPos(0);          SetPos(0);
487          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
488                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
489          {          {
490              Write(buf, n);              Write(buf, n);
# Line 527  namespace { Line 500  namespace {
500       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
501       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
502       *       *
503         * @param pProgress - callback function for progress notification
504       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
505       *                        was provided yet       *                        was provided yet
506       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
507       */       */
508      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
509          // first update base class's chunks          // first update base class's chunks
510          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
511    
512          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
513          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 595  namespace { Line 569  namespace {
569      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
570          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
571          this->SamplesTotal = 0;          this->SamplesTotal = 0;
572          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
573    
574          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
575          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 611  namespace { Line 585  namespace {
585                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
586                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
587                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
588                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
589    
590                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
591                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 630  namespace { Line 604  namespace {
604    
605                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
606                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
607                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
608    
609                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
610                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 646  namespace { Line 620  namespace {
620    
621          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
622          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
623          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
624          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
625          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
626          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
627              FrameTable[i] = *iter;              FrameTable[i] = *iter;
628          }          }
# Line 689  namespace { Line 663  namespace {
663       *                      the cached sample data in bytes       *                      the cached sample data in bytes
664       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
665       */       */
666      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
667          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
668      }      }
669    
# Line 748  namespace { Line 722  namespace {
722       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
723       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
724       */       */
725      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
726          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
727          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
728          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
729          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
730          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
731          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 815  namespace { Line 789  namespace {
789       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
790       * other formats will fail!       * other formats will fail!
791       *       *
792       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
793       *                   greater than zero)       *                  greater than zero)
794       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
795       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
796       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
797       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
798       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
799       */       */
800      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
801          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
802          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
803      }      }
804    
805      /**      /**
# Line 849  namespace { Line 823  namespace {
823       * @returns            the new sample position       * @returns            the new sample position
824       * @see                Read()       * @see                Read()
825       */       */
826      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
827          if (Compressed) {          if (Compressed) {
828              switch (Whence) {              switch (Whence) {
829                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 867  namespace { Line 841  namespace {
841              }              }
842              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
843    
844              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
845              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
846              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
847              return this->SamplePos;              return this->SamplePos;
848          }          }
849          else { // not compressed          else { // not compressed
850              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
851              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
852              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
853                                              : result / this->FrameSize;                                              : result / this->FrameSize;
854          }          }
# Line 883  namespace { Line 857  namespace {
857      /**      /**
858       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
859       */       */
860      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
861          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
862          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
863      }      }
# Line 922  namespace { Line 896  namespace {
896       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
897       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
898       */       */
899      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
900                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
901          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
902          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
903    
904          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 962  namespace { Line 936  namespace {
936                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
937                                  // backward playback                                  // backward playback
938    
939                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
940                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
941                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
942                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
943    
944                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
945    
# Line 1013  namespace { Line 987  namespace {
987                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
988                          // backward playback                          // backward playback
989    
990                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
991                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
992                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
993                                                                                    : samplestoread;                                                                                    : samplestoread;
994                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
995    
996                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
997    
# Line 1097  namespace { Line 1071  namespace {
1071       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1072       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1073       */       */
1074      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1075          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1076          if (!Compressed) {          if (!Compressed) {
1077              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1112  namespace { Line 1086  namespace {
1086          else {          else {
1087              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1088              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1089              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1090                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1091                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1092                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1135  namespace { Line 1109  namespace {
1109              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1110    
1111              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1112                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1113                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1114    
1115                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1116    
# Line 1286  namespace { Line 1260  namespace {
1260       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1261       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1262       */       */
1263      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1264          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1265    
1266          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
# Line 1295  namespace { Line 1269  namespace {
1269              __resetCRC(crc);              __resetCRC(crc);
1270          }          }
1271          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1272          unsigned long res;          file_offset_t res;
1273          if (BitDepth == 24) {          if (BitDepth == 24) {
1274              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1275          } else { // 16 bit          } else { // 16 bit
# Line 1329  namespace { Line 1303  namespace {
1303       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1304       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1305       */       */
1306      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1307          buffer_t result;          buffer_t result;
1308          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1309                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1310          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1311          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1312          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1313          return result;          return result;
# Line 1383  namespace { Line 1357  namespace {
1357  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1358  // *  // *
1359    
1360      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1361      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1362    
1363      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1751  namespace { Line 1725  namespace {
1725       *       *
1726       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1727       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1728         *
1729         * @param pProgress - callback function for progress notification
1730       */       */
1731      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1732          // first update base class's chunk          // first update base class's chunk
1733          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1734    
1735          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1736          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 3025  namespace { Line 3001  namespace {
3001       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3002       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3003       *       *
3004         * @param pProgress - callback function for progress notification
3005       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3006       */       */
3007      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3008          // in the gig format we don't care about the Region's sample reference          // in the gig format we don't care about the Region's sample reference
3009          // but we still have to provide some existing one to not corrupt the          // but we still have to provide some existing one to not corrupt the
3010          // file, so to avoid the latter we simply always assign the sample of          // file, so to avoid the latter we simply always assign the sample of
# Line 3035  namespace { Line 3012  namespace {
3012          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3013    
3014          // first update base class's chunks          // first update base class's chunks
3015          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3016    
3017          // update dimension region's chunks          // update dimension region's chunks
3018          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3019              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3020          }          }
3021    
3022          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 3055  namespace { Line 3032  namespace {
3032              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3033    
3034              // move 3prg to last position              // move 3prg to last position
3035              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3036          }          }
3037    
3038          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 3129  namespace { Line 3106  namespace {
3106          int step = 1;          int step = 1;
3107          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3108          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3109    
3110          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3111          int dim[8] = { 0 };          int dim[8] = { 0 };
3112          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3113                const int end = i + step * pDimensionDefinitions[veldim].zones;
3114    
3115                // create a velocity table for all cases where the velocity zone is zero
3116              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3117                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3118                  // create the velocity table                  // create the velocity table
# Line 3165  namespace { Line 3143  namespace {
3143                  }                  }
3144              }              }
3145    
3146                // jump to the next case where the velocity zone is zero
3147              int j;              int j;
3148              int shift = 0;              int shift = 0;
3149              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3388  namespace { Line 3367  namespace {
3367          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3368      }      }
3369    
3370        /** @brief Delete one split zone of a dimension (decrement zone amount).
3371         *
3372         * Instead of deleting an entire dimensions, this method will only delete
3373         * one particular split zone given by @a zone of the Region's dimension
3374         * given by @a type. So this method will simply decrement the amount of
3375         * zones by one of the dimension in question. To be able to do that, the
3376         * respective dimension must exist on this Region and it must have at least
3377         * 3 zones. All DimensionRegion objects associated with the zone will be
3378         * deleted.
3379         *
3380         * @param type - identifies the dimension where a zone shall be deleted
3381         * @param zone - index of the dimension split zone that shall be deleted
3382         * @throws gig::Exception if requested zone could not be deleted
3383         */
3384        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3385            dimension_def_t* oldDef = GetDimensionDefinition(type);
3386            if (!oldDef)
3387                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3388            if (oldDef->zones <= 2)
3389                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3390            if (zone < 0 || zone >= oldDef->zones)
3391                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3392    
3393            const int newZoneSize = oldDef->zones - 1;
3394    
3395            // create a temporary Region which just acts as a temporary copy
3396            // container and will be deleted at the end of this function and will
3397            // also not be visible through the API during this process
3398            gig::Region* tempRgn = NULL;
3399            {
3400                // adding these temporary chunks is probably not even necessary
3401                Instrument* instr = static_cast<Instrument*>(GetParent());
3402                RIFF::List* pCkInstrument = instr->pCkInstrument;
3403                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3404                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3405                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3406                tempRgn = new Region(instr, rgn);
3407            }
3408    
3409            // copy this region's dimensions (with already the dimension split size
3410            // requested by the arguments of this method call) to the temporary
3411            // region, and don't use Region::CopyAssign() here for this task, since
3412            // it would also alter fast lookup helper variables here and there
3413            dimension_def_t newDef;
3414            for (int i = 0; i < Dimensions; ++i) {
3415                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3416                // is this the dimension requested by the method arguments? ...
3417                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3418                    def.zones = newZoneSize;
3419                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3420                    newDef = def;
3421                }
3422                tempRgn->AddDimension(&def);
3423            }
3424    
3425            // find the dimension index in the tempRegion which is the dimension
3426            // type passed to this method (paranoidly expecting different order)
3427            int tempReducedDimensionIndex = -1;
3428            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3429                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3430                    tempReducedDimensionIndex = d;
3431                    break;
3432                }
3433            }
3434    
3435            // copy dimension regions from this region to the temporary region
3436            for (int iDst = 0; iDst < 256; ++iDst) {
3437                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3438                if (!dstDimRgn) continue;
3439                std::map<dimension_t,int> dimCase;
3440                bool isValidZone = true;
3441                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3442                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3443                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3444                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3445                    baseBits += dstBits;
3446                    // there are also DimensionRegion objects of unused zones, skip them
3447                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3448                        isValidZone = false;
3449                        break;
3450                    }
3451                }
3452                if (!isValidZone) continue;
3453                // a bit paranoid: cope with the chance that the dimensions would
3454                // have different order in source and destination regions
3455                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3456                if (dimCase[type] >= zone) dimCase[type]++;
3457                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3458                dstDimRgn->CopyAssign(srcDimRgn);
3459                // if this is the upper most zone of the dimension passed to this
3460                // method, then correct (raise) its upper limit to 127
3461                if (newDef.split_type == split_type_normal && isLastZone)
3462                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3463            }
3464    
3465            // now tempRegion's dimensions and DimensionRegions basically reflect
3466            // what we wanted to get for this actual Region here, so we now just
3467            // delete and recreate the dimension in question with the new amount
3468            // zones and then copy back from tempRegion      
3469            DeleteDimension(oldDef);
3470            AddDimension(&newDef);
3471            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3472                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3473                if (!srcDimRgn) continue;
3474                std::map<dimension_t,int> dimCase;
3475                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3476                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3477                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3478                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3479                    baseBits += srcBits;
3480                }
3481                // a bit paranoid: cope with the chance that the dimensions would
3482                // have different order in source and destination regions
3483                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3484                if (!dstDimRgn) continue;
3485                dstDimRgn->CopyAssign(srcDimRgn);
3486            }
3487    
3488            // delete temporary region
3489            delete tempRgn;
3490    
3491            UpdateVelocityTable();
3492        }
3493    
3494        /** @brief Divide split zone of a dimension in two (increment zone amount).
3495         *
3496         * This will increment the amount of zones for the dimension (given by
3497         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3498         * in the middle of its zone range in two. So the two zones resulting from
3499         * the zone being splitted, will be an equivalent copy regarding all their
3500         * articulation informations and sample reference. The two zones will only
3501         * differ in their zone's upper limit
3502         * (DimensionRegion::DimensionUpperLimits).
3503         *
3504         * @param type - identifies the dimension where a zone shall be splitted
3505         * @param zone - index of the dimension split zone that shall be splitted
3506         * @throws gig::Exception if requested zone could not be splitted
3507         */
3508        void Region::SplitDimensionZone(dimension_t type, int zone) {
3509            dimension_def_t* oldDef = GetDimensionDefinition(type);
3510            if (!oldDef)
3511                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3512            if (zone < 0 || zone >= oldDef->zones)
3513                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3514    
3515            const int newZoneSize = oldDef->zones + 1;
3516    
3517            // create a temporary Region which just acts as a temporary copy
3518            // container and will be deleted at the end of this function and will
3519            // also not be visible through the API during this process
3520            gig::Region* tempRgn = NULL;
3521            {
3522                // adding these temporary chunks is probably not even necessary
3523                Instrument* instr = static_cast<Instrument*>(GetParent());
3524                RIFF::List* pCkInstrument = instr->pCkInstrument;
3525                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3526                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3527                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3528                tempRgn = new Region(instr, rgn);
3529            }
3530    
3531            // copy this region's dimensions (with already the dimension split size
3532            // requested by the arguments of this method call) to the temporary
3533            // region, and don't use Region::CopyAssign() here for this task, since
3534            // it would also alter fast lookup helper variables here and there
3535            dimension_def_t newDef;
3536            for (int i = 0; i < Dimensions; ++i) {
3537                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3538                // is this the dimension requested by the method arguments? ...
3539                if (def.dimension == type) { // ... if yes, increment zone amount by one
3540                    def.zones = newZoneSize;
3541                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3542                    newDef = def;
3543                }
3544                tempRgn->AddDimension(&def);
3545            }
3546    
3547            // find the dimension index in the tempRegion which is the dimension
3548            // type passed to this method (paranoidly expecting different order)
3549            int tempIncreasedDimensionIndex = -1;
3550            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3551                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3552                    tempIncreasedDimensionIndex = d;
3553                    break;
3554                }
3555            }
3556    
3557            // copy dimension regions from this region to the temporary region
3558            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3559                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3560                if (!srcDimRgn) continue;
3561                std::map<dimension_t,int> dimCase;
3562                bool isValidZone = true;
3563                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3564                    const int srcBits = pDimensionDefinitions[d].bits;
3565                    dimCase[pDimensionDefinitions[d].dimension] =
3566                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3567                    // there are also DimensionRegion objects for unused zones, skip them
3568                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3569                        isValidZone = false;
3570                        break;
3571                    }
3572                    baseBits += srcBits;
3573                }
3574                if (!isValidZone) continue;
3575                // a bit paranoid: cope with the chance that the dimensions would
3576                // have different order in source and destination regions            
3577                if (dimCase[type] > zone) dimCase[type]++;
3578                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3579                dstDimRgn->CopyAssign(srcDimRgn);
3580                // if this is the requested zone to be splitted, then also copy
3581                // the source DimensionRegion to the newly created target zone
3582                // and set the old zones upper limit lower
3583                if (dimCase[type] == zone) {
3584                    // lower old zones upper limit
3585                    if (newDef.split_type == split_type_normal) {
3586                        const int high =
3587                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3588                        int low = 0;
3589                        if (zone > 0) {
3590                            std::map<dimension_t,int> lowerCase = dimCase;
3591                            lowerCase[type]--;
3592                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3593                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3594                        }
3595                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3596                    }
3597                    // fill the newly created zone of the divided zone as well
3598                    dimCase[type]++;
3599                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3600                    dstDimRgn->CopyAssign(srcDimRgn);
3601                }
3602            }
3603    
3604            // now tempRegion's dimensions and DimensionRegions basically reflect
3605            // what we wanted to get for this actual Region here, so we now just
3606            // delete and recreate the dimension in question with the new amount
3607            // zones and then copy back from tempRegion      
3608            DeleteDimension(oldDef);
3609            AddDimension(&newDef);
3610            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3611                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3612                if (!srcDimRgn) continue;
3613                std::map<dimension_t,int> dimCase;
3614                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3615                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3616                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3617                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3618                    baseBits += srcBits;
3619                }
3620                // a bit paranoid: cope with the chance that the dimensions would
3621                // have different order in source and destination regions
3622                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3623                if (!dstDimRgn) continue;
3624                dstDimRgn->CopyAssign(srcDimRgn);
3625            }
3626    
3627            // delete temporary region
3628            delete tempRgn;
3629    
3630            UpdateVelocityTable();
3631        }
3632    
3633        /** @brief Change type of an existing dimension.
3634         *
3635         * Alters the dimension type of a dimension already existing on this
3636         * region. If there is currently no dimension on this Region with type
3637         * @a oldType, then this call with throw an Exception. Likewise there are
3638         * cases where the requested dimension type cannot be performed. For example
3639         * if the new dimension type shall be gig::dimension_samplechannel, and the
3640         * current dimension has more than 2 zones. In such cases an Exception is
3641         * thrown as well.
3642         *
3643         * @param oldType - identifies the existing dimension to be changed
3644         * @param newType - to which dimension type it should be changed to
3645         * @throws gig::Exception if requested change cannot be performed
3646         */
3647        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3648            if (oldType == newType) return;
3649            dimension_def_t* def = GetDimensionDefinition(oldType);
3650            if (!def)
3651                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3652            if (newType == dimension_samplechannel && def->zones != 2)
3653                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3654            if (GetDimensionDefinition(newType))
3655                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3656            def->dimension  = newType;
3657            def->split_type = __resolveSplitType(newType);
3658        }
3659    
3660        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3661            uint8_t bits[8] = {};
3662            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3663                 it != DimCase.end(); ++it)
3664            {
3665                for (int d = 0; d < Dimensions; ++d) {
3666                    if (pDimensionDefinitions[d].dimension == it->first) {
3667                        bits[d] = it->second;
3668                        goto nextDimCaseSlice;
3669                    }
3670                }
3671                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3672                nextDimCaseSlice:
3673                ; // noop
3674            }
3675            return GetDimensionRegionByBit(bits);
3676        }
3677    
3678      /**      /**
3679       * Searches in the current Region for a dimension of the given dimension       * Searches in the current Region for a dimension of the given dimension
3680       * type and returns the precise configuration of that dimension in this       * type and returns the precise configuration of that dimension in this
# Line 3461  namespace { Line 3748  namespace {
3748              }              }
3749              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3750          }          }
3751          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3752            if (!dimreg) return NULL;
3753          if (veldim != -1) {          if (veldim != -1) {
3754              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3755              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3756                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3757              else // normal split type              else // normal split type
3758                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3759    
3760              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3761              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3762                dimreg = pDimensionRegions[dimregidx & 255];
3763          }          }
3764          return dimreg;          return dimreg;
3765      }      }
3766    
3767        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3768            uint8_t bits;
3769            int veldim = -1;
3770            int velbitpos;
3771            int bitpos = 0;
3772            int dimregidx = 0;
3773            for (uint i = 0; i < Dimensions; i++) {
3774                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3775                    // the velocity dimension must be handled after the other dimensions
3776                    veldim = i;
3777                    velbitpos = bitpos;
3778                } else {
3779                    switch (pDimensionDefinitions[i].split_type) {
3780                        case split_type_normal:
3781                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3782                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3783                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3784                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3785                                }
3786                            } else {
3787                                // gig2: evenly sized zones
3788                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3789                            }
3790                            break;
3791                        case split_type_bit: // the value is already the sought dimension bit number
3792                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3793                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3794                            break;
3795                    }
3796                    dimregidx |= bits << bitpos;
3797                }
3798                bitpos += pDimensionDefinitions[i].bits;
3799            }
3800            dimregidx &= 255;
3801            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3802            if (!dimreg) return -1;
3803            if (veldim != -1) {
3804                // (dimreg is now the dimension region for the lowest velocity)
3805                if (dimreg->VelocityTable) // custom defined zone ranges
3806                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3807                else // normal split type
3808                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3809    
3810                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3811                dimregidx |= (bits & limiter_mask) << velbitpos;
3812                dimregidx &= 255;
3813            }
3814            return dimregidx;
3815        }
3816    
3817      /**      /**
3818       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3819       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 3513  namespace { Line 3852  namespace {
3852          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3853          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3854          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3855          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3856          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3857          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
3858          while (sample) {              uint64_t soughtoffset =
3859              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3860                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3861              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
3862                while (sample) {
3863                    if (sample->ullWavePoolOffset == soughtoffset)
3864                        return static_cast<gig::Sample*>(sample);
3865                    sample = file->GetNextSample();
3866                }
3867            } else {
3868                // use extension files and 32 bit wave pool offsets
3869                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3870                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3871                Sample* sample = file->GetFirstSample(pProgress);
3872                while (sample) {
3873                    if (sample->ullWavePoolOffset == soughtoffset &&
3874                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3875                    sample = file->GetNextSample();
3876                }
3877          }          }
3878          return NULL;          return NULL;
3879      }      }
# Line 3741  namespace { Line 4095  namespace {
4095          }          }
4096      }      }
4097    
4098    // *************** Script ***************
4099    // *
4100    
4101        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4102            pGroup = group;
4103            pChunk = ckScri;
4104            if (ckScri) { // object is loaded from file ...
4105                // read header
4106                uint32_t headerSize = ckScri->ReadUint32();
4107                Compression = (Compression_t) ckScri->ReadUint32();
4108                Encoding    = (Encoding_t) ckScri->ReadUint32();
4109                Language    = (Language_t) ckScri->ReadUint32();
4110                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4111                crc         = ckScri->ReadUint32();
4112                uint32_t nameSize = ckScri->ReadUint32();
4113                Name.resize(nameSize, ' ');
4114                for (int i = 0; i < nameSize; ++i)
4115                    Name[i] = ckScri->ReadUint8();
4116                // to handle potential future extensions of the header
4117                ckScri->SetPos(sizeof(int32_t) + headerSize);
4118                // read actual script data
4119                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4120                data.resize(scriptSize);
4121                for (int i = 0; i < scriptSize; ++i)
4122                    data[i] = ckScri->ReadUint8();
4123            } else { // this is a new script object, so just initialize it as such ...
4124                Compression = COMPRESSION_NONE;
4125                Encoding = ENCODING_ASCII;
4126                Language = LANGUAGE_NKSP;
4127                Bypass   = false;
4128                crc      = 0;
4129                Name     = "Unnamed Script";
4130            }
4131        }
4132    
4133        Script::~Script() {
4134        }
4135    
4136        /**
4137         * Returns the current script (i.e. as source code) in text format.
4138         */
4139        String Script::GetScriptAsText() {
4140            String s;
4141            s.resize(data.size(), ' ');
4142            memcpy(&s[0], &data[0], data.size());
4143            return s;
4144        }
4145    
4146        /**
4147         * Replaces the current script with the new script source code text given
4148         * by @a text.
4149         *
4150         * @param text - new script source code
4151         */
4152        void Script::SetScriptAsText(const String& text) {
4153            data.resize(text.size());
4154            memcpy(&data[0], &text[0], text.size());
4155        }
4156    
4157        /**
4158         * Apply this script to the respective RIFF chunks. You have to call
4159         * File::Save() to make changes persistent.
4160         *
4161         * Usually there is absolutely no need to call this method explicitly.
4162         * It will be called automatically when File::Save() was called.
4163         *
4164         * @param pProgress - callback function for progress notification
4165         */
4166        void Script::UpdateChunks(progress_t* pProgress) {
4167            // recalculate CRC32 check sum
4168            __resetCRC(crc);
4169            __calculateCRC(&data[0], data.size(), crc);
4170            __encodeCRC(crc);
4171            // make sure chunk exists and has the required size
4172            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4173            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4174            else pChunk->Resize(chunkSize);
4175            // fill the chunk data to be written to disk
4176            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4177            int pos = 0;
4178            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4179            pos += sizeof(int32_t);
4180            store32(&pData[pos], Compression);
4181            pos += sizeof(int32_t);
4182            store32(&pData[pos], Encoding);
4183            pos += sizeof(int32_t);
4184            store32(&pData[pos], Language);
4185            pos += sizeof(int32_t);
4186            store32(&pData[pos], Bypass ? 1 : 0);
4187            pos += sizeof(int32_t);
4188            store32(&pData[pos], crc);
4189            pos += sizeof(int32_t);
4190            store32(&pData[pos], Name.size());
4191            pos += sizeof(int32_t);
4192            for (int i = 0; i < Name.size(); ++i, ++pos)
4193                pData[pos] = Name[i];
4194            for (int i = 0; i < data.size(); ++i, ++pos)
4195                pData[pos] = data[i];
4196        }
4197    
4198        /**
4199         * Move this script from its current ScriptGroup to another ScriptGroup
4200         * given by @a pGroup.
4201         *
4202         * @param pGroup - script's new group
4203         */
4204        void Script::SetGroup(ScriptGroup* pGroup) {
4205            if (this->pGroup == pGroup) return;
4206            if (pChunk)
4207                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4208            this->pGroup = pGroup;
4209        }
4210    
4211        /**
4212         * Returns the script group this script currently belongs to. Each script
4213         * is a member of exactly one ScriptGroup.
4214         *
4215         * @returns current script group
4216         */
4217        ScriptGroup* Script::GetGroup() const {
4218            return pGroup;
4219        }
4220    
4221        void Script::RemoveAllScriptReferences() {
4222            File* pFile = pGroup->pFile;
4223            for (int i = 0; pFile->GetInstrument(i); ++i) {
4224                Instrument* instr = pFile->GetInstrument(i);
4225                instr->RemoveScript(this);
4226            }
4227        }
4228    
4229    // *************** ScriptGroup ***************
4230    // *
4231    
4232        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4233            pFile = file;
4234            pList = lstRTIS;
4235            pScripts = NULL;
4236            if (lstRTIS) {
4237                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4238                ::LoadString(ckName, Name);
4239            } else {
4240                Name = "Default Group";
4241            }
4242        }
4243    
4244        ScriptGroup::~ScriptGroup() {
4245            if (pScripts) {
4246                std::list<Script*>::iterator iter = pScripts->begin();
4247                std::list<Script*>::iterator end  = pScripts->end();
4248                while (iter != end) {
4249                    delete *iter;
4250                    ++iter;
4251                }
4252                delete pScripts;
4253            }
4254        }
4255    
4256        /**
4257         * Apply this script group to the respective RIFF chunks. You have to call
4258         * File::Save() to make changes persistent.
4259         *
4260         * Usually there is absolutely no need to call this method explicitly.
4261         * It will be called automatically when File::Save() was called.
4262         *
4263         * @param pProgress - callback function for progress notification
4264         */
4265        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4266            if (pScripts) {
4267                if (!pList)
4268                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4269    
4270                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4271                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4272    
4273                for (std::list<Script*>::iterator it = pScripts->begin();
4274                     it != pScripts->end(); ++it)
4275                {
4276                    (*it)->UpdateChunks(pProgress);
4277                }
4278            }
4279        }
4280    
4281        /** @brief Get instrument script.
4282         *
4283         * Returns the real-time instrument script with the given index.
4284         *
4285         * @param index - number of the sought script (0..n)
4286         * @returns sought script or NULL if there's no such script
4287         */
4288        Script* ScriptGroup::GetScript(uint index) {
4289            if (!pScripts) LoadScripts();
4290            std::list<Script*>::iterator it = pScripts->begin();
4291            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4292                if (i == index) return *it;
4293            return NULL;
4294        }
4295    
4296        /** @brief Add new instrument script.
4297         *
4298         * Adds a new real-time instrument script to the file. The script is not
4299         * actually used / executed unless it is referenced by an instrument to be
4300         * used. This is similar to samples, which you can add to a file, without
4301         * an instrument necessarily actually using it.
4302         *
4303         * You have to call Save() to make this persistent to the file.
4304         *
4305         * @return new empty script object
4306         */
4307        Script* ScriptGroup::AddScript() {
4308            if (!pScripts) LoadScripts();
4309            Script* pScript = new Script(this, NULL);
4310            pScripts->push_back(pScript);
4311            return pScript;
4312        }
4313    
4314        /** @brief Delete an instrument script.
4315         *
4316         * This will delete the given real-time instrument script. References of
4317         * instruments that are using that script will be removed accordingly.
4318         *
4319         * You have to call Save() to make this persistent to the file.
4320         *
4321         * @param pScript - script to delete
4322         * @throws gig::Exception if given script could not be found
4323         */
4324        void ScriptGroup::DeleteScript(Script* pScript) {
4325            if (!pScripts) LoadScripts();
4326            std::list<Script*>::iterator iter =
4327                find(pScripts->begin(), pScripts->end(), pScript);
4328            if (iter == pScripts->end())
4329                throw gig::Exception("Could not delete script, could not find given script");
4330            pScripts->erase(iter);
4331            pScript->RemoveAllScriptReferences();
4332            if (pScript->pChunk)
4333                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4334            delete pScript;
4335        }
4336    
4337        void ScriptGroup::LoadScripts() {
4338            if (pScripts) return;
4339            pScripts = new std::list<Script*>;
4340            if (!pList) return;
4341    
4342            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4343                 ck = pList->GetNextSubChunk())
4344            {
4345                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4346                    pScripts->push_back(new Script(this, ck));
4347                }
4348            }
4349        }
4350    
4351  // *************** Instrument ***************  // *************** Instrument ***************
4352  // *  // *
4353    
# Line 3763  namespace { Line 4370  namespace {
4370          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4371          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4372          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4373            pScriptRefs = NULL;
4374    
4375          // Loading          // Loading
4376          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 3823  namespace { Line 4431  namespace {
4431              }              }
4432          }          }
4433    
4434            // own gig format extensions
4435            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4436            if (lst3LS) {
4437                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4438                if (ckSCSL) {
4439                    int headerSize = ckSCSL->ReadUint32();
4440                    int slotCount  = ckSCSL->ReadUint32();
4441                    if (slotCount) {
4442                        int slotSize  = ckSCSL->ReadUint32();
4443                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4444                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4445                        for (int i = 0; i < slotCount; ++i) {
4446                            _ScriptPooolEntry e;
4447                            e.fileOffset = ckSCSL->ReadUint32();
4448                            e.bypass     = ckSCSL->ReadUint32() & 1;
4449                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4450                            scriptPoolFileOffsets.push_back(e);
4451                        }
4452                    }
4453                }
4454            }
4455    
4456          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4457      }      }
4458    
# Line 3843  namespace { Line 4473  namespace {
4473              delete pMidiRules[i];              delete pMidiRules[i];
4474          }          }
4475          delete[] pMidiRules;          delete[] pMidiRules;
4476            if (pScriptRefs) delete pScriptRefs;
4477      }      }
4478    
4479      /**      /**
# Line 3852  namespace { Line 4483  namespace {
4483       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4484       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4485       *       *
4486         * @param pProgress - callback function for progress notification
4487       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4488       */       */
4489      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4490          // first update base classes' chunks          // first update base classes' chunks
4491          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4492    
4493          // update Regions' chunks          // update Regions' chunks
4494          {          {
4495              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4496              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4497              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4498                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4499          }          }
4500    
4501          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 3898  namespace { Line 4530  namespace {
4530                  pMidiRules[i]->UpdateChunks(pData);                  pMidiRules[i]->UpdateChunks(pData);
4531              }              }
4532          }          }
4533    
4534            // own gig format extensions
4535           if (ScriptSlotCount()) {
4536               // make sure we have converted the original loaded script file
4537               // offsets into valid Script object pointers
4538               LoadScripts();
4539    
4540               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4541               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4542               const int slotCount = pScriptRefs->size();
4543               const int headerSize = 3 * sizeof(uint32_t);
4544               const int slotSize  = 2 * sizeof(uint32_t);
4545               const int totalChunkSize = headerSize + slotCount * slotSize;
4546               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4547               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4548               else ckSCSL->Resize(totalChunkSize);
4549               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4550               int pos = 0;
4551               store32(&pData[pos], headerSize);
4552               pos += sizeof(uint32_t);
4553               store32(&pData[pos], slotCount);
4554               pos += sizeof(uint32_t);
4555               store32(&pData[pos], slotSize);
4556               pos += sizeof(uint32_t);
4557               for (int i = 0; i < slotCount; ++i) {
4558                   // arbitrary value, the actual file offset will be updated in
4559                   // UpdateScriptFileOffsets() after the file has been resized
4560                   int bogusFileOffset = 0;
4561                   store32(&pData[pos], bogusFileOffset);
4562                   pos += sizeof(uint32_t);
4563                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4564                   pos += sizeof(uint32_t);
4565               }
4566           } else {
4567               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4568               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4569               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4570           }
4571        }
4572    
4573        void Instrument::UpdateScriptFileOffsets() {
4574           // own gig format extensions
4575           if (pScriptRefs && pScriptRefs->size() > 0) {
4576               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4577               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4578               const int slotCount = pScriptRefs->size();
4579               const int headerSize = 3 * sizeof(uint32_t);
4580               ckSCSL->SetPos(headerSize);
4581               for (int i = 0; i < slotCount; ++i) {
4582                   uint32_t fileOffset =
4583                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4584                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4585                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4586                   ckSCSL->WriteUint32(&fileOffset);
4587                   // jump over flags entry (containing the bypass flag)
4588                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4589               }
4590           }        
4591      }      }
4592    
4593      /**      /**
# Line 3967  namespace { Line 4657  namespace {
4657      }      }
4658    
4659      /**      /**
4660         * Move this instrument at the position before @arg dst.
4661         *
4662         * This method can be used to reorder the sequence of instruments in a
4663         * .gig file. This might be helpful especially on large .gig files which
4664         * contain a large number of instruments within the same .gig file. So
4665         * grouping such instruments to similar ones, can help to keep track of them
4666         * when working with such complex .gig files.
4667         *
4668         * When calling this method, this instrument will be removed from in its
4669         * current position in the instruments list and moved to the requested
4670         * target position provided by @param dst. You may also pass NULL as
4671         * argument to this method, in that case this intrument will be moved to the
4672         * very end of the .gig file's instrument list.
4673         *
4674         * You have to call Save() to make the order change persistent to the .gig
4675         * file.
4676         *
4677         * Currently this method is limited to moving the instrument within the same
4678         * .gig file. Trying to move it to another .gig file by calling this method
4679         * will throw an exception.
4680         *
4681         * @param dst - destination instrument at which this instrument will be
4682         *              moved to, or pass NULL for moving to end of list
4683         * @throw gig::Exception if this instrument and target instrument are not
4684         *                       part of the same file
4685         */
4686        void Instrument::MoveTo(Instrument* dst) {
4687            if (dst && GetParent() != dst->GetParent())
4688                throw Exception(
4689                    "gig::Instrument::MoveTo() can only be used for moving within "
4690                    "the same gig file."
4691                );
4692    
4693            File* pFile = (File*) GetParent();
4694    
4695            // move this instrument within the instrument list
4696            {
4697                File::InstrumentList& list = *pFile->pInstruments;
4698    
4699                File::InstrumentList::iterator itFrom =
4700                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4701    
4702                File::InstrumentList::iterator itTo =
4703                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4704    
4705                list.splice(itTo, list, itFrom);
4706            }
4707    
4708            // move the instrument's actual list RIFF chunk appropriately
4709            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4710            lstCkInstruments->MoveSubChunk(
4711                this->pCkInstrument,
4712                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4713            );
4714        }
4715    
4716        /**
4717       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4718       *       *
4719       * The list of MIDI rules, at least in gig v3, always contains at       * The list of MIDI rules, at least in gig v3, always contains at
# Line 4029  namespace { Line 4776  namespace {
4776          pMidiRules[i] = 0;          pMidiRules[i] = 0;
4777      }      }
4778    
4779        void Instrument::LoadScripts() {
4780            if (pScriptRefs) return;
4781            pScriptRefs = new std::vector<_ScriptPooolRef>;
4782            if (scriptPoolFileOffsets.empty()) return;
4783            File* pFile = (File*) GetParent();
4784            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4785                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4786                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4787                    ScriptGroup* group = pFile->GetScriptGroup(i);
4788                    for (uint s = 0; group->GetScript(s); ++s) {
4789                        Script* script = group->GetScript(s);
4790                        if (script->pChunk) {
4791                            uint32_t offset = script->pChunk->GetFilePos() -
4792                                              script->pChunk->GetPos() -
4793                                              CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4794                            if (offset == soughtOffset)
4795                            {
4796                                _ScriptPooolRef ref;
4797                                ref.script = script;
4798                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4799                                pScriptRefs->push_back(ref);
4800                                break;
4801                            }
4802                        }
4803                    }
4804                }
4805            }
4806            // we don't need that anymore
4807            scriptPoolFileOffsets.clear();
4808        }
4809    
4810        /** @brief Get instrument script (gig format extension).
4811         *
4812         * Returns the real-time instrument script of instrument script slot
4813         * @a index.
4814         *
4815         * @note This is an own format extension which did not exist i.e. in the
4816         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4817         * gigedit.
4818         *
4819         * @param index - instrument script slot index
4820         * @returns script or NULL if index is out of bounds
4821         */
4822        Script* Instrument::GetScriptOfSlot(uint index) {
4823            LoadScripts();
4824            if (index >= pScriptRefs->size()) return NULL;
4825            return pScriptRefs->at(index).script;
4826        }
4827    
4828        /** @brief Add new instrument script slot (gig format extension).
4829         *
4830         * Add the given real-time instrument script reference to this instrument,
4831         * which shall be executed by the sampler for for this instrument. The
4832         * script will be added to the end of the script list of this instrument.
4833         * The positions of the scripts in the Instrument's Script list are
4834         * relevant, because they define in which order they shall be executed by
4835         * the sampler. For this reason it is also legal to add the same script
4836         * twice to an instrument, for example you might have a script called
4837         * "MyFilter" which performs an event filter task, and you might have
4838         * another script called "MyNoteTrigger" which triggers new notes, then you
4839         * might for example have the following list of scripts on the instrument:
4840         *
4841         * 1. Script "MyFilter"
4842         * 2. Script "MyNoteTrigger"
4843         * 3. Script "MyFilter"
4844         *
4845         * Which would make sense, because the 2nd script launched new events, which
4846         * you might need to filter as well.
4847         *
4848         * There are two ways to disable / "bypass" scripts. You can either disable
4849         * a script locally for the respective script slot on an instrument (i.e. by
4850         * passing @c false to the 2nd argument of this method, or by calling
4851         * SetScriptBypassed()). Or you can disable a script globally for all slots
4852         * and all instruments by setting Script::Bypass.
4853         *
4854         * @note This is an own format extension which did not exist i.e. in the
4855         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4856         * gigedit.
4857         *
4858         * @param pScript - script that shall be executed for this instrument
4859         * @param bypass  - if enabled, the sampler shall skip executing this
4860         *                  script (in the respective list position)
4861         * @see SetScriptBypassed()
4862         */
4863        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4864            LoadScripts();
4865            _ScriptPooolRef ref = { pScript, bypass };
4866            pScriptRefs->push_back(ref);
4867        }
4868    
4869        /** @brief Flip two script slots with each other (gig format extension).
4870         *
4871         * Swaps the position of the two given scripts in the Instrument's Script
4872         * list. The positions of the scripts in the Instrument's Script list are
4873         * relevant, because they define in which order they shall be executed by
4874         * the sampler.
4875         *
4876         * @note This is an own format extension which did not exist i.e. in the
4877         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4878         * gigedit.
4879         *
4880         * @param index1 - index of the first script slot to swap
4881         * @param index2 - index of the second script slot to swap
4882         */
4883        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4884            LoadScripts();
4885            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4886                return;
4887            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4888            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4889            (*pScriptRefs)[index2] = tmp;
4890        }
4891    
4892        /** @brief Remove script slot.
4893         *
4894         * Removes the script slot with the given slot index.
4895         *
4896         * @param index - index of script slot to remove
4897         */
4898        void Instrument::RemoveScriptSlot(uint index) {
4899            LoadScripts();
4900            if (index >= pScriptRefs->size()) return;
4901            pScriptRefs->erase( pScriptRefs->begin() + index );
4902        }
4903    
4904        /** @brief Remove reference to given Script (gig format extension).
4905         *
4906         * This will remove all script slots on the instrument which are referencing
4907         * the given script.
4908         *
4909         * @note This is an own format extension which did not exist i.e. in the
4910         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4911         * gigedit.
4912         *
4913         * @param pScript - script reference to remove from this instrument
4914         * @see RemoveScriptSlot()
4915         */
4916        void Instrument::RemoveScript(Script* pScript) {
4917            LoadScripts();
4918            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4919                if ((*pScriptRefs)[i].script == pScript) {
4920                    pScriptRefs->erase( pScriptRefs->begin() + i );
4921                }
4922            }
4923        }
4924    
4925        /** @brief Instrument's amount of script slots.
4926         *
4927         * This method returns the amount of script slots this instrument currently
4928         * uses.
4929         *
4930         * A script slot is a reference of a real-time instrument script to be
4931         * executed by the sampler. The scripts will be executed by the sampler in
4932         * sequence of the slots. One (same) script may be referenced multiple
4933         * times in different slots.
4934         *
4935         * @note This is an own format extension which did not exist i.e. in the
4936         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4937         * gigedit.
4938         */
4939        uint Instrument::ScriptSlotCount() const {
4940            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4941        }
4942    
4943        /** @brief Whether script execution shall be skipped.
4944         *
4945         * Defines locally for the Script reference slot in the Instrument's Script
4946         * list, whether the script shall be skipped by the sampler regarding
4947         * execution.
4948         *
4949         * It is also possible to ignore exeuction of the script globally, for all
4950         * slots and for all instruments by setting Script::Bypass.
4951         *
4952         * @note This is an own format extension which did not exist i.e. in the
4953         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4954         * gigedit.
4955         *
4956         * @param index - index of the script slot on this instrument
4957         * @see Script::Bypass
4958         */
4959        bool Instrument::IsScriptSlotBypassed(uint index) {
4960            if (index >= ScriptSlotCount()) return false;
4961            return pScriptRefs ? pScriptRefs->at(index).bypass
4962                               : scriptPoolFileOffsets.at(index).bypass;
4963            
4964        }
4965    
4966        /** @brief Defines whether execution shall be skipped.
4967         *
4968         * You can call this method to define locally whether or whether not the
4969         * given script slot shall be executed by the sampler.
4970         *
4971         * @note This is an own format extension which did not exist i.e. in the
4972         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4973         * gigedit.
4974         *
4975         * @param index - script slot index on this instrument
4976         * @param bBypass - if true, the script slot will be skipped by the sampler
4977         * @see Script::Bypass
4978         */
4979        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
4980            if (index >= ScriptSlotCount()) return;
4981            if (pScriptRefs)
4982                pScriptRefs->at(index).bypass = bBypass;
4983            else
4984                scriptPoolFileOffsets.at(index).bypass = bBypass;
4985        }
4986    
4987      /**      /**
4988       * Make a (semi) deep copy of the Instrument object given by @a orig       * Make a (semi) deep copy of the Instrument object given by @a orig
4989       * and assign it to this object.       * and assign it to this object.
# Line 4062  namespace { Line 5017  namespace {
5017          PitchbendRange = orig->PitchbendRange;          PitchbendRange = orig->PitchbendRange;
5018          PianoReleaseMode = orig->PianoReleaseMode;          PianoReleaseMode = orig->PianoReleaseMode;
5019          DimensionKeyRange = orig->DimensionKeyRange;          DimensionKeyRange = orig->DimensionKeyRange;
5020            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5021            pScriptRefs = orig->pScriptRefs;
5022                    
5023          // free old midi rules          // free old midi rules
5024          for (int i = 0 ; pMidiRules[i] ; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
# Line 4116  namespace { Line 5073  namespace {
5073       *       *
5074       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5075       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5076         *
5077         * @param pProgress - callback function for progress notification
5078       */       */
5079      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5080          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5081          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5082          if (!_3gri) {          if (!_3gri) {
# Line 4247  namespace { Line 5206  namespace {
5206          bAutoLoad = true;          bAutoLoad = true;
5207          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5208          pGroups = NULL;          pGroups = NULL;
5209            pScriptGroups = NULL;
5210          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5211          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5212    
# Line 4262  namespace { Line 5222  namespace {
5222      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5223          bAutoLoad = true;          bAutoLoad = true;
5224          pGroups = NULL;          pGroups = NULL;
5225            pScriptGroups = NULL;
5226          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5227      }      }
5228    
# Line 4275  namespace { Line 5236  namespace {
5236              }              }
5237              delete pGroups;              delete pGroups;
5238          }          }
5239            if (pScriptGroups) {
5240                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5241                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5242                while (iter != end) {
5243                    delete *iter;
5244                    ++iter;
5245                }
5246                delete pScriptGroups;
5247            }
5248      }      }
5249    
5250      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 4383  namespace { Line 5353  namespace {
5353          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5354    
5355          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5356            // (only for old gig files < 2 GB)
5357          int lastFileNo = 0;          int lastFileNo = 0;
5358          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5359              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5360                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5361                }
5362          }          }
5363          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5364          int nameLen = name.length();          int nameLen = name.length();
# Line 4395  namespace { Line 5368  namespace {
5368          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5369              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5370              if (wvpl) {              if (wvpl) {
5371                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5372                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5373                  while (wave) {                  while (wave) {
5374                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 4403  namespace { Line 5376  namespace {
5376                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5377                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5378    
5379                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5380                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5381    
5382                          iSampleIndex++;                          iSampleIndex++;
# Line 4787  namespace { Line 5760  namespace {
5760          }          }
5761      }      }
5762    
5763        /** @brief Get instrument script group (by index).
5764         *
5765         * Returns the real-time instrument script group with the given index.
5766         *
5767         * @param index - number of the sought group (0..n)
5768         * @returns sought script group or NULL if there's no such group
5769         */
5770        ScriptGroup* File::GetScriptGroup(uint index) {
5771            if (!pScriptGroups) LoadScriptGroups();
5772            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5773            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5774                if (i == index) return *it;
5775            return NULL;
5776        }
5777    
5778        /** @brief Get instrument script group (by name).
5779         *
5780         * Returns the first real-time instrument script group found with the given
5781         * group name. Note that group names may not necessarily be unique.
5782         *
5783         * @param name - name of the sought script group
5784         * @returns sought script group or NULL if there's no such group
5785         */
5786        ScriptGroup* File::GetScriptGroup(const String& name) {
5787            if (!pScriptGroups) LoadScriptGroups();
5788            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5789            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5790                if ((*it)->Name == name) return *it;
5791            return NULL;
5792        }
5793    
5794        /** @brief Add new instrument script group.
5795         *
5796         * Adds a new, empty real-time instrument script group to the file.
5797         *
5798         * You have to call Save() to make this persistent to the file.
5799         *
5800         * @return new empty script group
5801         */
5802        ScriptGroup* File::AddScriptGroup() {
5803            if (!pScriptGroups) LoadScriptGroups();
5804            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5805            pScriptGroups->push_back(pScriptGroup);
5806            return pScriptGroup;
5807        }
5808    
5809        /** @brief Delete an instrument script group.
5810         *
5811         * This will delete the given real-time instrument script group and all its
5812         * instrument scripts it contains. References inside instruments that are
5813         * using the deleted scripts will be removed from the respective instruments
5814         * accordingly.
5815         *
5816         * You have to call Save() to make this persistent to the file.
5817         *
5818         * @param pScriptGroup - script group to delete
5819         * @throws gig::Exception if given script group could not be found
5820         */
5821        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5822            if (!pScriptGroups) LoadScriptGroups();
5823            std::list<ScriptGroup*>::iterator iter =
5824                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5825            if (iter == pScriptGroups->end())
5826                throw gig::Exception("Could not delete script group, could not find given script group");
5827            pScriptGroups->erase(iter);
5828            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5829                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5830            if (pScriptGroup->pList)
5831                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5832            delete pScriptGroup;
5833        }
5834    
5835        void File::LoadScriptGroups() {
5836            if (pScriptGroups) return;
5837            pScriptGroups = new std::list<ScriptGroup*>;
5838            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
5839            if (lstLS) {
5840                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
5841                     lst = lstLS->GetNextSubList())
5842                {
5843                    if (lst->GetListType() == LIST_TYPE_RTIS) {
5844                        pScriptGroups->push_back(new ScriptGroup(this, lst));
5845                    }
5846                }
5847            }
5848        }
5849    
5850      /**      /**
5851       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
5852       * to the respective RIFF chunks. You have to call Save() to make changes       * to the respective RIFF chunks. You have to call Save() to make changes
# Line 4795  namespace { Line 5855  namespace {
5855       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5856       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5857       *       *
5858         * @param pProgress - callback function for progress notification
5859       * @throws Exception - on errors       * @throws Exception - on errors
5860       */       */
5861      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
5862          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
5863    
5864          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
5865            // (not part of the GigaStudio 4 format)
5866            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
5867            if (!lst3LS) {
5868                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
5869            }
5870            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
5871            // location of <3LS > is irrelevant, however it should be located
5872            // before  the actual wave data
5873            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
5874            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
5875    
5876            // This must be performed before writing the chunks for instruments,
5877            // because the instruments' script slots will write the file offsets
5878            // of the respective instrument script chunk as reference.
5879            if (pScriptGroups) {
5880                // Update instrument script (group) chunks.
5881                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5882                     it != pScriptGroups->end(); ++it)
5883                {
5884                    (*it)->UpdateChunks(pProgress);
5885                }
5886            }
5887    
5888            // in case no libgig custom format data was added, then remove the
5889            // custom "3LS " chunk again
5890            if (!lst3LS->CountSubChunks()) {
5891                pRIFF->DeleteSubChunk(lst3LS);
5892                lst3LS = NULL;
5893            }
5894    
5895          // first update base class's chunks          // first update base class's chunks
5896          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
5897    
5898          if (newFile) {          if (newFile) {
5899              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 4840  namespace { Line 5930  namespace {
5930              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
5931              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
5932              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
5933                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
5934              }              }
5935          }          }
5936    
# Line 4972  namespace { Line 6062  namespace {
6062              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6063          }          }
6064      }      }
6065        
6066        void File::UpdateFileOffsets() {
6067            DLS::File::UpdateFileOffsets();
6068    
6069            for (Instrument* instrument = GetFirstInstrument(); instrument;
6070                 instrument = GetNextInstrument())
6071            {
6072                instrument->UpdateScriptFileOffsets();
6073            }
6074        }
6075    
6076      /**      /**
6077       * Enable / disable automatic loading. By default this properyt is       * Enable / disable automatic loading. By default this properyt is

Legend:
Removed from v.2547  
changed lines
  Added in v.2923

  ViewVC Help
Powered by ViewVC