/[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 2557 by schoenebeck, Sat May 17 23:31:20 2014 UTC revision 2985 by schoenebeck, Tue Sep 20 22:13:37 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 30  Line 30 
30  #include <iostream>  #include <iostream>
31  #include <assert.h>  #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
39  /// the biggest sample piece expected to be read by the sampler engine,  /// the biggest sample piece expected to be read by the sampler engine,
# Line 53  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 123  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 160  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 346  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 367  namespace { Line 339  namespace {
339       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
340       *                         is located, 0 otherwise       *                         is located, 0 otherwise
341       */       */
342      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {
343          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
344              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
345              { 0, 0 }              { 0, 0 }
# Line 509  namespace { Line 481  namespace {
481          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
482          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
483          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
484          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
485          pOrig->SetPos(0);          pOrig->SetPos(0);
486          SetPos(0);          SetPos(0);
487          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
488                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
489          {          {
490              Write(buf, n);              Write(buf, n);
# Line 528  namespace { Line 500  namespace {
500       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
501       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
502       *       *
503         * @param pProgress - callback function for progress notification
504       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
505       *                        was provided yet       *                        was provided yet
506       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
507       */       */
508      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
509          // first update base class's chunks          // first update base class's chunks
510          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
511    
512          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
513          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 596  namespace { Line 569  namespace {
569      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
570          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
571          this->SamplesTotal = 0;          this->SamplesTotal = 0;
572          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
573    
574          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
575          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 612  namespace { Line 585  namespace {
585                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
586                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
587                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
588                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
589    
590                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
591                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 631  namespace { Line 604  namespace {
604    
605                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
606                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
607                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
608    
609                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
610                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 647  namespace { Line 620  namespace {
620    
621          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
622          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
623          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
624          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
625          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
626          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
627              FrameTable[i] = *iter;              FrameTable[i] = *iter;
628          }          }
# Line 690  namespace { Line 663  namespace {
663       *                      the cached sample data in bytes       *                      the cached sample data in bytes
664       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
665       */       */
666      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
667          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
668      }      }
669    
# Line 749  namespace { Line 722  namespace {
722       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
723       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
724       */       */
725      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
726          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
727          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
728          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
729          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
730          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
731          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 816  namespace { Line 789  namespace {
789       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
790       * other formats will fail!       * other formats will fail!
791       *       *
792       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
793       *                   greater than zero)       *                  greater than zero)
794       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
795       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
796       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
797       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
798       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
799       */       */
800      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
801          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
802          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
803      }      }
804    
805      /**      /**
# Line 850  namespace { Line 823  namespace {
823       * @returns            the new sample position       * @returns            the new sample position
824       * @see                Read()       * @see                Read()
825       */       */
826      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
827          if (Compressed) {          if (Compressed) {
828              switch (Whence) {              switch (Whence) {
829                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 868  namespace { Line 841  namespace {
841              }              }
842              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
843    
844              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
845              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
846              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
847              return this->SamplePos;              return this->SamplePos;
848          }          }
849          else { // not compressed          else { // not compressed
850              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
851              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
852              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
853                                              : result / this->FrameSize;                                              : result / this->FrameSize;
854          }          }
# Line 884  namespace { Line 857  namespace {
857      /**      /**
858       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
859       */       */
860      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
861          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
862          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
863      }      }
# Line 923  namespace { Line 896  namespace {
896       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
897       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
898       */       */
899      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
900                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
901          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
902          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
903    
904          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 963  namespace { Line 936  namespace {
936                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
937                                  // backward playback                                  // backward playback
938    
939                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
940                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
941                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
942                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
943    
944                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
945    
# Line 1014  namespace { Line 987  namespace {
987                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
988                          // backward playback                          // backward playback
989    
990                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
991                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
992                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
993                                                                                    : samplestoread;                                                                                    : samplestoread;
994                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
995    
996                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
997    
# Line 1098  namespace { Line 1071  namespace {
1071       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1072       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1073       */       */
1074      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1075          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1076          if (!Compressed) {          if (!Compressed) {
1077              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1113  namespace { Line 1086  namespace {
1086          else {          else {
1087              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1088              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1089              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1090                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1091                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1092                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1136  namespace { Line 1109  namespace {
1109              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1110    
1111              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1112                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1113                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1114    
1115                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1116    
# Line 1287  namespace { Line 1260  namespace {
1260       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1261       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1262       */       */
1263      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1264          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1265    
1266          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
# Line 1296  namespace { Line 1269  namespace {
1269              __resetCRC(crc);              __resetCRC(crc);
1270          }          }
1271          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1272          unsigned long res;          file_offset_t res;
1273          if (BitDepth == 24) {          if (BitDepth == 24) {
1274              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1275          } else { // 16 bit          } else { // 16 bit
# Line 1330  namespace { Line 1303  namespace {
1303       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1304       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1305       */       */
1306      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1307          buffer_t result;          buffer_t result;
1308          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1309                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;                  (256.0 /*frame size*/ + 12.0 /*header*/ + 2.0 /*compression type flag (stereo)*/) / 256.0;
1310          result.Size              = (unsigned long) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);          result.Size              = (file_offset_t) (double(MaxReadSize) * 3.0 /*(24 Bit)*/ * 2.0 /*stereo*/ * worstCaseHeaderOverhead);
1311          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1312          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1313          return result;          return result;
# Line 1368  namespace { Line 1341  namespace {
1341          return pGroup;          return pGroup;
1342      }      }
1343    
1344        /**
1345         * Checks the integrity of this sample's raw audio wave data. Whenever a
1346         * Sample's raw wave data is intentionally modified (i.e. by calling
1347         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1348         * is calculated and stored/updated for this sample, along to the sample's
1349         * meta informations.
1350         *
1351         * Now by calling this method the current raw audio wave data is checked
1352         * against the already stored CRC32 check sum in order to check whether the
1353         * sample data had been damaged unintentionally for some reason. Since by
1354         * calling this method always the entire raw audio wave data has to be
1355         * read, verifying all samples this way may take a long time accordingly.
1356         * And that's also the reason why the sample integrity is not checked by
1357         * default whenever a gig file is loaded. So this method must be called
1358         * explicitly to fulfill this task.
1359         *
1360         * @returns true if sample is OK or false if the sample is damaged
1361         * @throws Exception if no checksum had been stored to disk for this
1362         *         sample yet, or on I/O issues
1363         */
1364        bool Sample::VerifyWaveData() {
1365            File* pFile = static_cast<File*>(GetParent());
1366            const uint32_t referenceCRC = pFile->GetSampleChecksum(this);
1367            uint32_t crc = CalculateWaveDataChecksum();
1368            return crc == referenceCRC;
1369        }
1370    
1371        uint32_t Sample::CalculateWaveDataChecksum() {
1372            const size_t sz = 20*1024; // 20kB buffer size
1373            std::vector<uint8_t> buffer(sz);
1374            buffer.resize(sz);
1375    
1376            const size_t n = sz / FrameSize;
1377            SetPos(0);
1378            uint32_t crc = 0;
1379            __resetCRC(crc);
1380            while (true) {
1381                file_offset_t nRead = Read(&buffer[0], n);
1382                if (nRead <= 0) break;
1383                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1384            }
1385            __encodeCRC(crc);
1386            return crc;
1387        }
1388    
1389      Sample::~Sample() {      Sample::~Sample() {
1390          Instances--;          Instances--;
1391          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1384  namespace { Line 1402  namespace {
1402  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1403  // *  // *
1404    
1405      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1406      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1407    
1408      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1752  namespace { Line 1770  namespace {
1770       *       *
1771       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1772       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1773         *
1774         * @param pProgress - callback function for progress notification
1775       */       */
1776      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1777          // first update base class's chunk          // first update base class's chunk
1778          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1779    
1780          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1781          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 3026  namespace { Line 3046  namespace {
3046       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3047       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3048       *       *
3049         * @param pProgress - callback function for progress notification
3050       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3051       */       */
3052      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3053          // 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
3054          // 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
3055          // 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 3036  namespace { Line 3057  namespace {
3057          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3058    
3059          // first update base class's chunks          // first update base class's chunks
3060          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3061    
3062          // update dimension region's chunks          // update dimension region's chunks
3063          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3064              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3065          }          }
3066    
3067          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 3056  namespace { Line 3077  namespace {
3077              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3078    
3079              // move 3prg to last position              // move 3prg to last position
3080              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3081          }          }
3082    
3083          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 3130  namespace { Line 3151  namespace {
3151          int step = 1;          int step = 1;
3152          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3153          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3154    
3155          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3156          int dim[8] = { 0 };          int dim[8] = { 0 };
3157          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3158                const int end = i + step * pDimensionDefinitions[veldim].zones;
3159    
3160                // create a velocity table for all cases where the velocity zone is zero
3161              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3162                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3163                  // create the velocity table                  // create the velocity table
# Line 3166  namespace { Line 3188  namespace {
3188                  }                  }
3189              }              }
3190    
3191                // jump to the next case where the velocity zone is zero
3192              int j;              int j;
3193              int shift = 0;              int shift = 0;
3194              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3652  namespace { Line 3675  namespace {
3675          UpdateVelocityTable();          UpdateVelocityTable();
3676      }      }
3677    
3678        /** @brief Change type of an existing dimension.
3679         *
3680         * Alters the dimension type of a dimension already existing on this
3681         * region. If there is currently no dimension on this Region with type
3682         * @a oldType, then this call with throw an Exception. Likewise there are
3683         * cases where the requested dimension type cannot be performed. For example
3684         * if the new dimension type shall be gig::dimension_samplechannel, and the
3685         * current dimension has more than 2 zones. In such cases an Exception is
3686         * thrown as well.
3687         *
3688         * @param oldType - identifies the existing dimension to be changed
3689         * @param newType - to which dimension type it should be changed to
3690         * @throws gig::Exception if requested change cannot be performed
3691         */
3692        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3693            if (oldType == newType) return;
3694            dimension_def_t* def = GetDimensionDefinition(oldType);
3695            if (!def)
3696                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3697            if (newType == dimension_samplechannel && def->zones != 2)
3698                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3699            if (GetDimensionDefinition(newType))
3700                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3701            def->dimension  = newType;
3702            def->split_type = __resolveSplitType(newType);
3703        }
3704    
3705      DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {      DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3706          uint8_t bits[8] = {};          uint8_t bits[8] = {};
3707          for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();          for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
# Line 3743  namespace { Line 3793  namespace {
3793              }              }
3794              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3795          }          }
3796          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3797            if (!dimreg) return NULL;
3798          if (veldim != -1) {          if (veldim != -1) {
3799              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3800              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3801                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3802              else // normal split type              else // normal split type
3803                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3804    
3805              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3806              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3807                dimreg = pDimensionRegions[dimregidx & 255];
3808          }          }
3809          return dimreg;          return dimreg;
3810      }      }
3811    
3812        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3813            uint8_t bits;
3814            int veldim = -1;
3815            int velbitpos;
3816            int bitpos = 0;
3817            int dimregidx = 0;
3818            for (uint i = 0; i < Dimensions; i++) {
3819                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3820                    // the velocity dimension must be handled after the other dimensions
3821                    veldim = i;
3822                    velbitpos = bitpos;
3823                } else {
3824                    switch (pDimensionDefinitions[i].split_type) {
3825                        case split_type_normal:
3826                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3827                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3828                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3829                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3830                                }
3831                            } else {
3832                                // gig2: evenly sized zones
3833                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3834                            }
3835                            break;
3836                        case split_type_bit: // the value is already the sought dimension bit number
3837                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3838                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3839                            break;
3840                    }
3841                    dimregidx |= bits << bitpos;
3842                }
3843                bitpos += pDimensionDefinitions[i].bits;
3844            }
3845            dimregidx &= 255;
3846            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3847            if (!dimreg) return -1;
3848            if (veldim != -1) {
3849                // (dimreg is now the dimension region for the lowest velocity)
3850                if (dimreg->VelocityTable) // custom defined zone ranges
3851                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3852                else // normal split type
3853                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3854    
3855                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3856                dimregidx |= (bits & limiter_mask) << velbitpos;
3857                dimregidx &= 255;
3858            }
3859            return dimregidx;
3860        }
3861    
3862      /**      /**
3863       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3864       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 3795  namespace { Line 3897  namespace {
3897          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3898          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3899          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3900          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3901          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3902          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
3903          while (sample) {              uint64_t soughtoffset =
3904              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3905                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3906              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
3907                while (sample) {
3908                    if (sample->ullWavePoolOffset == soughtoffset)
3909                        return static_cast<gig::Sample*>(sample);
3910                    sample = file->GetNextSample();
3911                }
3912            } else {
3913                // use extension files and 32 bit wave pool offsets
3914                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3915                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3916                Sample* sample = file->GetFirstSample(pProgress);
3917                while (sample) {
3918                    if (sample->ullWavePoolOffset == soughtoffset &&
3919                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3920                    sample = file->GetNextSample();
3921                }
3922          }          }
3923          return NULL;          return NULL;
3924      }      }
# Line 4023  namespace { Line 4140  namespace {
4140          }          }
4141      }      }
4142    
4143    // *************** Script ***************
4144    // *
4145    
4146        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4147            pGroup = group;
4148            pChunk = ckScri;
4149            if (ckScri) { // object is loaded from file ...
4150                // read header
4151                uint32_t headerSize = ckScri->ReadUint32();
4152                Compression = (Compression_t) ckScri->ReadUint32();
4153                Encoding    = (Encoding_t) ckScri->ReadUint32();
4154                Language    = (Language_t) ckScri->ReadUint32();
4155                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4156                crc         = ckScri->ReadUint32();
4157                uint32_t nameSize = ckScri->ReadUint32();
4158                Name.resize(nameSize, ' ');
4159                for (int i = 0; i < nameSize; ++i)
4160                    Name[i] = ckScri->ReadUint8();
4161                // to handle potential future extensions of the header
4162                ckScri->SetPos(sizeof(int32_t) + headerSize);
4163                // read actual script data
4164                uint32_t scriptSize = ckScri->GetSize() - ckScri->GetPos();
4165                data.resize(scriptSize);
4166                for (int i = 0; i < scriptSize; ++i)
4167                    data[i] = ckScri->ReadUint8();
4168            } else { // this is a new script object, so just initialize it as such ...
4169                Compression = COMPRESSION_NONE;
4170                Encoding = ENCODING_ASCII;
4171                Language = LANGUAGE_NKSP;
4172                Bypass   = false;
4173                crc      = 0;
4174                Name     = "Unnamed Script";
4175            }
4176        }
4177    
4178        Script::~Script() {
4179        }
4180    
4181        /**
4182         * Returns the current script (i.e. as source code) in text format.
4183         */
4184        String Script::GetScriptAsText() {
4185            String s;
4186            s.resize(data.size(), ' ');
4187            memcpy(&s[0], &data[0], data.size());
4188            return s;
4189        }
4190    
4191        /**
4192         * Replaces the current script with the new script source code text given
4193         * by @a text.
4194         *
4195         * @param text - new script source code
4196         */
4197        void Script::SetScriptAsText(const String& text) {
4198            data.resize(text.size());
4199            memcpy(&data[0], &text[0], text.size());
4200        }
4201    
4202        /**
4203         * Apply this script to the respective RIFF chunks. You have to call
4204         * File::Save() to make changes persistent.
4205         *
4206         * Usually there is absolutely no need to call this method explicitly.
4207         * It will be called automatically when File::Save() was called.
4208         *
4209         * @param pProgress - callback function for progress notification
4210         */
4211        void Script::UpdateChunks(progress_t* pProgress) {
4212            // recalculate CRC32 check sum
4213            __resetCRC(crc);
4214            __calculateCRC(&data[0], data.size(), crc);
4215            __encodeCRC(crc);
4216            // make sure chunk exists and has the required size
4217            const int chunkSize = 7*sizeof(int32_t) + Name.size() + data.size();
4218            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4219            else pChunk->Resize(chunkSize);
4220            // fill the chunk data to be written to disk
4221            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4222            int pos = 0;
4223            store32(&pData[pos], 6*sizeof(int32_t) + Name.size()); // total header size
4224            pos += sizeof(int32_t);
4225            store32(&pData[pos], Compression);
4226            pos += sizeof(int32_t);
4227            store32(&pData[pos], Encoding);
4228            pos += sizeof(int32_t);
4229            store32(&pData[pos], Language);
4230            pos += sizeof(int32_t);
4231            store32(&pData[pos], Bypass ? 1 : 0);
4232            pos += sizeof(int32_t);
4233            store32(&pData[pos], crc);
4234            pos += sizeof(int32_t);
4235            store32(&pData[pos], Name.size());
4236            pos += sizeof(int32_t);
4237            for (int i = 0; i < Name.size(); ++i, ++pos)
4238                pData[pos] = Name[i];
4239            for (int i = 0; i < data.size(); ++i, ++pos)
4240                pData[pos] = data[i];
4241        }
4242    
4243        /**
4244         * Move this script from its current ScriptGroup to another ScriptGroup
4245         * given by @a pGroup.
4246         *
4247         * @param pGroup - script's new group
4248         */
4249        void Script::SetGroup(ScriptGroup* pGroup) {
4250            if (this->pGroup == pGroup) return;
4251            if (pChunk)
4252                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4253            this->pGroup = pGroup;
4254        }
4255    
4256        /**
4257         * Returns the script group this script currently belongs to. Each script
4258         * is a member of exactly one ScriptGroup.
4259         *
4260         * @returns current script group
4261         */
4262        ScriptGroup* Script::GetGroup() const {
4263            return pGroup;
4264        }
4265    
4266        void Script::RemoveAllScriptReferences() {
4267            File* pFile = pGroup->pFile;
4268            for (int i = 0; pFile->GetInstrument(i); ++i) {
4269                Instrument* instr = pFile->GetInstrument(i);
4270                instr->RemoveScript(this);
4271            }
4272        }
4273    
4274    // *************** ScriptGroup ***************
4275    // *
4276    
4277        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4278            pFile = file;
4279            pList = lstRTIS;
4280            pScripts = NULL;
4281            if (lstRTIS) {
4282                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4283                ::LoadString(ckName, Name);
4284            } else {
4285                Name = "Default Group";
4286            }
4287        }
4288    
4289        ScriptGroup::~ScriptGroup() {
4290            if (pScripts) {
4291                std::list<Script*>::iterator iter = pScripts->begin();
4292                std::list<Script*>::iterator end  = pScripts->end();
4293                while (iter != end) {
4294                    delete *iter;
4295                    ++iter;
4296                }
4297                delete pScripts;
4298            }
4299        }
4300    
4301        /**
4302         * Apply this script group to the respective RIFF chunks. You have to call
4303         * File::Save() to make changes persistent.
4304         *
4305         * Usually there is absolutely no need to call this method explicitly.
4306         * It will be called automatically when File::Save() was called.
4307         *
4308         * @param pProgress - callback function for progress notification
4309         */
4310        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4311            if (pScripts) {
4312                if (!pList)
4313                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4314    
4315                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4316                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4317    
4318                for (std::list<Script*>::iterator it = pScripts->begin();
4319                     it != pScripts->end(); ++it)
4320                {
4321                    (*it)->UpdateChunks(pProgress);
4322                }
4323            }
4324        }
4325    
4326        /** @brief Get instrument script.
4327         *
4328         * Returns the real-time instrument script with the given index.
4329         *
4330         * @param index - number of the sought script (0..n)
4331         * @returns sought script or NULL if there's no such script
4332         */
4333        Script* ScriptGroup::GetScript(uint index) {
4334            if (!pScripts) LoadScripts();
4335            std::list<Script*>::iterator it = pScripts->begin();
4336            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4337                if (i == index) return *it;
4338            return NULL;
4339        }
4340    
4341        /** @brief Add new instrument script.
4342         *
4343         * Adds a new real-time instrument script to the file. The script is not
4344         * actually used / executed unless it is referenced by an instrument to be
4345         * used. This is similar to samples, which you can add to a file, without
4346         * an instrument necessarily actually using it.
4347         *
4348         * You have to call Save() to make this persistent to the file.
4349         *
4350         * @return new empty script object
4351         */
4352        Script* ScriptGroup::AddScript() {
4353            if (!pScripts) LoadScripts();
4354            Script* pScript = new Script(this, NULL);
4355            pScripts->push_back(pScript);
4356            return pScript;
4357        }
4358    
4359        /** @brief Delete an instrument script.
4360         *
4361         * This will delete the given real-time instrument script. References of
4362         * instruments that are using that script will be removed accordingly.
4363         *
4364         * You have to call Save() to make this persistent to the file.
4365         *
4366         * @param pScript - script to delete
4367         * @throws gig::Exception if given script could not be found
4368         */
4369        void ScriptGroup::DeleteScript(Script* pScript) {
4370            if (!pScripts) LoadScripts();
4371            std::list<Script*>::iterator iter =
4372                find(pScripts->begin(), pScripts->end(), pScript);
4373            if (iter == pScripts->end())
4374                throw gig::Exception("Could not delete script, could not find given script");
4375            pScripts->erase(iter);
4376            pScript->RemoveAllScriptReferences();
4377            if (pScript->pChunk)
4378                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4379            delete pScript;
4380        }
4381    
4382        void ScriptGroup::LoadScripts() {
4383            if (pScripts) return;
4384            pScripts = new std::list<Script*>;
4385            if (!pList) return;
4386    
4387            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4388                 ck = pList->GetNextSubChunk())
4389            {
4390                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4391                    pScripts->push_back(new Script(this, ck));
4392                }
4393            }
4394        }
4395    
4396  // *************** Instrument ***************  // *************** Instrument ***************
4397  // *  // *
4398    
# Line 4045  namespace { Line 4415  namespace {
4415          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4416          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4417          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4418            pScriptRefs = NULL;
4419    
4420          // Loading          // Loading
4421          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 4105  namespace { Line 4476  namespace {
4476              }              }
4477          }          }
4478    
4479            // own gig format extensions
4480            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4481            if (lst3LS) {
4482                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4483                if (ckSCSL) {
4484                    int headerSize = ckSCSL->ReadUint32();
4485                    int slotCount  = ckSCSL->ReadUint32();
4486                    if (slotCount) {
4487                        int slotSize  = ckSCSL->ReadUint32();
4488                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4489                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4490                        for (int i = 0; i < slotCount; ++i) {
4491                            _ScriptPooolEntry e;
4492                            e.fileOffset = ckSCSL->ReadUint32();
4493                            e.bypass     = ckSCSL->ReadUint32() & 1;
4494                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4495                            scriptPoolFileOffsets.push_back(e);
4496                        }
4497                    }
4498                }
4499            }
4500    
4501          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4502      }      }
4503    
# Line 4125  namespace { Line 4518  namespace {
4518              delete pMidiRules[i];              delete pMidiRules[i];
4519          }          }
4520          delete[] pMidiRules;          delete[] pMidiRules;
4521            if (pScriptRefs) delete pScriptRefs;
4522      }      }
4523    
4524      /**      /**
# Line 4134  namespace { Line 4528  namespace {
4528       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4529       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4530       *       *
4531         * @param pProgress - callback function for progress notification
4532       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4533       */       */
4534      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4535          // first update base classes' chunks          // first update base classes' chunks
4536          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4537    
4538          // update Regions' chunks          // update Regions' chunks
4539          {          {
4540              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4541              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4542              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4543                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4544          }          }
4545    
4546          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 4180  namespace { Line 4575  namespace {
4575                  pMidiRules[i]->UpdateChunks(pData);                  pMidiRules[i]->UpdateChunks(pData);
4576              }              }
4577          }          }
4578    
4579            // own gig format extensions
4580           if (ScriptSlotCount()) {
4581               // make sure we have converted the original loaded script file
4582               // offsets into valid Script object pointers
4583               LoadScripts();
4584    
4585               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4586               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4587               const int slotCount = pScriptRefs->size();
4588               const int headerSize = 3 * sizeof(uint32_t);
4589               const int slotSize  = 2 * sizeof(uint32_t);
4590               const int totalChunkSize = headerSize + slotCount * slotSize;
4591               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4592               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4593               else ckSCSL->Resize(totalChunkSize);
4594               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4595               int pos = 0;
4596               store32(&pData[pos], headerSize);
4597               pos += sizeof(uint32_t);
4598               store32(&pData[pos], slotCount);
4599               pos += sizeof(uint32_t);
4600               store32(&pData[pos], slotSize);
4601               pos += sizeof(uint32_t);
4602               for (int i = 0; i < slotCount; ++i) {
4603                   // arbitrary value, the actual file offset will be updated in
4604                   // UpdateScriptFileOffsets() after the file has been resized
4605                   int bogusFileOffset = 0;
4606                   store32(&pData[pos], bogusFileOffset);
4607                   pos += sizeof(uint32_t);
4608                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4609                   pos += sizeof(uint32_t);
4610               }
4611           } else {
4612               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4613               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4614               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4615           }
4616        }
4617    
4618        void Instrument::UpdateScriptFileOffsets() {
4619           // own gig format extensions
4620           if (pScriptRefs && pScriptRefs->size() > 0) {
4621               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4622               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4623               const int slotCount = pScriptRefs->size();
4624               const int headerSize = 3 * sizeof(uint32_t);
4625               ckSCSL->SetPos(headerSize);
4626               for (int i = 0; i < slotCount; ++i) {
4627                   uint32_t fileOffset =
4628                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4629                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4630                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize());
4631                   ckSCSL->WriteUint32(&fileOffset);
4632                   // jump over flags entry (containing the bypass flag)
4633                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4634               }
4635           }        
4636      }      }
4637    
4638      /**      /**
# Line 4249  namespace { Line 4702  namespace {
4702      }      }
4703    
4704      /**      /**
4705         * Move this instrument at the position before @arg dst.
4706         *
4707         * This method can be used to reorder the sequence of instruments in a
4708         * .gig file. This might be helpful especially on large .gig files which
4709         * contain a large number of instruments within the same .gig file. So
4710         * grouping such instruments to similar ones, can help to keep track of them
4711         * when working with such complex .gig files.
4712         *
4713         * When calling this method, this instrument will be removed from in its
4714         * current position in the instruments list and moved to the requested
4715         * target position provided by @param dst. You may also pass NULL as
4716         * argument to this method, in that case this intrument will be moved to the
4717         * very end of the .gig file's instrument list.
4718         *
4719         * You have to call Save() to make the order change persistent to the .gig
4720         * file.
4721         *
4722         * Currently this method is limited to moving the instrument within the same
4723         * .gig file. Trying to move it to another .gig file by calling this method
4724         * will throw an exception.
4725         *
4726         * @param dst - destination instrument at which this instrument will be
4727         *              moved to, or pass NULL for moving to end of list
4728         * @throw gig::Exception if this instrument and target instrument are not
4729         *                       part of the same file
4730         */
4731        void Instrument::MoveTo(Instrument* dst) {
4732            if (dst && GetParent() != dst->GetParent())
4733                throw Exception(
4734                    "gig::Instrument::MoveTo() can only be used for moving within "
4735                    "the same gig file."
4736                );
4737    
4738            File* pFile = (File*) GetParent();
4739    
4740            // move this instrument within the instrument list
4741            {
4742                File::InstrumentList& list = *pFile->pInstruments;
4743    
4744                File::InstrumentList::iterator itFrom =
4745                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4746    
4747                File::InstrumentList::iterator itTo =
4748                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4749    
4750                list.splice(itTo, list, itFrom);
4751            }
4752    
4753            // move the instrument's actual list RIFF chunk appropriately
4754            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4755            lstCkInstruments->MoveSubChunk(
4756                this->pCkInstrument,
4757                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4758            );
4759        }
4760    
4761        /**
4762       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4763       *       *
4764       * 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 4311  namespace { Line 4821  namespace {
4821          pMidiRules[i] = 0;          pMidiRules[i] = 0;
4822      }      }
4823    
4824        void Instrument::LoadScripts() {
4825            if (pScriptRefs) return;
4826            pScriptRefs = new std::vector<_ScriptPooolRef>;
4827            if (scriptPoolFileOffsets.empty()) return;
4828            File* pFile = (File*) GetParent();
4829            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4830                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4831                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4832                    ScriptGroup* group = pFile->GetScriptGroup(i);
4833                    for (uint s = 0; group->GetScript(s); ++s) {
4834                        Script* script = group->GetScript(s);
4835                        if (script->pChunk) {
4836                            uint32_t offset = script->pChunk->GetFilePos() -
4837                                              script->pChunk->GetPos() -
4838                                              CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize());
4839                            if (offset == soughtOffset)
4840                            {
4841                                _ScriptPooolRef ref;
4842                                ref.script = script;
4843                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4844                                pScriptRefs->push_back(ref);
4845                                break;
4846                            }
4847                        }
4848                    }
4849                }
4850            }
4851            // we don't need that anymore
4852            scriptPoolFileOffsets.clear();
4853        }
4854    
4855        /** @brief Get instrument script (gig format extension).
4856         *
4857         * Returns the real-time instrument script of instrument script slot
4858         * @a index.
4859         *
4860         * @note This is an own format extension which did not exist i.e. in the
4861         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4862         * gigedit.
4863         *
4864         * @param index - instrument script slot index
4865         * @returns script or NULL if index is out of bounds
4866         */
4867        Script* Instrument::GetScriptOfSlot(uint index) {
4868            LoadScripts();
4869            if (index >= pScriptRefs->size()) return NULL;
4870            return pScriptRefs->at(index).script;
4871        }
4872    
4873        /** @brief Add new instrument script slot (gig format extension).
4874         *
4875         * Add the given real-time instrument script reference to this instrument,
4876         * which shall be executed by the sampler for for this instrument. The
4877         * script will be added to the end of the script list of this instrument.
4878         * The positions of the scripts in the Instrument's Script list are
4879         * relevant, because they define in which order they shall be executed by
4880         * the sampler. For this reason it is also legal to add the same script
4881         * twice to an instrument, for example you might have a script called
4882         * "MyFilter" which performs an event filter task, and you might have
4883         * another script called "MyNoteTrigger" which triggers new notes, then you
4884         * might for example have the following list of scripts on the instrument:
4885         *
4886         * 1. Script "MyFilter"
4887         * 2. Script "MyNoteTrigger"
4888         * 3. Script "MyFilter"
4889         *
4890         * Which would make sense, because the 2nd script launched new events, which
4891         * you might need to filter as well.
4892         *
4893         * There are two ways to disable / "bypass" scripts. You can either disable
4894         * a script locally for the respective script slot on an instrument (i.e. by
4895         * passing @c false to the 2nd argument of this method, or by calling
4896         * SetScriptBypassed()). Or you can disable a script globally for all slots
4897         * and all instruments by setting Script::Bypass.
4898         *
4899         * @note This is an own format extension which did not exist i.e. in the
4900         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4901         * gigedit.
4902         *
4903         * @param pScript - script that shall be executed for this instrument
4904         * @param bypass  - if enabled, the sampler shall skip executing this
4905         *                  script (in the respective list position)
4906         * @see SetScriptBypassed()
4907         */
4908        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4909            LoadScripts();
4910            _ScriptPooolRef ref = { pScript, bypass };
4911            pScriptRefs->push_back(ref);
4912        }
4913    
4914        /** @brief Flip two script slots with each other (gig format extension).
4915         *
4916         * Swaps the position of the two given scripts in the Instrument's Script
4917         * list. The positions of the scripts in the Instrument's Script list are
4918         * relevant, because they define in which order they shall be executed by
4919         * the sampler.
4920         *
4921         * @note This is an own format extension which did not exist i.e. in the
4922         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4923         * gigedit.
4924         *
4925         * @param index1 - index of the first script slot to swap
4926         * @param index2 - index of the second script slot to swap
4927         */
4928        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4929            LoadScripts();
4930            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4931                return;
4932            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4933            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4934            (*pScriptRefs)[index2] = tmp;
4935        }
4936    
4937        /** @brief Remove script slot.
4938         *
4939         * Removes the script slot with the given slot index.
4940         *
4941         * @param index - index of script slot to remove
4942         */
4943        void Instrument::RemoveScriptSlot(uint index) {
4944            LoadScripts();
4945            if (index >= pScriptRefs->size()) return;
4946            pScriptRefs->erase( pScriptRefs->begin() + index );
4947        }
4948    
4949        /** @brief Remove reference to given Script (gig format extension).
4950         *
4951         * This will remove all script slots on the instrument which are referencing
4952         * the given script.
4953         *
4954         * @note This is an own format extension which did not exist i.e. in the
4955         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4956         * gigedit.
4957         *
4958         * @param pScript - script reference to remove from this instrument
4959         * @see RemoveScriptSlot()
4960         */
4961        void Instrument::RemoveScript(Script* pScript) {
4962            LoadScripts();
4963            for (int i = pScriptRefs->size() - 1; i >= 0; --i) {
4964                if ((*pScriptRefs)[i].script == pScript) {
4965                    pScriptRefs->erase( pScriptRefs->begin() + i );
4966                }
4967            }
4968        }
4969    
4970        /** @brief Instrument's amount of script slots.
4971         *
4972         * This method returns the amount of script slots this instrument currently
4973         * uses.
4974         *
4975         * A script slot is a reference of a real-time instrument script to be
4976         * executed by the sampler. The scripts will be executed by the sampler in
4977         * sequence of the slots. One (same) script may be referenced multiple
4978         * times in different slots.
4979         *
4980         * @note This is an own format extension which did not exist i.e. in the
4981         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4982         * gigedit.
4983         */
4984        uint Instrument::ScriptSlotCount() const {
4985            return pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size();
4986        }
4987    
4988        /** @brief Whether script execution shall be skipped.
4989         *
4990         * Defines locally for the Script reference slot in the Instrument's Script
4991         * list, whether the script shall be skipped by the sampler regarding
4992         * execution.
4993         *
4994         * It is also possible to ignore exeuction of the script globally, for all
4995         * slots and for all instruments by setting Script::Bypass.
4996         *
4997         * @note This is an own format extension which did not exist i.e. in the
4998         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4999         * gigedit.
5000         *
5001         * @param index - index of the script slot on this instrument
5002         * @see Script::Bypass
5003         */
5004        bool Instrument::IsScriptSlotBypassed(uint index) {
5005            if (index >= ScriptSlotCount()) return false;
5006            return pScriptRefs ? pScriptRefs->at(index).bypass
5007                               : scriptPoolFileOffsets.at(index).bypass;
5008            
5009        }
5010    
5011        /** @brief Defines whether execution shall be skipped.
5012         *
5013         * You can call this method to define locally whether or whether not the
5014         * given script slot shall be executed by the sampler.
5015         *
5016         * @note This is an own format extension which did not exist i.e. in the
5017         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5018         * gigedit.
5019         *
5020         * @param index - script slot index on this instrument
5021         * @param bBypass - if true, the script slot will be skipped by the sampler
5022         * @see Script::Bypass
5023         */
5024        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5025            if (index >= ScriptSlotCount()) return;
5026            if (pScriptRefs)
5027                pScriptRefs->at(index).bypass = bBypass;
5028            else
5029                scriptPoolFileOffsets.at(index).bypass = bBypass;
5030        }
5031    
5032      /**      /**
5033       * 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
5034       * and assign it to this object.       * and assign it to this object.
# Line 4344  namespace { Line 5062  namespace {
5062          PitchbendRange = orig->PitchbendRange;          PitchbendRange = orig->PitchbendRange;
5063          PianoReleaseMode = orig->PianoReleaseMode;          PianoReleaseMode = orig->PianoReleaseMode;
5064          DimensionKeyRange = orig->DimensionKeyRange;          DimensionKeyRange = orig->DimensionKeyRange;
5065            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5066            pScriptRefs = orig->pScriptRefs;
5067                    
5068          // free old midi rules          // free old midi rules
5069          for (int i = 0 ; pMidiRules[i] ; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
# Line 4398  namespace { Line 5118  namespace {
5118       *       *
5119       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5120       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5121         *
5122         * @param pProgress - callback function for progress notification
5123       */       */
5124      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5125          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5126          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5127          if (!_3gri) {          if (!_3gri) {
# Line 4529  namespace { Line 5251  namespace {
5251          bAutoLoad = true;          bAutoLoad = true;
5252          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5253          pGroups = NULL;          pGroups = NULL;
5254            pScriptGroups = NULL;
5255          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5256          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5257    
# Line 4544  namespace { Line 5267  namespace {
5267      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5268          bAutoLoad = true;          bAutoLoad = true;
5269          pGroups = NULL;          pGroups = NULL;
5270            pScriptGroups = NULL;
5271          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5272      }      }
5273    
# Line 4557  namespace { Line 5281  namespace {
5281              }              }
5282              delete pGroups;              delete pGroups;
5283          }          }
5284            if (pScriptGroups) {
5285                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5286                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5287                while (iter != end) {
5288                    delete *iter;
5289                    ++iter;
5290                }
5291                delete pScriptGroups;
5292            }
5293      }      }
5294    
5295      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 4665  namespace { Line 5398  namespace {
5398          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5399    
5400          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5401            // (only for old gig files < 2 GB)
5402          int lastFileNo = 0;          int lastFileNo = 0;
5403          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5404              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5405                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5406                }
5407          }          }
5408          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5409          int nameLen = name.length();          int nameLen = name.length();
# Line 4677  namespace { Line 5413  namespace {
5413          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5414              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5415              if (wvpl) {              if (wvpl) {
5416                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5417                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5418                  while (wave) {                  while (wave) {
5419                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 4685  namespace { Line 5421  namespace {
5421                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5422                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5423    
5424                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5425                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));
5426    
5427                          iSampleIndex++;                          iSampleIndex++;
# Line 4924  namespace { Line 5660  namespace {
5660          if (!_3crc) return;          if (!_3crc) return;
5661    
5662          // get the index of the sample          // get the index of the sample
5663          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;  
             }  
         }  
5664          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");
5665    
5666          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5667          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5668          uint32_t tmp = 1;          uint32_t one = 1;
5669          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5670          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5671    
5672            // reload CRC table to RAM to keep it persistent over several subsequent save operations
5673            _3crc->ReleaseChunkData();
5674            _3crc->LoadChunkData();
5675        }
5676    
5677        uint32_t File::GetSampleChecksum(Sample* pSample) {
5678            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5679            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5680            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5681            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5682    
5683            // get the index of the sample
5684            int iWaveIndex = GetWaveTableIndexOf(pSample);
5685            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5686    
5687            // read the CRC-32 checksum directly from disk
5688            size_t pos = iWaveIndex * 8;
5689            if (pos + 8 > _3crc->GetNewSize())
5690                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5691    
5692            uint32_t one = load32(&pData[pos]); // always 1
5693            if (one != 1)
5694                throw gig::Exception("Could not verify sample, because reference checksum table is damaged");
5695    
5696            return load32(&pData[pos+4]);
5697        }
5698        
5699        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5700            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5701            File::SampleList::iterator iter = pSamples->begin();
5702            File::SampleList::iterator end  = pSamples->end();
5703            for (int index = 0; iter != end; ++iter, ++index)
5704                if (*iter == pSample)
5705                    return index;
5706            return -1;
5707        }
5708    
5709        /**
5710         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5711         * the CRC32 check sums of all samples' raw wave data.
5712         *
5713         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5714         */
5715        bool File::VerifySampleChecksumTable() {
5716            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5717            if (!_3crc) return false;
5718            if (_3crc->GetNewSize() <= 0) return false;
5719            if (_3crc->GetNewSize() % 8) return false;
5720            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5721            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5722    
5723            const int n = _3crc->GetNewSize() / 8;
5724    
5725            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5726            if (!pData) return false;
5727    
5728            for (int i = 0; i < n; ++i) {
5729                uint32_t one = pData[i*2];
5730                if (one != 1) return false;
5731            }
5732    
5733            return true;
5734        }
5735    
5736        /**
5737         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5738         * file's checksum table with those new checksums. This might usually
5739         * just be necessary if the checksum table was damaged.
5740         *
5741         * @e IMPORTANT: The current implementation of this method only works
5742         * with files that have not been modified since it was loaded, because
5743         * it expects that no externally caused file structure changes are
5744         * required!
5745         *
5746         * Due to the expectation above, this method is currently protected
5747         * and actually only used by the command line tool "gigdump" yet.
5748         *
5749         * @returns true if Save() is required to be called after this call,
5750         *          false if no further action is required
5751         */
5752        bool File::RebuildSampleChecksumTable() {
5753            // make sure sample chunks were scanned
5754            if (!pSamples) GetFirstSample();
5755    
5756            bool bRequiresSave = false;
5757    
5758            // make sure "3CRC" chunk exists with required size
5759            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5760            if (!_3crc) {
5761                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5762                bRequiresSave = true;
5763            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5764                _3crc->Resize(pSamples->size() * 8);
5765                bRequiresSave = true;
5766            }
5767    
5768            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5769                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5770                {
5771                    File::SampleList::iterator iter = pSamples->begin();
5772                    File::SampleList::iterator end  = pSamples->end();
5773                    for (; iter != end; ++iter) {
5774                        gig::Sample* pSample = (gig::Sample*) *iter;
5775                        int index = GetWaveTableIndexOf(pSample);
5776                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5777                        pData[index*2]   = 1; // always 1
5778                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5779                    }
5780                }
5781            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5782                // make sure file is in write mode
5783                pRIFF->SetMode(RIFF::stream_mode_read_write);
5784                {
5785                    File::SampleList::iterator iter = pSamples->begin();
5786                    File::SampleList::iterator end  = pSamples->end();
5787                    for (; iter != end; ++iter) {
5788                        gig::Sample* pSample = (gig::Sample*) *iter;
5789                        int index = GetWaveTableIndexOf(pSample);
5790                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5791                        uint32_t crc = pSample->CalculateWaveDataChecksum();
5792                        SetSampleChecksum(pSample, crc);
5793                    }
5794                }
5795            }
5796    
5797            return bRequiresSave;
5798      }      }
5799    
5800      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
# Line 5069  namespace { Line 5924  namespace {
5924          }          }
5925      }      }
5926    
5927        /** @brief Get instrument script group (by index).
5928         *
5929         * Returns the real-time instrument script group with the given index.
5930         *
5931         * @param index - number of the sought group (0..n)
5932         * @returns sought script group or NULL if there's no such group
5933         */
5934        ScriptGroup* File::GetScriptGroup(uint index) {
5935            if (!pScriptGroups) LoadScriptGroups();
5936            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5937            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5938                if (i == index) return *it;
5939            return NULL;
5940        }
5941    
5942        /** @brief Get instrument script group (by name).
5943         *
5944         * Returns the first real-time instrument script group found with the given
5945         * group name. Note that group names may not necessarily be unique.
5946         *
5947         * @param name - name of the sought script group
5948         * @returns sought script group or NULL if there's no such group
5949         */
5950        ScriptGroup* File::GetScriptGroup(const String& name) {
5951            if (!pScriptGroups) LoadScriptGroups();
5952            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
5953            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
5954                if ((*it)->Name == name) return *it;
5955            return NULL;
5956        }
5957    
5958        /** @brief Add new instrument script group.
5959         *
5960         * Adds a new, empty real-time instrument script group to the file.
5961         *
5962         * You have to call Save() to make this persistent to the file.
5963         *
5964         * @return new empty script group
5965         */
5966        ScriptGroup* File::AddScriptGroup() {
5967            if (!pScriptGroups) LoadScriptGroups();
5968            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
5969            pScriptGroups->push_back(pScriptGroup);
5970            return pScriptGroup;
5971        }
5972    
5973        /** @brief Delete an instrument script group.
5974         *
5975         * This will delete the given real-time instrument script group and all its
5976         * instrument scripts it contains. References inside instruments that are
5977         * using the deleted scripts will be removed from the respective instruments
5978         * accordingly.
5979         *
5980         * You have to call Save() to make this persistent to the file.
5981         *
5982         * @param pScriptGroup - script group to delete
5983         * @throws gig::Exception if given script group could not be found
5984         */
5985        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
5986            if (!pScriptGroups) LoadScriptGroups();
5987            std::list<ScriptGroup*>::iterator iter =
5988                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
5989            if (iter == pScriptGroups->end())
5990                throw gig::Exception("Could not delete script group, could not find given script group");
5991            pScriptGroups->erase(iter);
5992            for (int i = 0; pScriptGroup->GetScript(i); ++i)
5993                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
5994            if (pScriptGroup->pList)
5995                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
5996            delete pScriptGroup;
5997        }
5998    
5999        void File::LoadScriptGroups() {
6000            if (pScriptGroups) return;
6001            pScriptGroups = new std::list<ScriptGroup*>;
6002            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6003            if (lstLS) {
6004                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6005                     lst = lstLS->GetNextSubList())
6006                {
6007                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6008                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6009                    }
6010                }
6011            }
6012        }
6013    
6014      /**      /**
6015       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6016       * 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 5077  namespace { Line 6019  namespace {
6019       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6020       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6021       *       *
6022         * @param pProgress - callback function for progress notification
6023       * @throws Exception - on errors       * @throws Exception - on errors
6024       */       */
6025      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6026          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6027    
6028          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6029            // (not part of the GigaStudio 4 format)
6030            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6031            if (!lst3LS) {
6032                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6033            }
6034            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6035            // location of <3LS > is irrelevant, however it should be located
6036            // before  the actual wave data
6037            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6038            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6039    
6040            // This must be performed before writing the chunks for instruments,
6041            // because the instruments' script slots will write the file offsets
6042            // of the respective instrument script chunk as reference.
6043            if (pScriptGroups) {
6044                // Update instrument script (group) chunks.
6045                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6046                     it != pScriptGroups->end(); ++it)
6047                {
6048                    (*it)->UpdateChunks(pProgress);
6049                }
6050            }
6051    
6052            // in case no libgig custom format data was added, then remove the
6053            // custom "3LS " chunk again
6054            if (!lst3LS->CountSubChunks()) {
6055                pRIFF->DeleteSubChunk(lst3LS);
6056                lst3LS = NULL;
6057            }
6058    
6059            // if there is a 3CRC chunk, make sure it is loaded into RAM, otherwise
6060            // its data might get lost or damaged on file structure changes
6061            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6062            if (_3crc) _3crc->LoadChunkData();
6063    
6064          // first update base class's chunks          // first update base class's chunks
6065          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6066    
6067          if (newFile) {          if (newFile) {
6068              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 5122  namespace { Line 6099  namespace {
6099              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
6100              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
6101              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
6102                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
6103              }              }
6104          }          }
6105    
# Line 5243  namespace { Line 6220  namespace {
6220          // samples. The actual checksum values will be filled in          // samples. The actual checksum values will be filled in
6221          // later, by Sample::Write.          // later, by Sample::Write.
6222    
         RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);  
6223          if (_3crc) {          if (_3crc) {
6224              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6225          } else if (newFile) {          } else if (newFile) {
# Line 5254  namespace { Line 6230  namespace {
6230              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6231          }          }
6232      }      }
6233        
6234        void File::UpdateFileOffsets() {
6235            DLS::File::UpdateFileOffsets();
6236    
6237            for (Instrument* instrument = GetFirstInstrument(); instrument;
6238                 instrument = GetNextInstrument())
6239            {
6240                instrument->UpdateScriptFileOffsets();
6241            }
6242        }
6243    
6244      /**      /**
6245       * Enable / disable automatic loading. By default this properyt is       * Enable / disable automatic loading. By default this properyt is

Legend:
Removed from v.2557  
changed lines
  Added in v.2985

  ViewVC Help
Powered by ViewVC