/[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 2990 by schoenebeck, Sat Sep 24 15:02:28 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 365  namespace { Line 338  namespace {
338       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
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         * @param index          - wave pool index of sample (may be -1 on new sample)
342       */       */
343      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, int index)
344            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
345        {
346          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
347              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
348              { 0, 0 }              { 0, 0 }
# Line 376  namespace { Line 352  namespace {
352          FileNo = fileNo;          FileNo = fileNo;
353    
354          __resetCRC(crc);          __resetCRC(crc);
355            // if this is not a new sample, try to get the sample's already existing
356            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
357            // checksum of the time when the sample was consciously modified by the
358            // user for the last time (by calling Sample::Write() that is).
359            if (index >= 0) { // not a new file ...
360                try {
361                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
362                    this->crc = crc;
363                } catch (...) {}
364            }
365    
366          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
367          if (pCk3gix) {          if (pCk3gix) {
# Line 508  namespace { Line 494  namespace {
494          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
495          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
496          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
497          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
498          pOrig->SetPos(0);          pOrig->SetPos(0);
499          SetPos(0);          SetPos(0);
500          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
501                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
502          {          {
503              Write(buf, n);              Write(buf, n);
# Line 527  namespace { Line 513  namespace {
513       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
514       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
515       *       *
516         * @param pProgress - callback function for progress notification
517       * @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
518       *                        was provided yet       *                        was provided yet
519       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
520       */       */
521      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
522          // first update base class's chunks          // first update base class's chunks
523          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
524    
525          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
526          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 595  namespace { Line 582  namespace {
582      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
583          //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)
584          this->SamplesTotal = 0;          this->SamplesTotal = 0;
585          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
586    
587          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
588          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 611  namespace { Line 598  namespace {
598                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
599                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
600                  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");
601                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
602    
603                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
604                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 630  namespace { Line 617  namespace {
617    
618                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
619                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
620                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
621    
622                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
623                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 646  namespace { Line 633  namespace {
633    
634          // 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)
635          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
636          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
637          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
638          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
639          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
640              FrameTable[i] = *iter;              FrameTable[i] = *iter;
641          }          }
# Line 689  namespace { Line 676  namespace {
676       *                      the cached sample data in bytes       *                      the cached sample data in bytes
677       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
678       */       */
679      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
680          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
681      }      }
682    
# Line 748  namespace { Line 735  namespace {
735       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
736       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
737       */       */
738      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
739          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
740          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
741          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
742          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
743          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
744          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 815  namespace { Line 802  namespace {
802       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
803       * other formats will fail!       * other formats will fail!
804       *       *
805       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
806       *                   greater than zero)       *                  greater than zero)
807       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
808       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
809       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
810       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
811       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
812       */       */
813      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
814          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)");
815          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
816      }      }
817    
818      /**      /**
# Line 849  namespace { Line 836  namespace {
836       * @returns            the new sample position       * @returns            the new sample position
837       * @see                Read()       * @see                Read()
838       */       */
839      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) {
840          if (Compressed) {          if (Compressed) {
841              switch (Whence) {              switch (Whence) {
842                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 867  namespace { Line 854  namespace {
854              }              }
855              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
856    
857              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
858              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
859              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
860              return this->SamplePos;              return this->SamplePos;
861          }          }
862          else { // not compressed          else { // not compressed
863              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
864              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
865              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
866                                              : result / this->FrameSize;                                              : result / this->FrameSize;
867          }          }
# Line 883  namespace { Line 870  namespace {
870      /**      /**
871       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
872       */       */
873      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
874          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
875          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
876      }      }
# Line 922  namespace { Line 909  namespace {
909       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
910       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
911       */       */
912      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,
913                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
914          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
915          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
916    
917          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 962  namespace { Line 949  namespace {
949                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
950                                  // backward playback                                  // backward playback
951    
952                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
953                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
954                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
955                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
956    
957                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
958    
# Line 1013  namespace { Line 1000  namespace {
1000                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1001                          // backward playback                          // backward playback
1002    
1003                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1004                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1005                          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)
1006                                                                                    : samplestoread;                                                                                    : samplestoread;
1007                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1008    
1009                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1010    
# Line 1097  namespace { Line 1084  namespace {
1084       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1085       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1086       */       */
1087      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) {
1088          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1089          if (!Compressed) {          if (!Compressed) {
1090              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1112  namespace { Line 1099  namespace {
1099          else {          else {
1100              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1101              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1102              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1103                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1104                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1105                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1135  namespace { Line 1122  namespace {
1122              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1123    
1124              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1125                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1126                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1127    
1128                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1129    
# Line 1286  namespace { Line 1273  namespace {
1273       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1274       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1275       */       */
1276      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1277          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)");
1278    
1279          // 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 1282  namespace {
1282              __resetCRC(crc);              __resetCRC(crc);
1283          }          }
1284          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");
1285          unsigned long res;          file_offset_t res;
1286          if (BitDepth == 24) {          if (BitDepth == 24) {
1287              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1288          } else { // 16 bit          } else { // 16 bit
# Line 1329  namespace { Line 1316  namespace {
1316       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1317       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1318       */       */
1319      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1320          buffer_t result;          buffer_t result;
1321          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1322                  (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;
1323          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);
1324          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1325          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1326          return result;          return result;
# Line 1367  namespace { Line 1354  namespace {
1354          return pGroup;          return pGroup;
1355      }      }
1356    
1357        /**
1358         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1359         * time when this sample's wave form data was modified for the last time
1360         * by calling Write(). This checksum only covers the raw wave form data,
1361         * not any meta informations like i.e. bit depth or loop points. Since
1362         * this method just returns the checksum stored for this sample i.e. when
1363         * the gig file was loaded, this method returns immediately. So it does no
1364         * recalcuation of the checksum with the currently available sample wave
1365         * form data.
1366         *
1367         * @see VerifyWaveData()
1368         */
1369        uint32_t Sample::GetWaveDataCRC32Checksum() {
1370            return crc;
1371        }
1372    
1373        /**
1374         * Checks the integrity of this sample's raw audio wave data. Whenever a
1375         * Sample's raw wave data is intentionally modified (i.e. by calling
1376         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1377         * is calculated and stored/updated for this sample, along to the sample's
1378         * meta informations.
1379         *
1380         * Now by calling this method the current raw audio wave data is checked
1381         * against the already stored CRC32 check sum in order to check whether the
1382         * sample data had been damaged unintentionally for some reason. Since by
1383         * calling this method always the entire raw audio wave data has to be
1384         * read, verifying all samples this way may take a long time accordingly.
1385         * And that's also the reason why the sample integrity is not checked by
1386         * default whenever a gig file is loaded. So this method must be called
1387         * explicitly to fulfill this task.
1388         *
1389         * @param pActually - (optional) if provided, will be set to the actually
1390         *                    calculated checksum of the current raw wave form data,
1391         *                    you can get the expected checksum instead by calling
1392         *                    GetWaveDataCRC32Checksum()
1393         * @returns true if sample is OK or false if the sample is damaged
1394         * @throws Exception if no checksum had been stored to disk for this
1395         *         sample yet, or on I/O issues
1396         * @see GetWaveDataCRC32Checksum()
1397         */
1398        bool Sample::VerifyWaveData(uint32_t* pActually) {
1399            File* pFile = static_cast<File*>(GetParent());
1400            uint32_t crc = CalculateWaveDataChecksum();
1401            if (pActually) *pActually = crc;
1402            return crc == this->crc;
1403        }
1404    
1405        uint32_t Sample::CalculateWaveDataChecksum() {
1406            const size_t sz = 20*1024; // 20kB buffer size
1407            std::vector<uint8_t> buffer(sz);
1408            buffer.resize(sz);
1409    
1410            const size_t n = sz / FrameSize;
1411            SetPos(0);
1412            uint32_t crc = 0;
1413            __resetCRC(crc);
1414            while (true) {
1415                file_offset_t nRead = Read(&buffer[0], n);
1416                if (nRead <= 0) break;
1417                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1418            }
1419            __encodeCRC(crc);
1420            return crc;
1421        }
1422    
1423      Sample::~Sample() {      Sample::~Sample() {
1424          Instances--;          Instances--;
1425          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1383  namespace { Line 1436  namespace {
1436  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1437  // *  // *
1438    
1439      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1440      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1441    
1442      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1577  namespace { Line 1630  namespace {
1630              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1631              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1632              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1633              EG2Release                      = 0.3;              EG2Release                      = 60;
1634              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1635              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1636              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1751  namespace { Line 1804  namespace {
1804       *       *
1805       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1806       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1807         *
1808         * @param pProgress - callback function for progress notification
1809       */       */
1810      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1811          // first update base class's chunk          // first update base class's chunk
1812          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1813    
1814          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1815          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 3025  namespace { Line 3080  namespace {
3080       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3081       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3082       *       *
3083         * @param pProgress - callback function for progress notification
3084       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3085       */       */
3086      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3087          // 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
3088          // 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
3089          // 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 3091  namespace {
3091          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3092    
3093          // first update base class's chunks          // first update base class's chunks
3094          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3095    
3096          // update dimension region's chunks          // update dimension region's chunks
3097          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3098              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3099          }          }
3100    
3101          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 3055  namespace { Line 3111  namespace {
3111              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3112    
3113              // move 3prg to last position              // move 3prg to last position
3114              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3115          }          }
3116    
3117          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 3129  namespace { Line 3185  namespace {
3185          int step = 1;          int step = 1;
3186          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3187          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3188    
3189          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3190          int dim[8] = { 0 };          int dim[8] = { 0 };
3191          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3192                const int end = i + step * pDimensionDefinitions[veldim].zones;
3193    
3194                // create a velocity table for all cases where the velocity zone is zero
3195              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3196                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3197                  // create the velocity table                  // create the velocity table
# Line 3165  namespace { Line 3222  namespace {
3222                  }                  }
3223              }              }
3224    
3225                // jump to the next case where the velocity zone is zero
3226              int j;              int j;
3227              int shift = 0;              int shift = 0;
3228              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3388  namespace { Line 3446  namespace {
3446          if (pDimDef->dimension == dimension_layer) Layers = 1;          if (pDimDef->dimension == dimension_layer) Layers = 1;
3447      }      }
3448    
3449        /** @brief Delete one split zone of a dimension (decrement zone amount).
3450         *
3451         * Instead of deleting an entire dimensions, this method will only delete
3452         * one particular split zone given by @a zone of the Region's dimension
3453         * given by @a type. So this method will simply decrement the amount of
3454         * zones by one of the dimension in question. To be able to do that, the
3455         * respective dimension must exist on this Region and it must have at least
3456         * 3 zones. All DimensionRegion objects associated with the zone will be
3457         * deleted.
3458         *
3459         * @param type - identifies the dimension where a zone shall be deleted
3460         * @param zone - index of the dimension split zone that shall be deleted
3461         * @throws gig::Exception if requested zone could not be deleted
3462         */
3463        void Region::DeleteDimensionZone(dimension_t type, int zone) {
3464            dimension_def_t* oldDef = GetDimensionDefinition(type);
3465            if (!oldDef)
3466                throw gig::Exception("Could not delete dimension zone, no such dimension of given type");
3467            if (oldDef->zones <= 2)
3468                throw gig::Exception("Could not delete dimension zone, because it would end up with only one zone.");
3469            if (zone < 0 || zone >= oldDef->zones)
3470                throw gig::Exception("Could not delete dimension zone, requested zone index out of bounds.");
3471    
3472            const int newZoneSize = oldDef->zones - 1;
3473    
3474            // create a temporary Region which just acts as a temporary copy
3475            // container and will be deleted at the end of this function and will
3476            // also not be visible through the API during this process
3477            gig::Region* tempRgn = NULL;
3478            {
3479                // adding these temporary chunks is probably not even necessary
3480                Instrument* instr = static_cast<Instrument*>(GetParent());
3481                RIFF::List* pCkInstrument = instr->pCkInstrument;
3482                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3483                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3484                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3485                tempRgn = new Region(instr, rgn);
3486            }
3487    
3488            // copy this region's dimensions (with already the dimension split size
3489            // requested by the arguments of this method call) to the temporary
3490            // region, and don't use Region::CopyAssign() here for this task, since
3491            // it would also alter fast lookup helper variables here and there
3492            dimension_def_t newDef;
3493            for (int i = 0; i < Dimensions; ++i) {
3494                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3495                // is this the dimension requested by the method arguments? ...
3496                if (def.dimension == type) { // ... if yes, decrement zone amount by one
3497                    def.zones = newZoneSize;
3498                    if ((1 << (def.bits - 1)) == def.zones) def.bits--;
3499                    newDef = def;
3500                }
3501                tempRgn->AddDimension(&def);
3502            }
3503    
3504            // find the dimension index in the tempRegion which is the dimension
3505            // type passed to this method (paranoidly expecting different order)
3506            int tempReducedDimensionIndex = -1;
3507            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3508                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3509                    tempReducedDimensionIndex = d;
3510                    break;
3511                }
3512            }
3513    
3514            // copy dimension regions from this region to the temporary region
3515            for (int iDst = 0; iDst < 256; ++iDst) {
3516                DimensionRegion* dstDimRgn = tempRgn->pDimensionRegions[iDst];
3517                if (!dstDimRgn) continue;
3518                std::map<dimension_t,int> dimCase;
3519                bool isValidZone = true;
3520                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3521                    const int dstBits = tempRgn->pDimensionDefinitions[d].bits;
3522                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3523                        (iDst >> baseBits) & ((1 << dstBits) - 1);
3524                    baseBits += dstBits;
3525                    // there are also DimensionRegion objects of unused zones, skip them
3526                    if (dimCase[tempRgn->pDimensionDefinitions[d].dimension] >= tempRgn->pDimensionDefinitions[d].zones) {
3527                        isValidZone = false;
3528                        break;
3529                    }
3530                }
3531                if (!isValidZone) continue;
3532                // a bit paranoid: cope with the chance that the dimensions would
3533                // have different order in source and destination regions
3534                const bool isLastZone = (dimCase[type] == newZoneSize - 1);
3535                if (dimCase[type] >= zone) dimCase[type]++;
3536                DimensionRegion* srcDimRgn = GetDimensionRegionByBit(dimCase);
3537                dstDimRgn->CopyAssign(srcDimRgn);
3538                // if this is the upper most zone of the dimension passed to this
3539                // method, then correct (raise) its upper limit to 127
3540                if (newDef.split_type == split_type_normal && isLastZone)
3541                    dstDimRgn->DimensionUpperLimits[tempReducedDimensionIndex] = 127;
3542            }
3543    
3544            // now tempRegion's dimensions and DimensionRegions basically reflect
3545            // what we wanted to get for this actual Region here, so we now just
3546            // delete and recreate the dimension in question with the new amount
3547            // zones and then copy back from tempRegion      
3548            DeleteDimension(oldDef);
3549            AddDimension(&newDef);
3550            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3551                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3552                if (!srcDimRgn) continue;
3553                std::map<dimension_t,int> dimCase;
3554                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3555                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3556                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3557                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3558                    baseBits += srcBits;
3559                }
3560                // a bit paranoid: cope with the chance that the dimensions would
3561                // have different order in source and destination regions
3562                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3563                if (!dstDimRgn) continue;
3564                dstDimRgn->CopyAssign(srcDimRgn);
3565            }
3566    
3567            // delete temporary region
3568            delete tempRgn;
3569    
3570            UpdateVelocityTable();
3571        }
3572    
3573        /** @brief Divide split zone of a dimension in two (increment zone amount).
3574         *
3575         * This will increment the amount of zones for the dimension (given by
3576         * @a type) by one. It will do so by dividing the zone (given by @a zone)
3577         * in the middle of its zone range in two. So the two zones resulting from
3578         * the zone being splitted, will be an equivalent copy regarding all their
3579         * articulation informations and sample reference. The two zones will only
3580         * differ in their zone's upper limit
3581         * (DimensionRegion::DimensionUpperLimits).
3582         *
3583         * @param type - identifies the dimension where a zone shall be splitted
3584         * @param zone - index of the dimension split zone that shall be splitted
3585         * @throws gig::Exception if requested zone could not be splitted
3586         */
3587        void Region::SplitDimensionZone(dimension_t type, int zone) {
3588            dimension_def_t* oldDef = GetDimensionDefinition(type);
3589            if (!oldDef)
3590                throw gig::Exception("Could not split dimension zone, no such dimension of given type");
3591            if (zone < 0 || zone >= oldDef->zones)
3592                throw gig::Exception("Could not split dimension zone, requested zone index out of bounds.");
3593    
3594            const int newZoneSize = oldDef->zones + 1;
3595    
3596            // create a temporary Region which just acts as a temporary copy
3597            // container and will be deleted at the end of this function and will
3598            // also not be visible through the API during this process
3599            gig::Region* tempRgn = NULL;
3600            {
3601                // adding these temporary chunks is probably not even necessary
3602                Instrument* instr = static_cast<Instrument*>(GetParent());
3603                RIFF::List* pCkInstrument = instr->pCkInstrument;
3604                RIFF::List* lrgn = pCkInstrument->GetSubList(LIST_TYPE_LRGN);
3605                if (!lrgn)  lrgn = pCkInstrument->AddSubList(LIST_TYPE_LRGN);
3606                RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
3607                tempRgn = new Region(instr, rgn);
3608            }
3609    
3610            // copy this region's dimensions (with already the dimension split size
3611            // requested by the arguments of this method call) to the temporary
3612            // region, and don't use Region::CopyAssign() here for this task, since
3613            // it would also alter fast lookup helper variables here and there
3614            dimension_def_t newDef;
3615            for (int i = 0; i < Dimensions; ++i) {
3616                dimension_def_t def = pDimensionDefinitions[i]; // copy, don't reference
3617                // is this the dimension requested by the method arguments? ...
3618                if (def.dimension == type) { // ... if yes, increment zone amount by one
3619                    def.zones = newZoneSize;
3620                    if ((1 << oldDef->bits) < newZoneSize) def.bits++;
3621                    newDef = def;
3622                }
3623                tempRgn->AddDimension(&def);
3624            }
3625    
3626            // find the dimension index in the tempRegion which is the dimension
3627            // type passed to this method (paranoidly expecting different order)
3628            int tempIncreasedDimensionIndex = -1;
3629            for (int d = 0; d < tempRgn->Dimensions; ++d) {
3630                if (tempRgn->pDimensionDefinitions[d].dimension == type) {
3631                    tempIncreasedDimensionIndex = d;
3632                    break;
3633                }
3634            }
3635    
3636            // copy dimension regions from this region to the temporary region
3637            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3638                DimensionRegion* srcDimRgn = pDimensionRegions[iSrc];
3639                if (!srcDimRgn) continue;
3640                std::map<dimension_t,int> dimCase;
3641                bool isValidZone = true;
3642                for (int d = 0, baseBits = 0; d < Dimensions; ++d) {
3643                    const int srcBits = pDimensionDefinitions[d].bits;
3644                    dimCase[pDimensionDefinitions[d].dimension] =
3645                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3646                    // there are also DimensionRegion objects for unused zones, skip them
3647                    if (dimCase[pDimensionDefinitions[d].dimension] >= pDimensionDefinitions[d].zones) {
3648                        isValidZone = false;
3649                        break;
3650                    }
3651                    baseBits += srcBits;
3652                }
3653                if (!isValidZone) continue;
3654                // a bit paranoid: cope with the chance that the dimensions would
3655                // have different order in source and destination regions            
3656                if (dimCase[type] > zone) dimCase[type]++;
3657                DimensionRegion* dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3658                dstDimRgn->CopyAssign(srcDimRgn);
3659                // if this is the requested zone to be splitted, then also copy
3660                // the source DimensionRegion to the newly created target zone
3661                // and set the old zones upper limit lower
3662                if (dimCase[type] == zone) {
3663                    // lower old zones upper limit
3664                    if (newDef.split_type == split_type_normal) {
3665                        const int high =
3666                            dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex];
3667                        int low = 0;
3668                        if (zone > 0) {
3669                            std::map<dimension_t,int> lowerCase = dimCase;
3670                            lowerCase[type]--;
3671                            DimensionRegion* dstDimRgnLow = tempRgn->GetDimensionRegionByBit(lowerCase);
3672                            low = dstDimRgnLow->DimensionUpperLimits[tempIncreasedDimensionIndex];
3673                        }
3674                        dstDimRgn->DimensionUpperLimits[tempIncreasedDimensionIndex] = low + (high - low) / 2;
3675                    }
3676                    // fill the newly created zone of the divided zone as well
3677                    dimCase[type]++;
3678                    dstDimRgn = tempRgn->GetDimensionRegionByBit(dimCase);
3679                    dstDimRgn->CopyAssign(srcDimRgn);
3680                }
3681            }
3682    
3683            // now tempRegion's dimensions and DimensionRegions basically reflect
3684            // what we wanted to get for this actual Region here, so we now just
3685            // delete and recreate the dimension in question with the new amount
3686            // zones and then copy back from tempRegion      
3687            DeleteDimension(oldDef);
3688            AddDimension(&newDef);
3689            for (int iSrc = 0; iSrc < 256; ++iSrc) {
3690                DimensionRegion* srcDimRgn = tempRgn->pDimensionRegions[iSrc];
3691                if (!srcDimRgn) continue;
3692                std::map<dimension_t,int> dimCase;
3693                for (int d = 0, baseBits = 0; d < tempRgn->Dimensions; ++d) {
3694                    const int srcBits = tempRgn->pDimensionDefinitions[d].bits;
3695                    dimCase[tempRgn->pDimensionDefinitions[d].dimension] =
3696                        (iSrc >> baseBits) & ((1 << srcBits) - 1);
3697                    baseBits += srcBits;
3698                }
3699                // a bit paranoid: cope with the chance that the dimensions would
3700                // have different order in source and destination regions
3701                DimensionRegion* dstDimRgn = GetDimensionRegionByBit(dimCase);
3702                if (!dstDimRgn) continue;
3703                dstDimRgn->CopyAssign(srcDimRgn);
3704            }
3705    
3706            // delete temporary region
3707            delete tempRgn;
3708    
3709            UpdateVelocityTable();
3710        }
3711    
3712        /** @brief Change type of an existing dimension.
3713         *
3714         * Alters the dimension type of a dimension already existing on this
3715         * region. If there is currently no dimension on this Region with type
3716         * @a oldType, then this call with throw an Exception. Likewise there are
3717         * cases where the requested dimension type cannot be performed. For example
3718         * if the new dimension type shall be gig::dimension_samplechannel, and the
3719         * current dimension has more than 2 zones. In such cases an Exception is
3720         * thrown as well.
3721         *
3722         * @param oldType - identifies the existing dimension to be changed
3723         * @param newType - to which dimension type it should be changed to
3724         * @throws gig::Exception if requested change cannot be performed
3725         */
3726        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3727            if (oldType == newType) return;
3728            dimension_def_t* def = GetDimensionDefinition(oldType);
3729            if (!def)
3730                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3731            if (newType == dimension_samplechannel && def->zones != 2)
3732                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3733            if (GetDimensionDefinition(newType))
3734                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3735            def->dimension  = newType;
3736            def->split_type = __resolveSplitType(newType);
3737        }
3738    
3739        DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3740            uint8_t bits[8] = {};
3741            for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
3742                 it != DimCase.end(); ++it)
3743            {
3744                for (int d = 0; d < Dimensions; ++d) {
3745                    if (pDimensionDefinitions[d].dimension == it->first) {
3746                        bits[d] = it->second;
3747                        goto nextDimCaseSlice;
3748                    }
3749                }
3750                assert(false); // do crash ... too harsh maybe ? ignore it instead ?
3751                nextDimCaseSlice:
3752                ; // noop
3753            }
3754            return GetDimensionRegionByBit(bits);
3755        }
3756    
3757      /**      /**
3758       * Searches in the current Region for a dimension of the given dimension       * Searches in the current Region for a dimension of the given dimension
3759       * 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 3827  namespace {
3827              }              }
3828              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3829          }          }
3830          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3831            if (!dimreg) return NULL;
3832          if (veldim != -1) {          if (veldim != -1) {
3833              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3834              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3835                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3836              else // normal split type              else // normal split type
3837                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3838    
3839              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3840              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3841                dimreg = pDimensionRegions[dimregidx & 255];
3842          }          }
3843          return dimreg;          return dimreg;
3844      }      }
3845    
3846        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3847            uint8_t bits;
3848            int veldim = -1;
3849            int velbitpos;
3850            int bitpos = 0;
3851            int dimregidx = 0;
3852            for (uint i = 0; i < Dimensions; i++) {
3853                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3854                    // the velocity dimension must be handled after the other dimensions
3855                    veldim = i;
3856                    velbitpos = bitpos;
3857                } else {
3858                    switch (pDimensionDefinitions[i].split_type) {
3859                        case split_type_normal:
3860                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3861                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3862                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3863                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3864                                }
3865                            } else {
3866                                // gig2: evenly sized zones
3867                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3868                            }
3869                            break;
3870                        case split_type_bit: // the value is already the sought dimension bit number
3871                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3872                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3873                            break;
3874                    }
3875                    dimregidx |= bits << bitpos;
3876                }
3877                bitpos += pDimensionDefinitions[i].bits;
3878            }
3879            dimregidx &= 255;
3880            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3881            if (!dimreg) return -1;
3882            if (veldim != -1) {
3883                // (dimreg is now the dimension region for the lowest velocity)
3884                if (dimreg->VelocityTable) // custom defined zone ranges
3885                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3886                else // normal split type
3887                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3888    
3889                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3890                dimregidx |= (bits & limiter_mask) << velbitpos;
3891                dimregidx &= 255;
3892            }
3893            return dimregidx;
3894        }
3895    
3896      /**      /**
3897       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3898       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 3513  namespace { Line 3931  namespace {
3931          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3932          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3933          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3934          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3935          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3936          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
3937          while (sample) {              uint64_t soughtoffset =
3938              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3939                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3940              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
3941                while (sample) {
3942                    if (sample->ullWavePoolOffset == soughtoffset)
3943                        return static_cast<gig::Sample*>(sample);
3944                    sample = file->GetNextSample();
3945                }
3946            } else {
3947                // use extension files and 32 bit wave pool offsets
3948                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3949                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3950                Sample* sample = file->GetFirstSample(pProgress);
3951                while (sample) {
3952                    if (sample->ullWavePoolOffset == soughtoffset &&
3953                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3954                    sample = file->GetNextSample();
3955                }
3956          }          }
3957          return NULL;          return NULL;
3958      }      }
# Line 3741  namespace { Line 4174  namespace {
4174          }          }
4175      }      }
4176    
4177    // *************** Script ***************
4178    // *
4179    
4180        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4181            pGroup = group;
4182            pChunk = ckScri;
4183            if (ckScri) { // object is loaded from file ...
4184                // read header
4185                uint32_t headerSize = ckScri->ReadUint32();
4186                Compression = (Compression_t) ckScri->ReadUint32();
4187                Encoding    = (Encoding_t) ckScri->ReadUint32();
4188                Language    = (Language_t) ckScri->ReadUint32();
4189                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4190                crc         = ckScri->ReadUint32();
4191                uint32_t nameSize = ckScri->ReadUint32();
4192                Name.resize(nameSize, ' ');
4193                for (int i = 0; i < nameSize; ++i)
4194                    Name[i] = ckScri->ReadUint8();
4195                // to handle potential future extensions of the header
4196                ckScri->SetPos(sizeof(int32_t) + headerSize);
4197                // read actual script data
4198                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4199                data.resize(scriptSize);
4200                for (int i = 0; i < scriptSize; ++i)
4201                    data[i] = ckScri->ReadUint8();
4202            } else { // this is a new script object, so just initialize it as such ...
4203                Compression = COMPRESSION_NONE;
4204                Encoding = ENCODING_ASCII;
4205                Language = LANGUAGE_NKSP;
4206                Bypass   = false;
4207                crc      = 0;
4208                Name     = "Unnamed Script";
4209            }
4210        }
4211    
4212        Script::~Script() {
4213        }
4214    
4215        /**
4216         * Returns the current script (i.e. as source code) in text format.
4217         */
4218        String Script::GetScriptAsText() {
4219            String s;
4220            s.resize(data.size(), ' ');
4221            memcpy(&s[0], &data[0], data.size());
4222            return s;
4223        }
4224    
4225        /**
4226         * Replaces the current script with the new script source code text given
4227         * by @a text.
4228         *
4229         * @param text - new script source code
4230         */
4231        void Script::SetScriptAsText(const String& text) {
4232            data.resize(text.size());
4233            memcpy(&data[0], &text[0], text.size());
4234        }
4235    
4236        /**
4237         * Apply this script to the respective RIFF chunks. You have to call
4238         * File::Save() to make changes persistent.
4239         *
4240         * Usually there is absolutely no need to call this method explicitly.
4241         * It will be called automatically when File::Save() was called.
4242         *
4243         * @param pProgress - callback function for progress notification
4244         */
4245        void Script::UpdateChunks(progress_t* pProgress) {
4246            // recalculate CRC32 check sum
4247            __resetCRC(crc);
4248            __calculateCRC(&data[0], data.size(), crc);
4249            __encodeCRC(crc);
4250            // make sure chunk exists and has the required size
4251            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4252            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4253            else pChunk->Resize(chunkSize);
4254            // fill the chunk data to be written to disk
4255            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4256            int pos = 0;
4257            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4258            pos += sizeof(int32_t);
4259            store32(&pData[pos], Compression);
4260            pos += sizeof(int32_t);
4261            store32(&pData[pos], Encoding);
4262            pos += sizeof(int32_t);
4263            store32(&pData[pos], Language);
4264            pos += sizeof(int32_t);
4265            store32(&pData[pos], Bypass ? 1 : 0);
4266            pos += sizeof(int32_t);
4267            store32(&pData[pos], crc);
4268            pos += sizeof(int32_t);
4269            store32(&pData[pos], Name.size());
4270            pos += sizeof(int32_t);
4271            for (int i = 0; i < Name.size(); ++i, ++pos)
4272                pData[pos] = Name[i];
4273            for (int i = 0; i < data.size(); ++i, ++pos)
4274                pData[pos] = data[i];
4275        }
4276    
4277        /**
4278         * Move this script from its current ScriptGroup to another ScriptGroup
4279         * given by @a pGroup.
4280         *
4281         * @param pGroup - script's new group
4282         */
4283        void Script::SetGroup(ScriptGroup* pGroup) {
4284            if (this->pGroup == pGroup) return;
4285            if (pChunk)
4286                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4287            this->pGroup = pGroup;
4288        }
4289    
4290        /**
4291         * Returns the script group this script currently belongs to. Each script
4292         * is a member of exactly one ScriptGroup.
4293         *
4294         * @returns current script group
4295         */
4296        ScriptGroup* Script::GetGroup() const {
4297            return pGroup;
4298        }
4299    
4300        void Script::RemoveAllScriptReferences() {
4301            File* pFile = pGroup->pFile;
4302            for (int i = 0; pFile->GetInstrument(i); ++i) {
4303                Instrument* instr = pFile->GetInstrument(i);
4304                instr->RemoveScript(this);
4305            }
4306        }
4307    
4308    // *************** ScriptGroup ***************
4309    // *
4310    
4311        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4312            pFile = file;
4313            pList = lstRTIS;
4314            pScripts = NULL;
4315            if (lstRTIS) {
4316                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4317                ::LoadString(ckName, Name);
4318            } else {
4319                Name = "Default Group";
4320            }
4321        }
4322    
4323        ScriptGroup::~ScriptGroup() {
4324            if (pScripts) {
4325                std::list<Script*>::iterator iter = pScripts->begin();
4326                std::list<Script*>::iterator end  = pScripts->end();
4327                while (iter != end) {
4328                    delete *iter;
4329                    ++iter;
4330                }
4331                delete pScripts;
4332            }
4333        }
4334    
4335        /**
4336         * Apply this script group to the respective RIFF chunks. You have to call
4337         * File::Save() to make changes persistent.
4338         *
4339         * Usually there is absolutely no need to call this method explicitly.
4340         * It will be called automatically when File::Save() was called.
4341         *
4342         * @param pProgress - callback function for progress notification
4343         */
4344        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4345            if (pScripts) {
4346                if (!pList)
4347                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4348    
4349                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4350                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4351    
4352                for (std::list<Script*>::iterator it = pScripts->begin();
4353                     it != pScripts->end(); ++it)
4354                {
4355                    (*it)->UpdateChunks(pProgress);
4356                }
4357            }
4358        }
4359    
4360        /** @brief Get instrument script.
4361         *
4362         * Returns the real-time instrument script with the given index.
4363         *
4364         * @param index - number of the sought script (0..n)
4365         * @returns sought script or NULL if there's no such script
4366         */
4367        Script* ScriptGroup::GetScript(uint index) {
4368            if (!pScripts) LoadScripts();
4369            std::list<Script*>::iterator it = pScripts->begin();
4370            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4371                if (i == index) return *it;
4372            return NULL;
4373        }
4374    
4375        /** @brief Add new instrument script.
4376         *
4377         * Adds a new real-time instrument script to the file. The script is not
4378         * actually used / executed unless it is referenced by an instrument to be
4379         * used. This is similar to samples, which you can add to a file, without
4380         * an instrument necessarily actually using it.
4381         *
4382         * You have to call Save() to make this persistent to the file.
4383         *
4384         * @return new empty script object
4385         */
4386        Script* ScriptGroup::AddScript() {
4387            if (!pScripts) LoadScripts();
4388            Script* pScript = new Script(this, NULL);
4389            pScripts->push_back(pScript);
4390            return pScript;
4391        }
4392    
4393        /** @brief Delete an instrument script.
4394         *
4395         * This will delete the given real-time instrument script. References of
4396         * instruments that are using that script will be removed accordingly.
4397         *
4398         * You have to call Save() to make this persistent to the file.
4399         *
4400         * @param pScript - script to delete
4401         * @throws gig::Exception if given script could not be found
4402         */
4403        void ScriptGroup::DeleteScript(Script* pScript) {
4404            if (!pScripts) LoadScripts();
4405            std::list<Script*>::iterator iter =
4406                find(pScripts->begin(), pScripts->end(), pScript);
4407            if (iter == pScripts->end())
4408                throw gig::Exception("Could not delete script, could not find given script");
4409            pScripts->erase(iter);
4410            pScript->RemoveAllScriptReferences();
4411            if (pScript->pChunk)
4412                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4413            delete pScript;
4414        }
4415    
4416        void ScriptGroup::LoadScripts() {
4417            if (pScripts) return;
4418            pScripts = new std::list<Script*>;
4419            if (!pList) return;
4420    
4421            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4422                 ck = pList->GetNextSubChunk())
4423            {
4424                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4425                    pScripts->push_back(new Script(this, ck));
4426                }
4427            }
4428        }
4429    
4430  // *************** Instrument ***************  // *************** Instrument ***************
4431  // *  // *
4432    
# Line 3763  namespace { Line 4449  namespace {
4449          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4450          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4451          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4452            pScriptRefs = NULL;
4453    
4454          // Loading          // Loading
4455          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 3823  namespace { Line 4510  namespace {
4510              }              }
4511          }          }
4512    
4513            // own gig format extensions
4514            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4515            if (lst3LS) {
4516                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4517                if (ckSCSL) {
4518                    int headerSize = ckSCSL->ReadUint32();
4519                    int slotCount  = ckSCSL->ReadUint32();
4520                    if (slotCount) {
4521                        int slotSize  = ckSCSL->ReadUint32();
4522                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4523                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4524                        for (int i = 0; i < slotCount; ++i) {
4525                            _ScriptPooolEntry e;
4526                            e.fileOffset = ckSCSL->ReadUint32();
4527                            e.bypass     = ckSCSL->ReadUint32() & 1;
4528                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4529                            scriptPoolFileOffsets.push_back(e);
4530                        }
4531                    }
4532                }
4533            }
4534    
4535          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4536      }      }
4537    
# Line 3843  namespace { Line 4552  namespace {
4552              delete pMidiRules[i];              delete pMidiRules[i];
4553          }          }
4554          delete[] pMidiRules;          delete[] pMidiRules;
4555            if (pScriptRefs) delete pScriptRefs;
4556      }      }
4557    
4558      /**      /**
# Line 3852  namespace { Line 4562  namespace {
4562       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4563       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4564       *       *
4565         * @param pProgress - callback function for progress notification
4566       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4567       */       */
4568      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4569          // first update base classes' chunks          // first update base classes' chunks
4570          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4571    
4572          // update Regions' chunks          // update Regions' chunks
4573          {          {
4574              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4575              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4576              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4577                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4578          }          }
4579    
4580          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 3898  namespace { Line 4609  namespace {
4609                  pMidiRules[i]->UpdateChunks(pData);                  pMidiRules[i]->UpdateChunks(pData);
4610              }              }
4611          }          }
4612    
4613            // own gig format extensions
4614           if (ScriptSlotCount()) {
4615               // make sure we have converted the original loaded script file
4616               // offsets into valid Script object pointers
4617               LoadScripts();
4618    
4619               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4620               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4621               const int slotCount = pScriptRefs->size();
4622               const int headerSize = 3 * sizeof(uint32_t);
4623               const int slotSize  = 2 * sizeof(uint32_t);
4624               const int totalChunkSize = headerSize + slotCount * slotSize;
4625               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4626               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4627               else ckSCSL->Resize(totalChunkSize);
4628               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4629               int pos = 0;
4630               store32(&pData[pos], headerSize);
4631               pos += sizeof(uint32_t);
4632               store32(&pData[pos], slotCount);
4633               pos += sizeof(uint32_t);
4634               store32(&pData[pos], slotSize);
4635               pos += sizeof(uint32_t);
4636               for (int i = 0; i < slotCount; ++i) {
4637                   // arbitrary value, the actual file offset will be updated in
4638                   // UpdateScriptFileOffsets() after the file has been resized
4639                   int bogusFileOffset = 0;
4640                   store32(&pData[pos], bogusFileOffset);
4641                   pos += sizeof(uint32_t);
4642                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4643                   pos += sizeof(uint32_t);
4644               }
4645           } else {
4646               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4647               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4648               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4649           }
4650        }
4651    
4652        void Instrument::UpdateScriptFileOffsets() {
4653           // own gig format extensions
4654           if (pScriptRefs && pScriptRefs->size() > 0) {
4655               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4656               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4657               const int slotCount = pScriptRefs->size();
4658               const int headerSize = 3 * sizeof(uint32_t);
4659               ckSCSL->SetPos(headerSize);
4660               for (int i = 0; i < slotCount; ++i) {
4661                   uint32_t fileOffset =
4662                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4663                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4664                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4665                   ckSCSL->WriteUint32(&fileOffset);
4666                   // jump over flags entry (containing the bypass flag)
4667                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4668               }
4669           }        
4670      }      }
4671    
4672      /**      /**
# Line 3967  namespace { Line 4736  namespace {
4736      }      }
4737    
4738      /**      /**
4739         * Move this instrument at the position before @arg dst.
4740         *
4741         * This method can be used to reorder the sequence of instruments in a
4742         * .gig file. This might be helpful especially on large .gig files which
4743         * contain a large number of instruments within the same .gig file. So
4744         * grouping such instruments to similar ones, can help to keep track of them
4745         * when working with such complex .gig files.
4746         *
4747         * When calling this method, this instrument will be removed from in its
4748         * current position in the instruments list and moved to the requested
4749         * target position provided by @param dst. You may also pass NULL as
4750         * argument to this method, in that case this intrument will be moved to the
4751         * very end of the .gig file's instrument list.
4752         *
4753         * You have to call Save() to make the order change persistent to the .gig
4754         * file.
4755         *
4756         * Currently this method is limited to moving the instrument within the same
4757         * .gig file. Trying to move it to another .gig file by calling this method
4758         * will throw an exception.
4759         *
4760         * @param dst - destination instrument at which this instrument will be
4761         *              moved to, or pass NULL for moving to end of list
4762         * @throw gig::Exception if this instrument and target instrument are not
4763         *                       part of the same file
4764         */
4765        void Instrument::MoveTo(Instrument* dst) {
4766            if (dst && GetParent() != dst->GetParent())
4767                throw Exception(
4768                    "gig::Instrument::MoveTo() can only be used for moving within "
4769                    "the same gig file."
4770                );
4771    
4772            File* pFile = (File*) GetParent();
4773    
4774            // move this instrument within the instrument list
4775            {
4776                File::InstrumentList& list = *pFile->pInstruments;
4777    
4778                File::InstrumentList::iterator itFrom =
4779                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4780    
4781                File::InstrumentList::iterator itTo =
4782                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4783    
4784                list.splice(itTo, list, itFrom);
4785            }
4786    
4787            // move the instrument's actual list RIFF chunk appropriately
4788            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4789            lstCkInstruments->MoveSubChunk(
4790                this->pCkInstrument,
4791                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4792            );
4793        }
4794    
4795        /**
4796       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4797       *       *
4798       * 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 4855  namespace {
4855          pMidiRules[i] = 0;          pMidiRules[i] = 0;
4856      }      }
4857    
4858        void Instrument::LoadScripts() {
4859            if (pScriptRefs) return;
4860            pScriptRefs = new std::vector<_ScriptPooolRef>;
4861            if (scriptPoolFileOffsets.empty()) return;
4862            File* pFile = (File*) GetParent();
4863            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4864                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4865                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4866                    ScriptGroup* group = pFile->GetScriptGroup(i);
4867                    for (uint s = 0; group->GetScript(s); ++s) {
4868                        Script* script = group->GetScript(s);
4869                        if (script->pChunk) {
4870                            uint32_t offset = script->pChunk->GetFilePos() -
4871                                              script->pChunk->GetPos() -
4872                                              CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4873                            if (offset == soughtOffset)
4874                            {
4875                                _ScriptPooolRef ref;
4876                                ref.script = script;
4877                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4878                                pScriptRefs->push_back(ref);
4879                                break;
4880                            }
4881                        }
4882                    }
4883                }
4884            }
4885            // we don't need that anymore
4886            scriptPoolFileOffsets.clear();
4887        }
4888    
4889        /** @brief Get instrument script (gig format extension).
4890         *
4891         * Returns the real-time instrument script of instrument script slot
4892         * @a index.
4893         *
4894         * @note This is an own format extension which did not exist i.e. in the
4895         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4896         * gigedit.
4897         *
4898         * @param index - instrument script slot index
4899         * @returns script or NULL if index is out of bounds
4900         */
4901        Script* Instrument::GetScriptOfSlot(uint index) {
4902            LoadScripts();
4903            if (index >= pScriptRefs->size()) return NULL;
4904            return pScriptRefs->at(index).script;
4905        }
4906    
4907        /** @brief Add new instrument script slot (gig format extension).
4908         *
4909         * Add the given real-time instrument script reference to this instrument,
4910         * which shall be executed by the sampler for for this instrument. The
4911         * script will be added to the end of the script list of this instrument.
4912         * The positions of the scripts in the Instrument's Script list are
4913         * relevant, because they define in which order they shall be executed by
4914         * the sampler. For this reason it is also legal to add the same script
4915         * twice to an instrument, for example you might have a script called
4916         * "MyFilter" which performs an event filter task, and you might have
4917         * another script called "MyNoteTrigger" which triggers new notes, then you
4918         * might for example have the following list of scripts on the instrument:
4919         *
4920         * 1. Script "MyFilter"
4921         * 2. Script "MyNoteTrigger"
4922         * 3. Script "MyFilter"
4923         *
4924         * Which would make sense, because the 2nd script launched new events, which
4925         * you might need to filter as well.
4926         *
4927         * There are two ways to disable / "bypass" scripts. You can either disable
4928         * a script locally for the respective script slot on an instrument (i.e. by
4929         * passing @c false to the 2nd argument of this method, or by calling
4930         * SetScriptBypassed()). Or you can disable a script globally for all slots
4931         * and all instruments by setting Script::Bypass.
4932         *
4933         * @note This is an own format extension which did not exist i.e. in the
4934         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4935         * gigedit.
4936         *
4937         * @param pScript - script that shall be executed for this instrument
4938         * @param bypass  - if enabled, the sampler shall skip executing this
4939         *                  script (in the respective list position)
4940         * @see SetScriptBypassed()
4941         */
4942        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4943            LoadScripts();
4944            _ScriptPooolRef ref = { pScript, bypass };
4945            pScriptRefs->push_back(ref);
4946        }
4947    
4948        /** @brief Flip two script slots with each other (gig format extension).
4949         *
4950         * Swaps the position of the two given scripts in the Instrument's Script
4951         * list. The positions of the scripts in the Instrument's Script list are
4952         * relevant, because they define in which order they shall be executed by
4953         * the sampler.
4954         *
4955         * @note This is an own format extension which did not exist i.e. in the
4956         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4957         * gigedit.
4958         *
4959         * @param index1 - index of the first script slot to swap
4960         * @param index2 - index of the second script slot to swap
4961         */
4962        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4963            LoadScripts();
4964            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4965                return;
4966            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4967            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4968            (*pScriptRefs)[index2] = tmp;
4969        }
4970    
4971        /** @brief Remove script slot.
4972         *
4973         * Removes the script slot with the given slot index.
4974         *
4975         * @param index - index of script slot to remove
4976         */
4977        void Instrument::RemoveScriptSlot(uint index) {
4978            LoadScripts();
4979            if (index >= pScriptRefs->size()) return;
4980            pScriptRefs->erase( pScriptRefs->begin() + index );
4981        }
4982    
4983        /** @brief Remove reference to given Script (gig format extension).
4984         *
4985         * This will remove all script slots on the instrument which are referencing
4986         * the given script.
4987         *
4988         * @note This is an own format extension which did not exist i.e. in the
4989         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4990         * gigedit.
4991         *
4992         * @param pScript - script reference to remove from this instrument
4993         * @see RemoveScriptSlot()
4994         */
4995        void Instrument::RemoveScript(Script* pScript) {
4996            LoadScripts();
4997            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4998                if ((*pScriptRefs)[i].script == pScript) {
4999                    pScriptRefs->erase( pScriptRefs->begin() + i );
5000                }
5001            }
5002        }
5003    
5004        /** @brief Instrument's amount of script slots.
5005         *
5006         * This method returns the amount of script slots this instrument currently
5007         * uses.
5008         *
5009         * A script slot is a reference of a real-time instrument script to be
5010         * executed by the sampler. The scripts will be executed by the sampler in
5011         * sequence of the slots. One (same) script may be referenced multiple
5012         * times in different slots.
5013         *
5014         * @note This is an own format extension which did not exist i.e. in the
5015         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5016         * gigedit.
5017         */
5018        uint Instrument::ScriptSlotCount() const {
5019            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
5020        }
5021    
5022        /** @brief Whether script execution shall be skipped.
5023         *
5024         * Defines locally for the Script reference slot in the Instrument's Script
5025         * list, whether the script shall be skipped by the sampler regarding
5026         * execution.
5027         *
5028         * It is also possible to ignore exeuction of the script globally, for all
5029         * slots and for all instruments by setting Script::Bypass.
5030         *
5031         * @note This is an own format extension which did not exist i.e. in the
5032         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5033         * gigedit.
5034         *
5035         * @param index - index of the script slot on this instrument
5036         * @see Script::Bypass
5037         */
5038        bool Instrument::IsScriptSlotBypassed(uint index) {
5039            if (index >= ScriptSlotCount()) return false;
5040            return pScriptRefs ? pScriptRefs->at(index).bypass
5041                               : scriptPoolFileOffsets.at(index).bypass;
5042            
5043        }
5044    
5045        /** @brief Defines whether execution shall be skipped.
5046         *
5047         * You can call this method to define locally whether or whether not the
5048         * given script slot shall be executed by the sampler.
5049         *
5050         * @note This is an own format extension which did not exist i.e. in the
5051         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5052         * gigedit.
5053         *
5054         * @param index - script slot index on this instrument
5055         * @param bBypass - if true, the script slot will be skipped by the sampler
5056         * @see Script::Bypass
5057         */
5058        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5059            if (index >= ScriptSlotCount()) return;
5060            if (pScriptRefs)
5061                pScriptRefs->at(index).bypass = bBypass;
5062            else
5063                scriptPoolFileOffsets.at(index).bypass = bBypass;
5064        }
5065    
5066      /**      /**
5067       * 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
5068       * and assign it to this object.       * and assign it to this object.
# Line 4062  namespace { Line 5096  namespace {
5096          PitchbendRange = orig->PitchbendRange;          PitchbendRange = orig->PitchbendRange;
5097          PianoReleaseMode = orig->PianoReleaseMode;          PianoReleaseMode = orig->PianoReleaseMode;
5098          DimensionKeyRange = orig->DimensionKeyRange;          DimensionKeyRange = orig->DimensionKeyRange;
5099            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5100            pScriptRefs = orig->pScriptRefs;
5101                    
5102          // free old midi rules          // free old midi rules
5103          for (int i = 0 ; pMidiRules[i] ; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
# Line 4116  namespace { Line 5152  namespace {
5152       *       *
5153       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5154       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5155         *
5156         * @param pProgress - callback function for progress notification
5157       */       */
5158      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5159          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5160          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5161          if (!_3gri) {          if (!_3gri) {
# Line 4247  namespace { Line 5285  namespace {
5285          bAutoLoad = true;          bAutoLoad = true;
5286          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5287          pGroups = NULL;          pGroups = NULL;
5288            pScriptGroups = NULL;
5289          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5290          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5291    
# Line 4262  namespace { Line 5301  namespace {
5301      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5302          bAutoLoad = true;          bAutoLoad = true;
5303          pGroups = NULL;          pGroups = NULL;
5304            pScriptGroups = NULL;
5305          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5306      }      }
5307    
# Line 4275  namespace { Line 5315  namespace {
5315              }              }
5316              delete pGroups;              delete pGroups;
5317          }          }
5318            if (pScriptGroups) {
5319                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5320                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5321                while (iter != end) {
5322                    delete *iter;
5323                    ++iter;
5324                }
5325                delete pScriptGroups;
5326            }
5327      }      }
5328    
5329      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 4383  namespace { Line 5432  namespace {
5432          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5433    
5434          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5435            // (only for old gig files < 2 GB)
5436          int lastFileNo = 0;          int lastFileNo = 0;
5437          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5438              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5439                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5440                }
5441          }          }
5442          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5443          int nameLen = name.length();          int nameLen = name.length();
# Line 4395  namespace { Line 5447  namespace {
5447          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5448              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5449              if (wvpl) {              if (wvpl) {
5450                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5451                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5452                  while (wave) {                  while (wave) {
5453                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 4403  namespace { Line 5455  namespace {
5455                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5456                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5457    
5458                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5459                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5460    
5461                          iSampleIndex++;                          iSampleIndex++;
5462                      }                      }
# Line 4642  namespace { Line 5694  namespace {
5694          if (!_3crc) return;          if (!_3crc) return;
5695    
5696          // get the index of the sample          // get the index of the sample
5697          int iWaveIndex = -1;          int iWaveIndex = GetWaveTableIndexOf(pSample);
         File::SampleList::iterator iter = pSamples->begin();  
         File::SampleList::iterator end  = pSamples->end();  
         for (int index = 0; iter != end; ++iter, ++index) {  
             if (*iter == pSample) {  
                 iWaveIndex = index;  
                 break;  
             }  
         }  
5698          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");          if (iWaveIndex < 0) throw gig::Exception("Could not update crc, could not find sample");
5699    
5700          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5701          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5702          uint32_t tmp = 1;          uint32_t one = 1;
5703          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5704          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5705      }      }
5706    
5707        uint32_t File::GetSampleChecksum(Sample* pSample) {
5708            // get the index of the sample
5709            int iWaveIndex = GetWaveTableIndexOf(pSample);
5710            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5711    
5712            return GetSampleChecksumByIndex(iWaveIndex);
5713        }
5714    
5715        uint32_t File::GetSampleChecksumByIndex(int index) {
5716            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5717    
5718            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5719            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5720            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5721            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5722    
5723            // read the CRC-32 checksum directly from disk
5724            size_t pos = index * 8;
5725            if (pos + 8 > _3crc->GetNewSize())
5726                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5727    
5728            uint32_t one = load32(&pData[pos]); // always 1
5729            if (one != 1)
5730                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5731    
5732            return load32(&pData[pos+4]);
5733        }
5734    
5735        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5736            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5737            File::SampleList::iterator iter = pSamples->begin();
5738            File::SampleList::iterator end  = pSamples->end();
5739            for (int index = 0; iter != end; ++iter, ++index)
5740                if (*iter == pSample)
5741                    return index;
5742            return -1;
5743        }
5744    
5745        /**
5746         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5747         * the CRC32 check sums of all samples' raw wave data.
5748         *
5749         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5750         */
5751        bool File::VerifySampleChecksumTable() {
5752            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5753            if (!_3crc) return false;
5754            if (_3crc->GetNewSize() <= 0) return false;
5755            if (_3crc->GetNewSize() % 8) return false;
5756            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5757            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5758    
5759            const int n = _3crc->GetNewSize() / 8;
5760    
5761            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5762            if (!pData) return false;
5763    
5764            for (int i = 0; i < n; ++i) {
5765                uint32_t one = pData[i*2];
5766                if (one != 1) return false;
5767            }
5768    
5769            return true;
5770        }
5771    
5772        /**
5773         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5774         * file's checksum table with those new checksums. This might usually
5775         * just be necessary if the checksum table was damaged.
5776         *
5777         * @e IMPORTANT: The current implementation of this method only works
5778         * with files that have not been modified since it was loaded, because
5779         * it expects that no externally caused file structure changes are
5780         * required!
5781         *
5782         * Due to the expectation above, this method is currently protected
5783         * and actually only used by the command line tool "gigdump" yet.
5784         *
5785         * @returns true if Save() is required to be called after this call,
5786         *          false if no further action is required
5787         */
5788        bool File::RebuildSampleChecksumTable() {
5789            // make sure sample chunks were scanned
5790            if (!pSamples) GetFirstSample();
5791    
5792            bool bRequiresSave = false;
5793    
5794            // make sure "3CRC" chunk exists with required size
5795            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5796            if (!_3crc) {
5797                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5798                // the order of einf and 3crc is not the same in v2 and v3
5799                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5800                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5801                bRequiresSave = true;
5802            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5803                _3crc->Resize(pSamples->size() * 8);
5804                bRequiresSave = true;
5805            }
5806    
5807            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5808                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5809                {
5810                    File::SampleList::iterator iter = pSamples->begin();
5811                    File::SampleList::iterator end  = pSamples->end();
5812                    for (; iter != end; ++iter) {
5813                        gig::Sample* pSample = (gig::Sample*) *iter;
5814                        int index = GetWaveTableIndexOf(pSample);
5815                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5816                        pData[index*2]   = 1; // always 1
5817                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5818                    }
5819                }
5820            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5821                // make sure file is in write mode
5822                pRIFF->SetMode(RIFF::stream_mode_read_write);
5823                {
5824                    File::SampleList::iterator iter = pSamples->begin();
5825                    File::SampleList::iterator end  = pSamples->end();
5826                    for (; iter != end; ++iter) {
5827                        gig::Sample* pSample = (gig::Sample*) *iter;
5828                        int index = GetWaveTableIndexOf(pSample);
5829                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5830                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5831                        SetSampleChecksum(pSample, pSample->crc);
5832                    }
5833                }
5834            }
5835    
5836            return bRequiresSave;
5837        }
5838    
5839      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5840          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5841          // there must always be at least one group          // there must always be at least one group
# Line 4787  namespace { Line 5963  namespace {
5963          }          }
5964      }      }
5965    
5966        /** @brief Get instrument script group (by index).
5967         *
5968         * Returns the real-time instrument script group with the given index.
5969         *
5970         * @param index - number of the sought group (0..n)
5971         * @returns sought script group or NULL if there's no such group
5972         */
5973        ScriptGroup* File::GetScriptGroup(uint index) {
5974            if (!pScriptGroups) LoadScriptGroups();
5975            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5976            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5977                if (i == index) return *it;
5978            return NULL;
5979        }
5980    
5981        /** @brief Get instrument script group (by name).
5982         *
5983         * Returns the first real-time instrument script group found with the given
5984         * group name. Note that group names may not necessarily be unique.
5985         *
5986         * @param name - name of the sought script group
5987         * @returns sought script group or NULL if there's no such group
5988         */
5989        ScriptGroup* File::GetScriptGroup(const String& name) {
5990            if (!pScriptGroups) LoadScriptGroups();
5991            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5992            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5993                if ((*it)->Name == name) return *it;
5994            return NULL;
5995        }
5996    
5997        /** @brief Add new instrument script group.
5998         *
5999         * Adds a new, empty real-time instrument script group to the file.
6000         *
6001         * You have to call Save() to make this persistent to the file.
6002         *
6003         * @return new empty script group
6004         */
6005        ScriptGroup* File::AddScriptGroup() {
6006            if (!pScriptGroups) LoadScriptGroups();
6007            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6008            pScriptGroups->push_back(pScriptGroup);
6009            return pScriptGroup;
6010        }
6011    
6012        /** @brief Delete an instrument script group.
6013         *
6014         * This will delete the given real-time instrument script group and all its
6015         * instrument scripts it contains. References inside instruments that are
6016         * using the deleted scripts will be removed from the respective instruments
6017         * accordingly.
6018         *
6019         * You have to call Save() to make this persistent to the file.
6020         *
6021         * @param pScriptGroup - script group to delete
6022         * @throws gig::Exception if given script group could not be found
6023         */
6024        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6025            if (!pScriptGroups) LoadScriptGroups();
6026            std::list<ScriptGroup*>::iterator iter =
6027                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6028            if (iter == pScriptGroups->end())
6029                throw gig::Exception("Could not delete script group, could not find given script group");
6030            pScriptGroups->erase(iter);
6031            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6032                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6033            if (pScriptGroup->pList)
6034                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6035            delete pScriptGroup;
6036        }
6037    
6038        void File::LoadScriptGroups() {
6039            if (pScriptGroups) return;
6040            pScriptGroups = new std::list<ScriptGroup*>;
6041            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6042            if (lstLS) {
6043                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6044                     lst = lstLS->GetNextSubList())
6045                {
6046                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6047                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6048                    }
6049                }
6050            }
6051        }
6052    
6053      /**      /**
6054       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6055       * 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 6058  namespace {
6058       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6059       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6060       *       *
6061         * @param pProgress - callback function for progress notification
6062       * @throws Exception - on errors       * @throws Exception - on errors
6063       */       */
6064      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6065          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6066    
6067          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6068            // (not part of the GigaStudio 4 format)
6069            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6070            if (!lst3LS) {
6071                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6072            }
6073            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6074            // location of <3LS > is irrelevant, however it should be located
6075            // before  the actual wave data
6076            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6077            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6078    
6079            // This must be performed before writing the chunks for instruments,
6080            // because the instruments' script slots will write the file offsets
6081            // of the respective instrument script chunk as reference.
6082            if (pScriptGroups) {
6083                // Update instrument script (group) chunks.
6084                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6085                     it != pScriptGroups->end(); ++it)
6086                {
6087                    (*it)->UpdateChunks(pProgress);
6088                }
6089            }
6090    
6091            // in case no libgig custom format data was added, then remove the
6092            // custom "3LS " chunk again
6093            if (!lst3LS->CountSubChunks()) {
6094                pRIFF->DeleteSubChunk(lst3LS);
6095                lst3LS = NULL;
6096            }
6097    
6098          // first update base class's chunks          // first update base class's chunks
6099          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6100    
6101          if (newFile) {          if (newFile) {
6102              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 4840  namespace { Line 6133  namespace {
6133              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
6134              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
6135              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
6136                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
6137              }              }
6138          }          }
6139    
# Line 4958  namespace { Line 6251  namespace {
6251          // update 3crc chunk          // update 3crc chunk
6252    
6253          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6254          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6255          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6256            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6257            // member variable). This step is required, because samples might have
6258            // been deleted by the user since the file was opened, which in turn
6259            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6260            // If a sample was conciously modified by the user (that is if
6261            // Sample::Write() was called later on) then Sample::Write() will just
6262            // update the respective individual checksum(s) directly on disk and
6263            // leaves all other sample checksums untouched.
6264    
6265          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6266          if (_3crc) {          if (_3crc) {
6267              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6268          } else if (newFile) {          } else /*if (newFile)*/ {
6269              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6270              // the order of einf and 3crc is not the same in v2 and v3              // the order of einf and 3crc is not the same in v2 and v3
6271              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6272          }          }
6273            { // must be performed in RAM here ...
6274                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6275                if (pData) {
6276                    File::SampleList::iterator iter = pSamples->begin();
6277                    File::SampleList::iterator end  = pSamples->end();
6278                    for (int index = 0; iter != end; ++iter, ++index) {
6279                        gig::Sample* pSample = (gig::Sample*) *iter;
6280                        pData[index*2]   = 1; // always 1
6281                        pData[index*2+1] = pSample->crc;
6282                    }
6283                }
6284            }
6285        }
6286        
6287        void File::UpdateFileOffsets() {
6288            DLS::File::UpdateFileOffsets();
6289    
6290            for (Instrument* instrument = GetFirstInstrument(); instrument;
6291                 instrument = GetNextInstrument())
6292            {
6293                instrument->UpdateScriptFileOffsets();
6294            }
6295      }      }
6296    
6297      /**      /**

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

  ViewVC Help
Powered by ViewVC