/[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 3117 by schoenebeck, Sun Apr 16 23:20:30 2017 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-2017 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 297  namespace { Line 269  namespace {
269       * steps.       * steps.
270       *       *
271       * Once the whole data was processed by __calculateCRC(), one should       * Once the whole data was processed by __calculateCRC(), one should
272       * call __encodeCRC() to get the final CRC result.       * call __finalizeCRC() to get the final CRC result.
273       *       *
274       * @param buf     - pointer to data the CRC shall be calculated of       * @param buf     - pointer to data the CRC shall be calculated of
275       * @param bufSize - size of the data to be processed       * @param bufSize - size of the data to be processed
276       * @param crc     - variable the CRC sum shall be stored to       * @param crc     - variable the CRC sum shall be stored to
277       */       */
278      static void __calculateCRC(unsigned char* buf, int bufSize, uint32_t& crc) {      static void __calculateCRC(unsigned char* buf, size_t bufSize, uint32_t& crc) {
279          for (int i = 0 ; i < bufSize ; i++) {          for (size_t i = 0 ; i < bufSize ; i++) {
280              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);              crc = __CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8);
281          }          }
282      }      }
# Line 314  namespace { Line 286  namespace {
286       *       *
287       * @param crc - variable previously passed to __calculateCRC()       * @param crc - variable previously passed to __calculateCRC()
288       */       */
289      inline static uint32_t __encodeCRC(const uint32_t& crc) {      inline static void __finalizeCRC(uint32_t& crc) {
290          return crc ^ 0xffffffff;          crc ^= 0xffffffff;
291      }      }
292    
293    
# 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 366  namespace { Line 338  namespace {
338       *                         ('wvpl') list chunk       *                         ('wvpl') list chunk
339       * @param fileNo         - number of an extension file where this sample       * @param fileNo         - number of an extension file where this sample
340       *                         is located, 0 otherwise       *                         is located, 0 otherwise
341         * @param index          - wave pool index of sample (may be -1 on new sample)
342       */       */
343      Sample::Sample(File* pFile, RIFF::List* waveList, unsigned long WavePoolOffset, unsigned long fileNo) : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset) {      Sample::Sample(File* pFile, RIFF::List* waveList, file_offset_t WavePoolOffset, unsigned long fileNo, int index)
344            : DLS::Sample((DLS::File*) pFile, waveList, WavePoolOffset)
345        {
346          static const DLS::Info::string_length_t fixedStringLengths[] = {          static const DLS::Info::string_length_t fixedStringLengths[] = {
347              { CHUNK_ID_INAM, 64 },              { CHUNK_ID_INAM, 64 },
348              { 0, 0 }              { 0, 0 }
# Line 377  namespace { Line 352  namespace {
352          FileNo = fileNo;          FileNo = fileNo;
353    
354          __resetCRC(crc);          __resetCRC(crc);
355            // if this is not a new sample, try to get the sample's already existing
356            // CRC32 checksum from disk, this checksum will reflect the sample's CRC32
357            // checksum of the time when the sample was consciously modified by the
358            // user for the last time (by calling Sample::Write() that is).
359            if (index >= 0) { // not a new file ...
360                try {
361                    uint32_t crc = pFile->GetSampleChecksumByIndex(index);
362                    this->crc = crc;
363                } catch (...) {}
364            }
365    
366          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);          pCk3gix = waveList->GetSubChunk(CHUNK_ID_3GIX);
367          if (pCk3gix) {          if (pCk3gix) {
# Line 509  namespace { Line 494  namespace {
494          const int iReadAtOnce = 32*1024;          const int iReadAtOnce = 32*1024;
495          char* buf = new char[iReadAtOnce * orig->FrameSize];          char* buf = new char[iReadAtOnce * orig->FrameSize];
496          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now          Sample* pOrig = (Sample*) orig; //HACK: remove constness for now
497          unsigned long restorePos = pOrig->GetPos();          file_offset_t restorePos = pOrig->GetPos();
498          pOrig->SetPos(0);          pOrig->SetPos(0);
499          SetPos(0);          SetPos(0);
500          for (unsigned long n = pOrig->Read(buf, iReadAtOnce); n;          for (file_offset_t n = pOrig->Read(buf, iReadAtOnce); n;
501                             n = pOrig->Read(buf, iReadAtOnce))                             n = pOrig->Read(buf, iReadAtOnce))
502          {          {
503              Write(buf, n);              Write(buf, n);
# Line 528  namespace { Line 513  namespace {
513       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
514       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
515       *       *
516         * @param pProgress - callback function for progress notification
517       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data       * @throws DLS::Exception if FormatTag != DLS_WAVE_FORMAT_PCM or no sample data
518       *                        was provided yet       *                        was provided yet
519       * @throws gig::Exception if there is any invalid sample setting       * @throws gig::Exception if there is any invalid sample setting
520       */       */
521      void Sample::UpdateChunks() {      void Sample::UpdateChunks(progress_t* pProgress) {
522          // first update base class's chunks          // first update base class's chunks
523          DLS::Sample::UpdateChunks();          DLS::Sample::UpdateChunks(pProgress);
524    
525          // make sure 'smpl' chunk exists          // make sure 'smpl' chunk exists
526          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);          pCkSmpl = pWaveList->GetSubChunk(CHUNK_ID_SMPL);
# Line 596  namespace { Line 582  namespace {
582      void Sample::ScanCompressedSample() {      void Sample::ScanCompressedSample() {
583          //TODO: we have to add some more scans here (e.g. determine compression rate)          //TODO: we have to add some more scans here (e.g. determine compression rate)
584          this->SamplesTotal = 0;          this->SamplesTotal = 0;
585          std::list<unsigned long> frameOffsets;          std::list<file_offset_t> frameOffsets;
586    
587          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;          SamplesPerFrame = BitDepth == 24 ? 256 : 2048;
588          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag          WorstCaseFrameSize = SamplesPerFrame * FrameSize + Channels; // +Channels for compression flag
# Line 612  namespace { Line 598  namespace {
598                  const int mode_l = pCkData->ReadUint8();                  const int mode_l = pCkData->ReadUint8();
599                  const int mode_r = pCkData->ReadUint8();                  const int mode_r = pCkData->ReadUint8();
600                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");                  if (mode_l > 5 || mode_r > 5) throw gig::Exception("Unknown compression mode");
601                  const unsigned long frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];                  const file_offset_t frameSize = bytesPerFrame[mode_l] + bytesPerFrame[mode_r];
602    
603                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
604                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 631  namespace { Line 617  namespace {
617    
618                  const int mode = pCkData->ReadUint8();                  const int mode = pCkData->ReadUint8();
619                  if (mode > 5) throw gig::Exception("Unknown compression mode");                  if (mode > 5) throw gig::Exception("Unknown compression mode");
620                  const unsigned long frameSize = bytesPerFrame[mode];                  const file_offset_t frameSize = bytesPerFrame[mode];
621    
622                  if (pCkData->RemainingBytes() <= frameSize) {                  if (pCkData->RemainingBytes() <= frameSize) {
623                      SamplesInLastFrame =                      SamplesInLastFrame =
# Line 647  namespace { Line 633  namespace {
633    
634          // Build the frames table (which is used for fast resolving of a frame's chunk offset)          // Build the frames table (which is used for fast resolving of a frame's chunk offset)
635          if (FrameTable) delete[] FrameTable;          if (FrameTable) delete[] FrameTable;
636          FrameTable = new unsigned long[frameOffsets.size()];          FrameTable = new file_offset_t[frameOffsets.size()];
637          std::list<unsigned long>::iterator end  = frameOffsets.end();          std::list<file_offset_t>::iterator end  = frameOffsets.end();
638          std::list<unsigned long>::iterator iter = frameOffsets.begin();          std::list<file_offset_t>::iterator iter = frameOffsets.begin();
639          for (int i = 0; iter != end; i++, iter++) {          for (int i = 0; iter != end; i++, iter++) {
640              FrameTable[i] = *iter;              FrameTable[i] = *iter;
641          }          }
# Line 690  namespace { Line 676  namespace {
676       *                      the cached sample data in bytes       *                      the cached sample data in bytes
677       * @see                 ReleaseSampleData(), Read(), SetPos()       * @see                 ReleaseSampleData(), Read(), SetPos()
678       */       */
679      buffer_t Sample::LoadSampleData(unsigned long SampleCount) {      buffer_t Sample::LoadSampleData(file_offset_t SampleCount) {
680          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples          return LoadSampleDataWithNullSamplesExtension(SampleCount, 0); // 0 amount of NullSamples
681      }      }
682    
# Line 749  namespace { Line 735  namespace {
735       *                           size of the cached sample data in bytes       *                           size of the cached sample data in bytes
736       * @see                      ReleaseSampleData(), Read(), SetPos()       * @see                      ReleaseSampleData(), Read(), SetPos()
737       */       */
738      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(unsigned long SampleCount, uint NullSamplesCount) {      buffer_t Sample::LoadSampleDataWithNullSamplesExtension(file_offset_t SampleCount, uint NullSamplesCount) {
739          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;          if (SampleCount > this->SamplesTotal) SampleCount = this->SamplesTotal;
740          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;          if (RAMCache.pStart) delete[] (int8_t*) RAMCache.pStart;
741          unsigned long allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;          file_offset_t allocationsize = (SampleCount + NullSamplesCount) * this->FrameSize;
742          SetPos(0); // reset read position to begin of sample          SetPos(0); // reset read position to begin of sample
743          RAMCache.pStart            = new int8_t[allocationsize];          RAMCache.pStart            = new int8_t[allocationsize];
744          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;          RAMCache.Size              = Read(RAMCache.pStart, SampleCount) * this->FrameSize;
# Line 816  namespace { Line 802  namespace {
802       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with       * FormatTag must be DLS_WAVE_FORMAT_PCM. Trying to resize samples with
803       * other formats will fail!       * other formats will fail!
804       *       *
805       * @param iNewSize - new sample wave data size in sample points (must be       * @param NewSize - new sample wave data size in sample points (must be
806       *                   greater than zero)       *                  greater than zero)
807       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM       * @throws DLS::Excecption if FormatTag != DLS_WAVE_FORMAT_PCM
808       *                         or if \a iNewSize is less than 1       * @throws DLS::Exception if \a NewSize is less than 1 or unrealistic large
809       * @throws gig::Exception if existing sample is compressed       * @throws gig::Exception if existing sample is compressed
810       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,       * @see DLS::Sample::GetSize(), DLS::Sample::FrameSize,
811       *      DLS::Sample::FormatTag, File::Save()       *      DLS::Sample::FormatTag, File::Save()
812       */       */
813      void Sample::Resize(int iNewSize) {      void Sample::Resize(file_offset_t NewSize) {
814          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");          if (Compressed) throw gig::Exception("There is no support for modifying compressed samples (yet)");
815          DLS::Sample::Resize(iNewSize);          DLS::Sample::Resize(NewSize);
816      }      }
817    
818      /**      /**
# Line 850  namespace { Line 836  namespace {
836       * @returns            the new sample position       * @returns            the new sample position
837       * @see                Read()       * @see                Read()
838       */       */
839      unsigned long Sample::SetPos(unsigned long SampleCount, RIFF::stream_whence_t Whence) {      file_offset_t Sample::SetPos(file_offset_t SampleCount, RIFF::stream_whence_t Whence) {
840          if (Compressed) {          if (Compressed) {
841              switch (Whence) {              switch (Whence) {
842                  case RIFF::stream_curpos:                  case RIFF::stream_curpos:
# Line 868  namespace { Line 854  namespace {
854              }              }
855              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;              if (this->SamplePos > this->SamplesTotal) this->SamplePos = this->SamplesTotal;
856    
857              unsigned long frame = this->SamplePos / 2048; // to which frame to jump              file_offset_t frame = this->SamplePos / 2048; // to which frame to jump
858              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame              this->FrameOffset   = this->SamplePos % 2048; // offset (in sample points) within that frame
859              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame              pCkData->SetPos(FrameTable[frame]);           // set chunk pointer to the start of sought frame
860              return this->SamplePos;              return this->SamplePos;
861          }          }
862          else { // not compressed          else { // not compressed
863              unsigned long orderedBytes = SampleCount * this->FrameSize;              file_offset_t orderedBytes = SampleCount * this->FrameSize;
864              unsigned long result = pCkData->SetPos(orderedBytes, Whence);              file_offset_t result = pCkData->SetPos(orderedBytes, Whence);
865              return (result == orderedBytes) ? SampleCount              return (result == orderedBytes) ? SampleCount
866                                              : result / this->FrameSize;                                              : result / this->FrameSize;
867          }          }
# Line 884  namespace { Line 870  namespace {
870      /**      /**
871       * Returns the current position in the sample (in sample points).       * Returns the current position in the sample (in sample points).
872       */       */
873      unsigned long Sample::GetPos() const {      file_offset_t Sample::GetPos() const {
874          if (Compressed) return SamplePos;          if (Compressed) return SamplePos;
875          else            return pCkData->GetPos() / FrameSize;          else            return pCkData->GetPos() / FrameSize;
876      }      }
# Line 923  namespace { Line 909  namespace {
909       * @returns                number of successfully read sample points       * @returns                number of successfully read sample points
910       * @see                    CreateDecompressionBuffer()       * @see                    CreateDecompressionBuffer()
911       */       */
912      unsigned long Sample::ReadAndLoop(void* pBuffer, unsigned long SampleCount, playback_state_t* pPlaybackState,      file_offset_t Sample::ReadAndLoop(void* pBuffer, file_offset_t SampleCount, playback_state_t* pPlaybackState,
913                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {                                        DimensionRegion* pDimRgn, buffer_t* pExternalDecompressionBuffer) {
914          unsigned long samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;          file_offset_t samplestoread = SampleCount, totalreadsamples = 0, readsamples, samplestoloopend;
915          uint8_t* pDst = (uint8_t*) pBuffer;          uint8_t* pDst = (uint8_t*) pBuffer;
916    
917          SetPos(pPlaybackState->position); // recover position from the last time          SetPos(pPlaybackState->position); // recover position from the last time
# Line 963  namespace { Line 949  namespace {
949                                  // reading, swap all sample frames so it reflects                                  // reading, swap all sample frames so it reflects
950                                  // backward playback                                  // backward playback
951    
952                                  unsigned long swapareastart       = totalreadsamples;                                  file_offset_t swapareastart       = totalreadsamples;
953                                  unsigned long loopoffset          = GetPos() - loop.LoopStart;                                  file_offset_t loopoffset          = GetPos() - loop.LoopStart;
954                                  unsigned long samplestoreadinloop = Min(samplestoread, loopoffset);                                  file_offset_t samplestoreadinloop = Min(samplestoread, loopoffset);
955                                  unsigned long reverseplaybackend  = GetPos() - samplestoreadinloop;                                  file_offset_t reverseplaybackend  = GetPos() - samplestoreadinloop;
956    
957                                  SetPos(reverseplaybackend);                                  SetPos(reverseplaybackend);
958    
# Line 1014  namespace { Line 1000  namespace {
1000                          // reading, swap all sample frames so it reflects                          // reading, swap all sample frames so it reflects
1001                          // backward playback                          // backward playback
1002    
1003                          unsigned long swapareastart       = totalreadsamples;                          file_offset_t swapareastart       = totalreadsamples;
1004                          unsigned long loopoffset          = GetPos() - loop.LoopStart;                          file_offset_t loopoffset          = GetPos() - loop.LoopStart;
1005                          unsigned long samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)                          file_offset_t samplestoreadinloop = (this->LoopPlayCount) ? Min(samplestoread, pPlaybackState->loop_cycles_left * loop.LoopLength - loopoffset)
1006                                                                                    : samplestoread;                                                                                    : samplestoread;
1007                          unsigned long reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);                          file_offset_t reverseplaybackend  = loop.LoopStart + Abs((loopoffset - samplestoreadinloop) % loop.LoopLength);
1008    
1009                          SetPos(reverseplaybackend);                          SetPos(reverseplaybackend);
1010    
# Line 1098  namespace { Line 1084  namespace {
1084       * @returns            number of successfully read sample points       * @returns            number of successfully read sample points
1085       * @see                SetPos(), CreateDecompressionBuffer()       * @see                SetPos(), CreateDecompressionBuffer()
1086       */       */
1087      unsigned long Sample::Read(void* pBuffer, unsigned long SampleCount, buffer_t* pExternalDecompressionBuffer) {      file_offset_t Sample::Read(void* pBuffer, file_offset_t SampleCount, buffer_t* pExternalDecompressionBuffer) {
1088          if (SampleCount == 0) return 0;          if (SampleCount == 0) return 0;
1089          if (!Compressed) {          if (!Compressed) {
1090              if (BitDepth == 24) {              if (BitDepth == 24) {
# Line 1113  namespace { Line 1099  namespace {
1099          else {          else {
1100              if (this->SamplePos >= this->SamplesTotal) return 0;              if (this->SamplePos >= this->SamplesTotal) return 0;
1101              //TODO: efficiency: maybe we should test for an average compression rate              //TODO: efficiency: maybe we should test for an average compression rate
1102              unsigned long assumedsize      = GuessSize(SampleCount),              file_offset_t assumedsize      = GuessSize(SampleCount),
1103                            remainingbytes   = 0,           // remaining bytes in the local buffer                            remainingbytes   = 0,           // remaining bytes in the local buffer
1104                            remainingsamples = SampleCount,                            remainingsamples = SampleCount,
1105                            copysamples, skipsamples,                            copysamples, skipsamples,
# Line 1136  namespace { Line 1122  namespace {
1122              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);              remainingbytes = pCkData->Read(pSrc, assumedsize, 1);
1123    
1124              while (remainingsamples && remainingbytes) {              while (remainingsamples && remainingbytes) {
1125                  unsigned long framesamples = SamplesPerFrame;                  file_offset_t framesamples = SamplesPerFrame;
1126                  unsigned long framebytes, rightChannelOffset = 0, nextFrameOffset;                  file_offset_t framebytes, rightChannelOffset = 0, nextFrameOffset;
1127    
1128                  int mode_l = *pSrc++, mode_r = 0;                  int mode_l = *pSrc++, mode_r = 0;
1129    
# Line 1287  namespace { Line 1273  namespace {
1273       * @throws gig::Exception if sample is compressed       * @throws gig::Exception if sample is compressed
1274       * @see DLS::LoadSampleData()       * @see DLS::LoadSampleData()
1275       */       */
1276      unsigned long Sample::Write(void* pBuffer, unsigned long SampleCount) {      file_offset_t Sample::Write(void* pBuffer, file_offset_t SampleCount) {
1277          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");          if (Compressed) throw gig::Exception("There is no support for writing compressed gig samples (yet)");
1278    
1279          // if this is the first write in this sample, reset the          // if this is the first write in this sample, reset the
# Line 1296  namespace { Line 1282  namespace {
1282              __resetCRC(crc);              __resetCRC(crc);
1283          }          }
1284          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");          if (GetSize() < SampleCount) throw Exception("Could not write sample data, current sample size to small");
1285          unsigned long res;          file_offset_t res;
1286          if (BitDepth == 24) {          if (BitDepth == 24) {
1287              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;              res = pCkData->Write(pBuffer, SampleCount * FrameSize, 1) / FrameSize;
1288          } else { // 16 bit          } else { // 16 bit
# Line 1308  namespace { Line 1294  namespace {
1294          // if this is the last write, update the checksum chunk in the          // if this is the last write, update the checksum chunk in the
1295          // file          // file
1296          if (pCkData->GetPos() == pCkData->GetSize()) {          if (pCkData->GetPos() == pCkData->GetSize()) {
1297                __finalizeCRC(crc);
1298              File* pFile = static_cast<File*>(GetParent());              File* pFile = static_cast<File*>(GetParent());
1299              pFile->SetSampleChecksum(this, __encodeCRC(crc));              pFile->SetSampleChecksum(this, crc);
1300          }          }
1301          return res;          return res;
1302      }      }
# Line 1330  namespace { Line 1317  namespace {
1317       * @returns allocated decompression buffer       * @returns allocated decompression buffer
1318       * @see DestroyDecompressionBuffer()       * @see DestroyDecompressionBuffer()
1319       */       */
1320      buffer_t Sample::CreateDecompressionBuffer(unsigned long MaxReadSize) {      buffer_t Sample::CreateDecompressionBuffer(file_offset_t MaxReadSize) {
1321          buffer_t result;          buffer_t result;
1322          const double worstCaseHeaderOverhead =          const double worstCaseHeaderOverhead =
1323                  (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;
1324          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);
1325          result.pStart            = new int8_t[result.Size];          result.pStart            = new int8_t[result.Size];
1326          result.NullExtensionSize = 0;          result.NullExtensionSize = 0;
1327          return result;          return result;
# Line 1368  namespace { Line 1355  namespace {
1355          return pGroup;          return pGroup;
1356      }      }
1357    
1358        /**
1359         * Returns the CRC-32 checksum of the sample's raw wave form data at the
1360         * time when this sample's wave form data was modified for the last time
1361         * by calling Write(). This checksum only covers the raw wave form data,
1362         * not any meta informations like i.e. bit depth or loop points. Since
1363         * this method just returns the checksum stored for this sample i.e. when
1364         * the gig file was loaded, this method returns immediately. So it does no
1365         * recalcuation of the checksum with the currently available sample wave
1366         * form data.
1367         *
1368         * @see VerifyWaveData()
1369         */
1370        uint32_t Sample::GetWaveDataCRC32Checksum() {
1371            return crc;
1372        }
1373    
1374        /**
1375         * Checks the integrity of this sample's raw audio wave data. Whenever a
1376         * Sample's raw wave data is intentionally modified (i.e. by calling
1377         * Write() and supplying the new raw audio wave form data) a CRC32 checksum
1378         * is calculated and stored/updated for this sample, along to the sample's
1379         * meta informations.
1380         *
1381         * Now by calling this method the current raw audio wave data is checked
1382         * against the already stored CRC32 check sum in order to check whether the
1383         * sample data had been damaged unintentionally for some reason. Since by
1384         * calling this method always the entire raw audio wave data has to be
1385         * read, verifying all samples this way may take a long time accordingly.
1386         * And that's also the reason why the sample integrity is not checked by
1387         * default whenever a gig file is loaded. So this method must be called
1388         * explicitly to fulfill this task.
1389         *
1390         * @param pActually - (optional) if provided, will be set to the actually
1391         *                    calculated checksum of the current raw wave form data,
1392         *                    you can get the expected checksum instead by calling
1393         *                    GetWaveDataCRC32Checksum()
1394         * @returns true if sample is OK or false if the sample is damaged
1395         * @throws Exception if no checksum had been stored to disk for this
1396         *         sample yet, or on I/O issues
1397         * @see GetWaveDataCRC32Checksum()
1398         */
1399        bool Sample::VerifyWaveData(uint32_t* pActually) {
1400            //File* pFile = static_cast<File*>(GetParent());
1401            uint32_t crc = CalculateWaveDataChecksum();
1402            if (pActually) *pActually = crc;
1403            return crc == this->crc;
1404        }
1405    
1406        uint32_t Sample::CalculateWaveDataChecksum() {
1407            const size_t sz = 20*1024; // 20kB buffer size
1408            std::vector<uint8_t> buffer(sz);
1409            buffer.resize(sz);
1410    
1411            const size_t n = sz / FrameSize;
1412            SetPos(0);
1413            uint32_t crc = 0;
1414            __resetCRC(crc);
1415            while (true) {
1416                file_offset_t nRead = Read(&buffer[0], n);
1417                if (nRead <= 0) break;
1418                __calculateCRC(&buffer[0], nRead * FrameSize, crc);
1419            }
1420            __finalizeCRC(crc);
1421            return crc;
1422        }
1423    
1424      Sample::~Sample() {      Sample::~Sample() {
1425          Instances--;          Instances--;
1426          if (!Instances && InternalDecompressionBuffer.Size) {          if (!Instances && InternalDecompressionBuffer.Size) {
# Line 1384  namespace { Line 1437  namespace {
1437  // *************** DimensionRegion ***************  // *************** DimensionRegion ***************
1438  // *  // *
1439    
1440      uint                               DimensionRegion::Instances       = 0;      size_t                             DimensionRegion::Instances       = 0;
1441      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;      DimensionRegion::VelocityTableMap* DimensionRegion::pVelocityTables = NULL;
1442    
1443      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {      DimensionRegion::DimensionRegion(Region* pParent, RIFF::List* _3ewl) : DLS::Sampler(_3ewl) {
# Line 1578  namespace { Line 1631  namespace {
1631              EG2Attack                       = 0.0;              EG2Attack                       = 0.0;
1632              EG2Decay1                       = 0.005;              EG2Decay1                       = 0.005;
1633              EG2Sustain                      = 1000;              EG2Sustain                      = 1000;
1634              EG2Release                      = 0.3;              EG2Release                      = 60;
1635              LFO2ControlDepth                = 0;              LFO2ControlDepth                = 0;
1636              LFO2Frequency                   = 1.0;              LFO2Frequency                   = 1.0;
1637              LFO2InternalDepth               = 0;              LFO2InternalDepth               = 0;
# Line 1752  namespace { Line 1805  namespace {
1805       *       *
1806       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
1807       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
1808         *
1809         * @param pProgress - callback function for progress notification
1810       */       */
1811      void DimensionRegion::UpdateChunks() {      void DimensionRegion::UpdateChunks(progress_t* pProgress) {
1812          // first update base class's chunk          // first update base class's chunk
1813          DLS::Sampler::UpdateChunks();          DLS::Sampler::UpdateChunks(pProgress);
1814    
1815          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);          RIFF::Chunk* wsmp = pParentList->GetSubChunk(CHUNK_ID_WSMP);
1816          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();          uint8_t* pData = (uint8_t*) wsmp->LoadChunkData();
# Line 1775  namespace { Line 1830  namespace {
1830    
1831          // update '3ewa' chunk with DimensionRegion's current settings          // update '3ewa' chunk with DimensionRegion's current settings
1832    
1833          const uint32_t chunksize = _3ewa->GetNewSize();          const uint32_t chunksize = (uint32_t) _3ewa->GetNewSize();
1834          store32(&pData[0], chunksize); // unknown, always chunk size?          store32(&pData[0], chunksize); // unknown, always chunk size?
1835    
1836          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);          const int32_t lfo3freq = (int32_t) GIG_EXP_ENCODE(LFO3Frequency);
# Line 3026  namespace { Line 3081  namespace {
3081       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
3082       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
3083       *       *
3084         * @param pProgress - callback function for progress notification
3085       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
3086       */       */
3087      void Region::UpdateChunks() {      void Region::UpdateChunks(progress_t* pProgress) {
3088          // 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
3089          // 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
3090          // 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 3092  namespace {
3092          pSample = pDimensionRegions[0]->pSample;          pSample = pDimensionRegions[0]->pSample;
3093    
3094          // first update base class's chunks          // first update base class's chunks
3095          DLS::Region::UpdateChunks();          DLS::Region::UpdateChunks(pProgress);
3096    
3097          // update dimension region's chunks          // update dimension region's chunks
3098          for (int i = 0; i < DimensionRegions; i++) {          for (int i = 0; i < DimensionRegions; i++) {
3099              pDimensionRegions[i]->UpdateChunks();              pDimensionRegions[i]->UpdateChunks(pProgress);
3100          }          }
3101    
3102          File* pFile = (File*) GetParent()->GetParent();          File* pFile = (File*) GetParent()->GetParent();
# Line 3056  namespace { Line 3112  namespace {
3112              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);              memset(_3lnk->LoadChunkData(), 0, _3lnkChunkSize);
3113    
3114              // move 3prg to last position              // move 3prg to last position
3115              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), 0);              pCkRegion->MoveSubChunk(pCkRegion->GetSubList(LIST_TYPE_3PRG), (RIFF::Chunk*)NULL);
3116          }          }
3117    
3118          // update dimension definitions in '3lnk' chunk          // update dimension definitions in '3lnk' chunk
# Line 3130  namespace { Line 3186  namespace {
3186          int step = 1;          int step = 1;
3187          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;          for (int i = 0 ; i < veldim ; i++) step <<= pDimensionDefinitions[i].bits;
3188          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;          int skipveldim = (step << pDimensionDefinitions[veldim].bits) - step;
         int end = step * pDimensionDefinitions[veldim].zones;  
3189    
3190          // loop through all dimension regions for all dimensions except the velocity dimension          // loop through all dimension regions for all dimensions except the velocity dimension
3191          int dim[8] = { 0 };          int dim[8] = { 0 };
3192          for (int i = 0 ; i < DimensionRegions ; i++) {          for (int i = 0 ; i < DimensionRegions ; i++) {
3193                const int end = i + step * pDimensionDefinitions[veldim].zones;
3194    
3195                // create a velocity table for all cases where the velocity zone is zero
3196              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||              if (pDimensionRegions[i]->DimensionUpperLimits[veldim] ||
3197                  pDimensionRegions[i]->VelocityUpperLimit) {                  pDimensionRegions[i]->VelocityUpperLimit) {
3198                  // create the velocity table                  // create the velocity table
# Line 3166  namespace { Line 3223  namespace {
3223                  }                  }
3224              }              }
3225    
3226                // jump to the next case where the velocity zone is zero
3227              int j;              int j;
3228              int shift = 0;              int shift = 0;
3229              for (j = 0 ; j < Dimensions ; j++) {              for (j = 0 ; j < Dimensions ; j++) {
# Line 3652  namespace { Line 3710  namespace {
3710          UpdateVelocityTable();          UpdateVelocityTable();
3711      }      }
3712    
3713        /** @brief Change type of an existing dimension.
3714         *
3715         * Alters the dimension type of a dimension already existing on this
3716         * region. If there is currently no dimension on this Region with type
3717         * @a oldType, then this call with throw an Exception. Likewise there are
3718         * cases where the requested dimension type cannot be performed. For example
3719         * if the new dimension type shall be gig::dimension_samplechannel, and the
3720         * current dimension has more than 2 zones. In such cases an Exception is
3721         * thrown as well.
3722         *
3723         * @param oldType - identifies the existing dimension to be changed
3724         * @param newType - to which dimension type it should be changed to
3725         * @throws gig::Exception if requested change cannot be performed
3726         */
3727        void Region::SetDimensionType(dimension_t oldType, dimension_t newType) {
3728            if (oldType == newType) return;
3729            dimension_def_t* def = GetDimensionDefinition(oldType);
3730            if (!def)
3731                throw gig::Exception("No dimension with provided old dimension type exists on this region");
3732            if (newType == dimension_samplechannel && def->zones != 2)
3733                throw gig::Exception("Cannot change to dimension type 'sample channel', because existing dimension does not have 2 zones");
3734            if (GetDimensionDefinition(newType))
3735                throw gig::Exception("There is already a dimension with requested new dimension type on this region");
3736            def->dimension  = newType;
3737            def->split_type = __resolveSplitType(newType);
3738        }
3739    
3740      DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {      DimensionRegion* Region::GetDimensionRegionByBit(const std::map<dimension_t,int>& DimCase) {
3741          uint8_t bits[8] = {};          uint8_t bits[8] = {};
3742          for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();          for (std::map<dimension_t,int>::const_iterator it = DimCase.begin();
# Line 3713  namespace { Line 3798  namespace {
3798      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {      DimensionRegion* Region::GetDimensionRegionByValue(const uint DimValues[8]) {
3799          uint8_t bits;          uint8_t bits;
3800          int veldim = -1;          int veldim = -1;
3801          int velbitpos;          int velbitpos = 0;
3802          int bitpos = 0;          int bitpos = 0;
3803          int dimregidx = 0;          int dimregidx = 0;
3804          for (uint i = 0; i < Dimensions; i++) {          for (uint i = 0; i < Dimensions; i++) {
# Line 3743  namespace { Line 3828  namespace {
3828              }              }
3829              bitpos += pDimensionDefinitions[i].bits;              bitpos += pDimensionDefinitions[i].bits;
3830          }          }
3831          DimensionRegion* dimreg = pDimensionRegions[dimregidx];          DimensionRegion* dimreg = pDimensionRegions[dimregidx & 255];
3832            if (!dimreg) return NULL;
3833          if (veldim != -1) {          if (veldim != -1) {
3834              // (dimreg is now the dimension region for the lowest velocity)              // (dimreg is now the dimension region for the lowest velocity)
3835              if (dimreg->VelocityTable) // custom defined zone ranges              if (dimreg->VelocityTable) // custom defined zone ranges
3836                  bits = dimreg->VelocityTable[DimValues[veldim]];                  bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3837              else // normal split type              else // normal split type
3838                  bits = uint8_t(DimValues[veldim] / pDimensionDefinitions[veldim].zone_size);                  bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3839    
3840              dimregidx |= bits << velbitpos;              const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3841              dimreg = pDimensionRegions[dimregidx];              dimregidx |= (bits & limiter_mask) << velbitpos;
3842                dimreg = pDimensionRegions[dimregidx & 255];
3843          }          }
3844          return dimreg;          return dimreg;
3845      }      }
3846    
3847        int Region::GetDimensionRegionIndexByValue(const uint DimValues[8]) {
3848            uint8_t bits;
3849            int veldim = -1;
3850            int velbitpos = 0;
3851            int bitpos = 0;
3852            int dimregidx = 0;
3853            for (uint i = 0; i < Dimensions; i++) {
3854                if (pDimensionDefinitions[i].dimension == dimension_velocity) {
3855                    // the velocity dimension must be handled after the other dimensions
3856                    veldim = i;
3857                    velbitpos = bitpos;
3858                } else {
3859                    switch (pDimensionDefinitions[i].split_type) {
3860                        case split_type_normal:
3861                            if (pDimensionRegions[0]->DimensionUpperLimits[i]) {
3862                                // gig3: all normal dimensions (not just the velocity dimension) have custom zone ranges
3863                                for (bits = 0 ; bits < pDimensionDefinitions[i].zones ; bits++) {
3864                                    if (DimValues[i] <= pDimensionRegions[bits << bitpos]->DimensionUpperLimits[i]) break;
3865                                }
3866                            } else {
3867                                // gig2: evenly sized zones
3868                                bits = uint8_t(DimValues[i] / pDimensionDefinitions[i].zone_size);
3869                            }
3870                            break;
3871                        case split_type_bit: // the value is already the sought dimension bit number
3872                            const uint8_t limiter_mask = (0xff << pDimensionDefinitions[i].bits) ^ 0xff;
3873                            bits = DimValues[i] & limiter_mask; // just make sure the value doesn't use more bits than allowed
3874                            break;
3875                    }
3876                    dimregidx |= bits << bitpos;
3877                }
3878                bitpos += pDimensionDefinitions[i].bits;
3879            }
3880            dimregidx &= 255;
3881            DimensionRegion* dimreg = pDimensionRegions[dimregidx];
3882            if (!dimreg) return -1;
3883            if (veldim != -1) {
3884                // (dimreg is now the dimension region for the lowest velocity)
3885                if (dimreg->VelocityTable) // custom defined zone ranges
3886                    bits = dimreg->VelocityTable[DimValues[veldim] & 127];
3887                else // normal split type
3888                    bits = uint8_t((DimValues[veldim] & 127) / pDimensionDefinitions[veldim].zone_size);
3889    
3890                const uint8_t limiter_mask = (1 << pDimensionDefinitions[veldim].bits) - 1;
3891                dimregidx |= (bits & limiter_mask) << velbitpos;
3892                dimregidx &= 255;
3893            }
3894            return dimregidx;
3895        }
3896    
3897      /**      /**
3898       * Returns the appropriate DimensionRegion for the given dimension bit       * Returns the appropriate DimensionRegion for the given dimension bit
3899       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>       * numbers (zone index). You usually use <i>GetDimensionRegionByValue</i>
# Line 3795  namespace { Line 3932  namespace {
3932          if ((int32_t)WavePoolTableIndex == -1) return NULL;          if ((int32_t)WavePoolTableIndex == -1) return NULL;
3933          File* file = (File*) GetParent()->GetParent();          File* file = (File*) GetParent()->GetParent();
3934          if (!file->pWavePoolTable) return NULL;          if (!file->pWavePoolTable) return NULL;
3935          unsigned long soughtoffset = file->pWavePoolTable[WavePoolTableIndex];          // for new files or files >= 2 GB use 64 bit wave pool offsets
3936          unsigned long soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];          if (file->pRIFF->IsNew() || (file->pRIFF->GetCurrentFileSize() >> 31)) {
3937          Sample* sample = file->GetFirstSample(pProgress);              // use 64 bit wave pool offsets (treating this as large file)
3938          while (sample) {              uint64_t soughtoffset =
3939              if (sample->ulWavePoolOffset == soughtoffset &&                  uint64_t(file->pWavePoolTable[WavePoolTableIndex]) |
3940                  sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);                  uint64_t(file->pWavePoolTableHi[WavePoolTableIndex]) << 32;
3941              sample = file->GetNextSample();              Sample* sample = file->GetFirstSample(pProgress);
3942                while (sample) {
3943                    if (sample->ullWavePoolOffset == soughtoffset)
3944                        return static_cast<gig::Sample*>(sample);
3945                    sample = file->GetNextSample();
3946                }
3947            } else {
3948                // use extension files and 32 bit wave pool offsets
3949                file_offset_t soughtoffset = file->pWavePoolTable[WavePoolTableIndex];
3950                file_offset_t soughtfileno = file->pWavePoolTableHi[WavePoolTableIndex];
3951                Sample* sample = file->GetFirstSample(pProgress);
3952                while (sample) {
3953                    if (sample->ullWavePoolOffset == soughtoffset &&
3954                        sample->FileNo == soughtfileno) return static_cast<gig::Sample*>(sample);
3955                    sample = file->GetNextSample();
3956                }
3957          }          }
3958          return NULL;          return NULL;
3959      }      }
# Line 4023  namespace { Line 4175  namespace {
4175          }          }
4176      }      }
4177    
4178    // *************** Script ***************
4179    // *
4180    
4181        Script::Script(ScriptGroup* group, RIFF::Chunk* ckScri) {
4182            pGroup = group;
4183            pChunk = ckScri;
4184            if (ckScri) { // object is loaded from file ...
4185                // read header
4186                uint32_t headerSize = ckScri->ReadUint32();
4187                Compression = (Compression_t) ckScri->ReadUint32();
4188                Encoding    = (Encoding_t) ckScri->ReadUint32();
4189                Language    = (Language_t) ckScri->ReadUint32();
4190                Bypass      = (Language_t) ckScri->ReadUint32() & 1;
4191                crc         = ckScri->ReadUint32();
4192                uint32_t nameSize = ckScri->ReadUint32();
4193                Name.resize(nameSize, ' ');
4194                for (int i = 0; i < nameSize; ++i)
4195                    Name[i] = ckScri->ReadUint8();
4196                // to handle potential future extensions of the header
4197                ckScri->SetPos(sizeof(int32_t) + headerSize);
4198                // read actual script data
4199                uint32_t scriptSize = uint32_t(ckScri->GetSize() - ckScri->GetPos());
4200                data.resize(scriptSize);
4201                for (int i = 0; i < scriptSize; ++i)
4202                    data[i] = ckScri->ReadUint8();
4203            } else { // this is a new script object, so just initialize it as such ...
4204                Compression = COMPRESSION_NONE;
4205                Encoding = ENCODING_ASCII;
4206                Language = LANGUAGE_NKSP;
4207                Bypass   = false;
4208                crc      = 0;
4209                Name     = "Unnamed Script";
4210            }
4211        }
4212    
4213        Script::~Script() {
4214        }
4215    
4216        /**
4217         * Returns the current script (i.e. as source code) in text format.
4218         */
4219        String Script::GetScriptAsText() {
4220            String s;
4221            s.resize(data.size(), ' ');
4222            memcpy(&s[0], &data[0], data.size());
4223            return s;
4224        }
4225    
4226        /**
4227         * Replaces the current script with the new script source code text given
4228         * by @a text.
4229         *
4230         * @param text - new script source code
4231         */
4232        void Script::SetScriptAsText(const String& text) {
4233            data.resize(text.size());
4234            memcpy(&data[0], &text[0], text.size());
4235        }
4236    
4237        /**
4238         * Apply this script to the respective RIFF chunks. You have to call
4239         * File::Save() to make changes persistent.
4240         *
4241         * Usually there is absolutely no need to call this method explicitly.
4242         * It will be called automatically when File::Save() was called.
4243         *
4244         * @param pProgress - callback function for progress notification
4245         */
4246        void Script::UpdateChunks(progress_t* pProgress) {
4247            // recalculate CRC32 check sum
4248            __resetCRC(crc);
4249            __calculateCRC(&data[0], data.size(), crc);
4250            __finalizeCRC(crc);
4251            // make sure chunk exists and has the required size
4252            const file_offset_t chunkSize = (file_offset_t) 7*sizeof(int32_t) + Name.size() + data.size();
4253            if (!pChunk) pChunk = pGroup->pList->AddSubChunk(CHUNK_ID_SCRI, chunkSize);
4254            else pChunk->Resize(chunkSize);
4255            // fill the chunk data to be written to disk
4256            uint8_t* pData = (uint8_t*) pChunk->LoadChunkData();
4257            int pos = 0;
4258            store32(&pData[pos], uint32_t(6*sizeof(int32_t) + Name.size())); // total header size
4259            pos += sizeof(int32_t);
4260            store32(&pData[pos], Compression);
4261            pos += sizeof(int32_t);
4262            store32(&pData[pos], Encoding);
4263            pos += sizeof(int32_t);
4264            store32(&pData[pos], Language);
4265            pos += sizeof(int32_t);
4266            store32(&pData[pos], Bypass ? 1 : 0);
4267            pos += sizeof(int32_t);
4268            store32(&pData[pos], crc);
4269            pos += sizeof(int32_t);
4270            store32(&pData[pos], (uint32_t) Name.size());
4271            pos += sizeof(int32_t);
4272            for (int i = 0; i < Name.size(); ++i, ++pos)
4273                pData[pos] = Name[i];
4274            for (int i = 0; i < data.size(); ++i, ++pos)
4275                pData[pos] = data[i];
4276        }
4277    
4278        /**
4279         * Move this script from its current ScriptGroup to another ScriptGroup
4280         * given by @a pGroup.
4281         *
4282         * @param pGroup - script's new group
4283         */
4284        void Script::SetGroup(ScriptGroup* pGroup) {
4285            if (this->pGroup == pGroup) return;
4286            if (pChunk)
4287                pChunk->GetParent()->MoveSubChunk(pChunk, pGroup->pList);
4288            this->pGroup = pGroup;
4289        }
4290    
4291        /**
4292         * Returns the script group this script currently belongs to. Each script
4293         * is a member of exactly one ScriptGroup.
4294         *
4295         * @returns current script group
4296         */
4297        ScriptGroup* Script::GetGroup() const {
4298            return pGroup;
4299        }
4300    
4301        /**
4302         * Make a (semi) deep copy of the Script object given by @a orig
4303         * and assign it to this object. Note: the ScriptGroup this Script
4304         * object belongs to remains untouched by this call.
4305         *
4306         * @param orig - original Script object to be copied from
4307         */
4308        void Script::CopyAssign(const Script* orig) {
4309            Name        = orig->Name;
4310            Compression = orig->Compression;
4311            Encoding    = orig->Encoding;
4312            Language    = orig->Language;
4313            Bypass      = orig->Bypass;
4314            data        = orig->data;
4315        }
4316    
4317        void Script::RemoveAllScriptReferences() {
4318            File* pFile = pGroup->pFile;
4319            for (int i = 0; pFile->GetInstrument(i); ++i) {
4320                Instrument* instr = pFile->GetInstrument(i);
4321                instr->RemoveScript(this);
4322            }
4323        }
4324    
4325    // *************** ScriptGroup ***************
4326    // *
4327    
4328        ScriptGroup::ScriptGroup(File* file, RIFF::List* lstRTIS) {
4329            pFile = file;
4330            pList = lstRTIS;
4331            pScripts = NULL;
4332            if (lstRTIS) {
4333                RIFF::Chunk* ckName = lstRTIS->GetSubChunk(CHUNK_ID_LSNM);
4334                ::LoadString(ckName, Name);
4335            } else {
4336                Name = "Default Group";
4337            }
4338        }
4339    
4340        ScriptGroup::~ScriptGroup() {
4341            if (pScripts) {
4342                std::list<Script*>::iterator iter = pScripts->begin();
4343                std::list<Script*>::iterator end  = pScripts->end();
4344                while (iter != end) {
4345                    delete *iter;
4346                    ++iter;
4347                }
4348                delete pScripts;
4349            }
4350        }
4351    
4352        /**
4353         * Apply this script group to the respective RIFF chunks. You have to call
4354         * File::Save() to make changes persistent.
4355         *
4356         * Usually there is absolutely no need to call this method explicitly.
4357         * It will be called automatically when File::Save() was called.
4358         *
4359         * @param pProgress - callback function for progress notification
4360         */
4361        void ScriptGroup::UpdateChunks(progress_t* pProgress) {
4362            if (pScripts) {
4363                if (!pList)
4364                    pList = pFile->pRIFF->GetSubList(LIST_TYPE_3LS)->AddSubList(LIST_TYPE_RTIS);
4365    
4366                // now store the name of this group as <LSNM> chunk as subchunk of the <RTIS> list chunk
4367                ::SaveString(CHUNK_ID_LSNM, NULL, pList, Name, String("Unnamed Group"), true, 64);
4368    
4369                for (std::list<Script*>::iterator it = pScripts->begin();
4370                     it != pScripts->end(); ++it)
4371                {
4372                    (*it)->UpdateChunks(pProgress);
4373                }
4374            }
4375        }
4376    
4377        /** @brief Get instrument script.
4378         *
4379         * Returns the real-time instrument script with the given index.
4380         *
4381         * @param index - number of the sought script (0..n)
4382         * @returns sought script or NULL if there's no such script
4383         */
4384        Script* ScriptGroup::GetScript(uint index) {
4385            if (!pScripts) LoadScripts();
4386            std::list<Script*>::iterator it = pScripts->begin();
4387            for (uint i = 0; it != pScripts->end(); ++i, ++it)
4388                if (i == index) return *it;
4389            return NULL;
4390        }
4391    
4392        /** @brief Add new instrument script.
4393         *
4394         * Adds a new real-time instrument script to the file. The script is not
4395         * actually used / executed unless it is referenced by an instrument to be
4396         * used. This is similar to samples, which you can add to a file, without
4397         * an instrument necessarily actually using it.
4398         *
4399         * You have to call Save() to make this persistent to the file.
4400         *
4401         * @return new empty script object
4402         */
4403        Script* ScriptGroup::AddScript() {
4404            if (!pScripts) LoadScripts();
4405            Script* pScript = new Script(this, NULL);
4406            pScripts->push_back(pScript);
4407            return pScript;
4408        }
4409    
4410        /** @brief Delete an instrument script.
4411         *
4412         * This will delete the given real-time instrument script. References of
4413         * instruments that are using that script will be removed accordingly.
4414         *
4415         * You have to call Save() to make this persistent to the file.
4416         *
4417         * @param pScript - script to delete
4418         * @throws gig::Exception if given script could not be found
4419         */
4420        void ScriptGroup::DeleteScript(Script* pScript) {
4421            if (!pScripts) LoadScripts();
4422            std::list<Script*>::iterator iter =
4423                find(pScripts->begin(), pScripts->end(), pScript);
4424            if (iter == pScripts->end())
4425                throw gig::Exception("Could not delete script, could not find given script");
4426            pScripts->erase(iter);
4427            pScript->RemoveAllScriptReferences();
4428            if (pScript->pChunk)
4429                pScript->pChunk->GetParent()->DeleteSubChunk(pScript->pChunk);
4430            delete pScript;
4431        }
4432    
4433        void ScriptGroup::LoadScripts() {
4434            if (pScripts) return;
4435            pScripts = new std::list<Script*>;
4436            if (!pList) return;
4437    
4438            for (RIFF::Chunk* ck = pList->GetFirstSubChunk(); ck;
4439                 ck = pList->GetNextSubChunk())
4440            {
4441                if (ck->GetChunkID() == CHUNK_ID_SCRI) {
4442                    pScripts->push_back(new Script(this, ck));
4443                }
4444            }
4445        }
4446    
4447  // *************** Instrument ***************  // *************** Instrument ***************
4448  // *  // *
4449    
# Line 4039  namespace { Line 4460  namespace {
4460          EffectSend = 0;          EffectSend = 0;
4461          Attenuation = 0;          Attenuation = 0;
4462          FineTune = 0;          FineTune = 0;
4463          PitchbendRange = 0;          PitchbendRange = 2;
4464          PianoReleaseMode = false;          PianoReleaseMode = false;
4465          DimensionKeyRange.low = 0;          DimensionKeyRange.low = 0;
4466          DimensionKeyRange.high = 0;          DimensionKeyRange.high = 0;
4467          pMidiRules = new MidiRule*[3];          pMidiRules = new MidiRule*[3];
4468          pMidiRules[0] = NULL;          pMidiRules[0] = NULL;
4469            pScriptRefs = NULL;
4470    
4471          // Loading          // Loading
4472          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);          RIFF::List* lart = insList->GetSubList(LIST_TYPE_LART);
# Line 4105  namespace { Line 4527  namespace {
4527              }              }
4528          }          }
4529    
4530            // own gig format extensions
4531            RIFF::List* lst3LS = insList->GetSubList(LIST_TYPE_3LS);
4532            if (lst3LS) {
4533                RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4534                if (ckSCSL) {
4535                    int headerSize = ckSCSL->ReadUint32();
4536                    int slotCount  = ckSCSL->ReadUint32();
4537                    if (slotCount) {
4538                        int slotSize  = ckSCSL->ReadUint32();
4539                        ckSCSL->SetPos(headerSize); // in case of future header extensions
4540                        int unknownSpace = slotSize - 2*sizeof(uint32_t); // in case of future slot extensions
4541                        for (int i = 0; i < slotCount; ++i) {
4542                            _ScriptPooolEntry e;
4543                            e.fileOffset = ckSCSL->ReadUint32();
4544                            e.bypass     = ckSCSL->ReadUint32() & 1;
4545                            if (unknownSpace) ckSCSL->SetPos(unknownSpace, RIFF::stream_curpos); // in case of future extensions
4546                            scriptPoolFileOffsets.push_back(e);
4547                        }
4548                    }
4549                }
4550            }
4551    
4552          __notify_progress(pProgress, 1.0f); // notify done          __notify_progress(pProgress, 1.0f); // notify done
4553      }      }
4554    
# Line 4125  namespace { Line 4569  namespace {
4569              delete pMidiRules[i];              delete pMidiRules[i];
4570          }          }
4571          delete[] pMidiRules;          delete[] pMidiRules;
4572            if (pScriptRefs) delete pScriptRefs;
4573      }      }
4574    
4575      /**      /**
# Line 4134  namespace { Line 4579  namespace {
4579       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
4580       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
4581       *       *
4582         * @param pProgress - callback function for progress notification
4583       * @throws gig::Exception if samples cannot be dereferenced       * @throws gig::Exception if samples cannot be dereferenced
4584       */       */
4585      void Instrument::UpdateChunks() {      void Instrument::UpdateChunks(progress_t* pProgress) {
4586          // first update base classes' chunks          // first update base classes' chunks
4587          DLS::Instrument::UpdateChunks();          DLS::Instrument::UpdateChunks(pProgress);
4588    
4589          // update Regions' chunks          // update Regions' chunks
4590          {          {
4591              RegionList::iterator iter = pRegions->begin();              RegionList::iterator iter = pRegions->begin();
4592              RegionList::iterator end  = pRegions->end();              RegionList::iterator end  = pRegions->end();
4593              for (; iter != end; ++iter)              for (; iter != end; ++iter)
4594                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
4595          }          }
4596    
4597          // make sure 'lart' RIFF list chunk exists          // make sure 'lart' RIFF list chunk exists
# Line 4180  namespace { Line 4626  namespace {
4626                  pMidiRules[i]->UpdateChunks(pData);                  pMidiRules[i]->UpdateChunks(pData);
4627              }              }
4628          }          }
4629    
4630            // own gig format extensions
4631           if (ScriptSlotCount()) {
4632               // make sure we have converted the original loaded script file
4633               // offsets into valid Script object pointers
4634               LoadScripts();
4635    
4636               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4637               if (!lst3LS) lst3LS = pCkInstrument->AddSubList(LIST_TYPE_3LS);
4638               const int slotCount = (int) pScriptRefs->size();
4639               const int headerSize = 3 * sizeof(uint32_t);
4640               const int slotSize  = 2 * sizeof(uint32_t);
4641               const int totalChunkSize = headerSize + slotCount * slotSize;
4642               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4643               if (!ckSCSL) ckSCSL = lst3LS->AddSubChunk(CHUNK_ID_SCSL, totalChunkSize);
4644               else ckSCSL->Resize(totalChunkSize);
4645               uint8_t* pData = (uint8_t*) ckSCSL->LoadChunkData();
4646               int pos = 0;
4647               store32(&pData[pos], headerSize);
4648               pos += sizeof(uint32_t);
4649               store32(&pData[pos], slotCount);
4650               pos += sizeof(uint32_t);
4651               store32(&pData[pos], slotSize);
4652               pos += sizeof(uint32_t);
4653               for (int i = 0; i < slotCount; ++i) {
4654                   // arbitrary value, the actual file offset will be updated in
4655                   // UpdateScriptFileOffsets() after the file has been resized
4656                   int bogusFileOffset = 0;
4657                   store32(&pData[pos], bogusFileOffset);
4658                   pos += sizeof(uint32_t);
4659                   store32(&pData[pos], (*pScriptRefs)[i].bypass ? 1 : 0);
4660                   pos += sizeof(uint32_t);
4661               }
4662           } else {
4663               // no script slots, so get rid of any LS custom RIFF chunks (if any)
4664               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4665               if (lst3LS) pCkInstrument->DeleteSubChunk(lst3LS);
4666           }
4667        }
4668    
4669        void Instrument::UpdateScriptFileOffsets() {
4670           // own gig format extensions
4671           if (pScriptRefs && pScriptRefs->size() > 0) {
4672               RIFF::List* lst3LS = pCkInstrument->GetSubList(LIST_TYPE_3LS);
4673               RIFF::Chunk* ckSCSL = lst3LS->GetSubChunk(CHUNK_ID_SCSL);
4674               const int slotCount = (int) pScriptRefs->size();
4675               const int headerSize = 3 * sizeof(uint32_t);
4676               ckSCSL->SetPos(headerSize);
4677               for (int i = 0; i < slotCount; ++i) {
4678                   uint32_t fileOffset = uint32_t(
4679                        (*pScriptRefs)[i].script->pChunk->GetFilePos() -
4680                        (*pScriptRefs)[i].script->pChunk->GetPos() -
4681                        CHUNK_HEADER_SIZE(ckSCSL->GetFile()->GetFileOffsetSize())
4682                   );
4683                   ckSCSL->WriteUint32(&fileOffset);
4684                   // jump over flags entry (containing the bypass flag)
4685                   ckSCSL->SetPos(sizeof(uint32_t), RIFF::stream_curpos);
4686               }
4687           }        
4688      }      }
4689    
4690      /**      /**
# Line 4234  namespace { Line 4739  namespace {
4739          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);          RIFF::List* rgn = lrgn->AddSubList(LIST_TYPE_RGN);
4740          Region* pNewRegion = new Region(this, rgn);          Region* pNewRegion = new Region(this, rgn);
4741          pRegions->push_back(pNewRegion);          pRegions->push_back(pNewRegion);
4742          Regions = pRegions->size();          Regions = (uint32_t) pRegions->size();
4743          // update Region key table for fast lookup          // update Region key table for fast lookup
4744          UpdateRegionKeyTable();          UpdateRegionKeyTable();
4745          // done          // done
# Line 4249  namespace { Line 4754  namespace {
4754      }      }
4755    
4756      /**      /**
4757         * Move this instrument at the position before @arg dst.
4758         *
4759         * This method can be used to reorder the sequence of instruments in a
4760         * .gig file. This might be helpful especially on large .gig files which
4761         * contain a large number of instruments within the same .gig file. So
4762         * grouping such instruments to similar ones, can help to keep track of them
4763         * when working with such complex .gig files.
4764         *
4765         * When calling this method, this instrument will be removed from in its
4766         * current position in the instruments list and moved to the requested
4767         * target position provided by @param dst. You may also pass NULL as
4768         * argument to this method, in that case this intrument will be moved to the
4769         * very end of the .gig file's instrument list.
4770         *
4771         * You have to call Save() to make the order change persistent to the .gig
4772         * file.
4773         *
4774         * Currently this method is limited to moving the instrument within the same
4775         * .gig file. Trying to move it to another .gig file by calling this method
4776         * will throw an exception.
4777         *
4778         * @param dst - destination instrument at which this instrument will be
4779         *              moved to, or pass NULL for moving to end of list
4780         * @throw gig::Exception if this instrument and target instrument are not
4781         *                       part of the same file
4782         */
4783        void Instrument::MoveTo(Instrument* dst) {
4784            if (dst && GetParent() != dst->GetParent())
4785                throw Exception(
4786                    "gig::Instrument::MoveTo() can only be used for moving within "
4787                    "the same gig file."
4788                );
4789    
4790            File* pFile = (File*) GetParent();
4791    
4792            // move this instrument within the instrument list
4793            {
4794                File::InstrumentList& list = *pFile->pInstruments;
4795    
4796                File::InstrumentList::iterator itFrom =
4797                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(this));
4798    
4799                File::InstrumentList::iterator itTo =
4800                    std::find(list.begin(), list.end(), static_cast<DLS::Instrument*>(dst));
4801    
4802                list.splice(itTo, list, itFrom);
4803            }
4804    
4805            // move the instrument's actual list RIFF chunk appropriately
4806            RIFF::List* lstCkInstruments = pFile->pRIFF->GetSubList(LIST_TYPE_LINS);
4807            lstCkInstruments->MoveSubChunk(
4808                this->pCkInstrument,
4809                (RIFF::Chunk*) ((dst) ? dst->pCkInstrument : NULL)
4810            );
4811        }
4812    
4813        /**
4814       * Returns a MIDI rule of the instrument.       * Returns a MIDI rule of the instrument.
4815       *       *
4816       * 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 4873  namespace {
4873          pMidiRules[i] = 0;          pMidiRules[i] = 0;
4874      }      }
4875    
4876        void Instrument::LoadScripts() {
4877            if (pScriptRefs) return;
4878            pScriptRefs = new std::vector<_ScriptPooolRef>;
4879            if (scriptPoolFileOffsets.empty()) return;
4880            File* pFile = (File*) GetParent();
4881            for (uint k = 0; k < scriptPoolFileOffsets.size(); ++k) {
4882                uint32_t soughtOffset = scriptPoolFileOffsets[k].fileOffset;
4883                for (uint i = 0; pFile->GetScriptGroup(i); ++i) {
4884                    ScriptGroup* group = pFile->GetScriptGroup(i);
4885                    for (uint s = 0; group->GetScript(s); ++s) {
4886                        Script* script = group->GetScript(s);
4887                        if (script->pChunk) {
4888                            uint32_t offset = uint32_t(
4889                                script->pChunk->GetFilePos() -
4890                                script->pChunk->GetPos() -
4891                                CHUNK_HEADER_SIZE(script->pChunk->GetFile()->GetFileOffsetSize())
4892                            );
4893                            if (offset == soughtOffset)
4894                            {
4895                                _ScriptPooolRef ref;
4896                                ref.script = script;
4897                                ref.bypass = scriptPoolFileOffsets[k].bypass;
4898                                pScriptRefs->push_back(ref);
4899                                break;
4900                            }
4901                        }
4902                    }
4903                }
4904            }
4905            // we don't need that anymore
4906            scriptPoolFileOffsets.clear();
4907        }
4908    
4909        /** @brief Get instrument script (gig format extension).
4910         *
4911         * Returns the real-time instrument script of instrument script slot
4912         * @a index.
4913         *
4914         * @note This is an own format extension which did not exist i.e. in the
4915         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4916         * gigedit.
4917         *
4918         * @param index - instrument script slot index
4919         * @returns script or NULL if index is out of bounds
4920         */
4921        Script* Instrument::GetScriptOfSlot(uint index) {
4922            LoadScripts();
4923            if (index >= pScriptRefs->size()) return NULL;
4924            return pScriptRefs->at(index).script;
4925        }
4926    
4927        /** @brief Add new instrument script slot (gig format extension).
4928         *
4929         * Add the given real-time instrument script reference to this instrument,
4930         * which shall be executed by the sampler for for this instrument. The
4931         * script will be added to the end of the script list of this instrument.
4932         * The positions of the scripts in the Instrument's Script list are
4933         * relevant, because they define in which order they shall be executed by
4934         * the sampler. For this reason it is also legal to add the same script
4935         * twice to an instrument, for example you might have a script called
4936         * "MyFilter" which performs an event filter task, and you might have
4937         * another script called "MyNoteTrigger" which triggers new notes, then you
4938         * might for example have the following list of scripts on the instrument:
4939         *
4940         * 1. Script "MyFilter"
4941         * 2. Script "MyNoteTrigger"
4942         * 3. Script "MyFilter"
4943         *
4944         * Which would make sense, because the 2nd script launched new events, which
4945         * you might need to filter as well.
4946         *
4947         * There are two ways to disable / "bypass" scripts. You can either disable
4948         * a script locally for the respective script slot on an instrument (i.e. by
4949         * passing @c false to the 2nd argument of this method, or by calling
4950         * SetScriptBypassed()). Or you can disable a script globally for all slots
4951         * and all instruments by setting Script::Bypass.
4952         *
4953         * @note This is an own format extension which did not exist i.e. in the
4954         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4955         * gigedit.
4956         *
4957         * @param pScript - script that shall be executed for this instrument
4958         * @param bypass  - if enabled, the sampler shall skip executing this
4959         *                  script (in the respective list position)
4960         * @see SetScriptBypassed()
4961         */
4962        void Instrument::AddScriptSlot(Script* pScript, bool bypass) {
4963            LoadScripts();
4964            _ScriptPooolRef ref = { pScript, bypass };
4965            pScriptRefs->push_back(ref);
4966        }
4967    
4968        /** @brief Flip two script slots with each other (gig format extension).
4969         *
4970         * Swaps the position of the two given scripts in the Instrument's Script
4971         * list. The positions of the scripts in the Instrument's Script list are
4972         * relevant, because they define in which order they shall be executed by
4973         * the sampler.
4974         *
4975         * @note This is an own format extension which did not exist i.e. in the
4976         * GigaStudio 4 software. It will currently only work with LinuxSampler and
4977         * gigedit.
4978         *
4979         * @param index1 - index of the first script slot to swap
4980         * @param index2 - index of the second script slot to swap
4981         */
4982        void Instrument::SwapScriptSlots(uint index1, uint index2) {
4983            LoadScripts();
4984            if (index1 >= pScriptRefs->size() || index2 >= pScriptRefs->size())
4985                return;
4986            _ScriptPooolRef tmp = (*pScriptRefs)[index1];
4987            (*pScriptRefs)[index1] = (*pScriptRefs)[index2];
4988            (*pScriptRefs)[index2] = tmp;
4989        }
4990    
4991        /** @brief Remove script slot.
4992         *
4993         * Removes the script slot with the given slot index.
4994         *
4995         * @param index - index of script slot to remove
4996         */
4997        void Instrument::RemoveScriptSlot(uint index) {
4998            LoadScripts();
4999            if (index >= pScriptRefs->size()) return;
5000            pScriptRefs->erase( pScriptRefs->begin() + index );
5001        }
5002    
5003        /** @brief Remove reference to given Script (gig format extension).
5004         *
5005         * This will remove all script slots on the instrument which are referencing
5006         * the given script.
5007         *
5008         * @note This is an own format extension which did not exist i.e. in the
5009         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5010         * gigedit.
5011         *
5012         * @param pScript - script reference to remove from this instrument
5013         * @see RemoveScriptSlot()
5014         */
5015        void Instrument::RemoveScript(Script* pScript) {
5016            LoadScripts();
5017            for (ssize_t i = pScriptRefs->size() - 1; i >= 0; --i) {
5018                if ((*pScriptRefs)[i].script == pScript) {
5019                    pScriptRefs->erase( pScriptRefs->begin() + i );
5020                }
5021            }
5022        }
5023    
5024        /** @brief Instrument's amount of script slots.
5025         *
5026         * This method returns the amount of script slots this instrument currently
5027         * uses.
5028         *
5029         * A script slot is a reference of a real-time instrument script to be
5030         * executed by the sampler. The scripts will be executed by the sampler in
5031         * sequence of the slots. One (same) script may be referenced multiple
5032         * times in different slots.
5033         *
5034         * @note This is an own format extension which did not exist i.e. in the
5035         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5036         * gigedit.
5037         */
5038        uint Instrument::ScriptSlotCount() const {
5039            return uint(pScriptRefs ? pScriptRefs->size() : scriptPoolFileOffsets.size());
5040        }
5041    
5042        /** @brief Whether script execution shall be skipped.
5043         *
5044         * Defines locally for the Script reference slot in the Instrument's Script
5045         * list, whether the script shall be skipped by the sampler regarding
5046         * execution.
5047         *
5048         * It is also possible to ignore exeuction of the script globally, for all
5049         * slots and for all instruments by setting Script::Bypass.
5050         *
5051         * @note This is an own format extension which did not exist i.e. in the
5052         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5053         * gigedit.
5054         *
5055         * @param index - index of the script slot on this instrument
5056         * @see Script::Bypass
5057         */
5058        bool Instrument::IsScriptSlotBypassed(uint index) {
5059            if (index >= ScriptSlotCount()) return false;
5060            return pScriptRefs ? pScriptRefs->at(index).bypass
5061                               : scriptPoolFileOffsets.at(index).bypass;
5062            
5063        }
5064    
5065        /** @brief Defines whether execution shall be skipped.
5066         *
5067         * You can call this method to define locally whether or whether not the
5068         * given script slot shall be executed by the sampler.
5069         *
5070         * @note This is an own format extension which did not exist i.e. in the
5071         * GigaStudio 4 software. It will currently only work with LinuxSampler and
5072         * gigedit.
5073         *
5074         * @param index - script slot index on this instrument
5075         * @param bBypass - if true, the script slot will be skipped by the sampler
5076         * @see Script::Bypass
5077         */
5078        void Instrument::SetScriptSlotBypassed(uint index, bool bBypass) {
5079            if (index >= ScriptSlotCount()) return;
5080            if (pScriptRefs)
5081                pScriptRefs->at(index).bypass = bBypass;
5082            else
5083                scriptPoolFileOffsets.at(index).bypass = bBypass;
5084        }
5085    
5086      /**      /**
5087       * 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
5088       * and assign it to this object.       * and assign it to this object.
# Line 4344  namespace { Line 5116  namespace {
5116          PitchbendRange = orig->PitchbendRange;          PitchbendRange = orig->PitchbendRange;
5117          PianoReleaseMode = orig->PianoReleaseMode;          PianoReleaseMode = orig->PianoReleaseMode;
5118          DimensionKeyRange = orig->DimensionKeyRange;          DimensionKeyRange = orig->DimensionKeyRange;
5119            scriptPoolFileOffsets = orig->scriptPoolFileOffsets;
5120            pScriptRefs = orig->pScriptRefs;
5121                    
5122          // free old midi rules          // free old midi rules
5123          for (int i = 0 ; pMidiRules[i] ; i++) {          for (int i = 0 ; pMidiRules[i] ; i++) {
# Line 4398  namespace { Line 5172  namespace {
5172       *       *
5173       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
5174       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
5175         *
5176         * @param pProgress - callback function for progress notification
5177       */       */
5178      void Group::UpdateChunks() {      void Group::UpdateChunks(progress_t* pProgress) {
5179          // make sure <3gri> and <3gnl> list chunks exist          // make sure <3gri> and <3gnl> list chunks exist
5180          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);          RIFF::List* _3gri = pFile->pRIFF->GetSubList(LIST_TYPE_3GRI);
5181          if (!_3gri) {          if (!_3gri) {
# Line 4529  namespace { Line 5305  namespace {
5305          bAutoLoad = true;          bAutoLoad = true;
5306          *pVersion = VERSION_3;          *pVersion = VERSION_3;
5307          pGroups = NULL;          pGroups = NULL;
5308            pScriptGroups = NULL;
5309          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5310          pInfo->ArchivalLocation = String(256, ' ');          pInfo->ArchivalLocation = String(256, ' ');
5311    
# Line 4544  namespace { Line 5321  namespace {
5321      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {      File::File(RIFF::File* pRIFF) : DLS::File(pRIFF) {
5322          bAutoLoad = true;          bAutoLoad = true;
5323          pGroups = NULL;          pGroups = NULL;
5324            pScriptGroups = NULL;
5325          pInfo->SetFixedStringLengths(_FileFixedStringLengths);          pInfo->SetFixedStringLengths(_FileFixedStringLengths);
5326      }      }
5327    
# Line 4557  namespace { Line 5335  namespace {
5335              }              }
5336              delete pGroups;              delete pGroups;
5337          }          }
5338            if (pScriptGroups) {
5339                std::list<ScriptGroup*>::iterator iter = pScriptGroups->begin();
5340                std::list<ScriptGroup*>::iterator end  = pScriptGroups->end();
5341                while (iter != end) {
5342                    delete *iter;
5343                    ++iter;
5344                }
5345                delete pScriptGroups;
5346            }
5347      }      }
5348    
5349      Sample* File::GetFirstSample(progress_t* pProgress) {      Sample* File::GetFirstSample(progress_t* pProgress) {
# Line 4665  namespace { Line 5452  namespace {
5452          int iTotalSamples = WavePoolCount;          int iTotalSamples = WavePoolCount;
5453    
5454          // check if samples should be loaded from extension files          // check if samples should be loaded from extension files
5455            // (only for old gig files < 2 GB)
5456          int lastFileNo = 0;          int lastFileNo = 0;
5457          for (int i = 0 ; i < WavePoolCount ; i++) {          if (!file->IsNew() && !(file->GetCurrentFileSize() >> 31)) {
5458              if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];              for (int i = 0 ; i < WavePoolCount ; i++) {
5459                    if (pWavePoolTableHi[i] > lastFileNo) lastFileNo = pWavePoolTableHi[i];
5460                }
5461          }          }
5462          String name(pRIFF->GetFileName());          String name(pRIFF->GetFileName());
5463          int nameLen = name.length();          int nameLen = (int) name.length();
5464          char suffix[6];          char suffix[6];
5465          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;          if (nameLen > 4 && name.substr(nameLen - 4) == ".gig") nameLen -= 4;
5466    
5467          for (int fileNo = 0 ; ; ) {          for (int fileNo = 0 ; ; ) {
5468              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);              RIFF::List* wvpl = file->GetSubList(LIST_TYPE_WVPL);
5469              if (wvpl) {              if (wvpl) {
5470                  unsigned long wvplFileOffset = wvpl->GetFilePos();                  file_offset_t wvplFileOffset = wvpl->GetFilePos();
5471                  RIFF::List* wave = wvpl->GetFirstSubList();                  RIFF::List* wave = wvpl->GetFirstSubList();
5472                  while (wave) {                  while (wave) {
5473                      if (wave->GetListType() == LIST_TYPE_WAVE) {                      if (wave->GetListType() == LIST_TYPE_WAVE) {
# Line 4685  namespace { Line 5475  namespace {
5475                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;                          const float subprogress = (float) iSampleIndex / (float) iTotalSamples;
5476                          __notify_progress(pProgress, subprogress);                          __notify_progress(pProgress, subprogress);
5477    
5478                          unsigned long waveFileOffset = wave->GetFilePos();                          file_offset_t waveFileOffset = wave->GetFilePos();
5479                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo));                          pSamples->push_back(new Sample(this, wave, waveFileOffset - wvplFileOffset, fileNo, iSampleIndex));
5480    
5481                          iSampleIndex++;                          iSampleIndex++;
5482                      }                      }
# Line 4839  namespace { Line 5629  namespace {
5629              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);              mGroups[pFile->GetSample(i)->GetGroup()]->AddSample(s);
5630              mSamples[pFile->GetSample(i)] = s;              mSamples[pFile->GetSample(i)] = s;
5631          }          }
5632            
5633            // clone script groups and their scripts
5634            for (int iGroup = 0; pFile->GetScriptGroup(iGroup); ++iGroup) {
5635                ScriptGroup* sg = pFile->GetScriptGroup(iGroup);
5636                ScriptGroup* dg = AddScriptGroup();
5637                dg->Name = "COPY" + ToString(iCallCount) + "_" + sg->Name;
5638                for (int iScript = 0; sg->GetScript(iScript); ++iScript) {
5639                    Script* ss = sg->GetScript(iScript);
5640                    Script* ds = dg->AddScript();
5641                    ds->CopyAssign(ss);
5642                }
5643            }
5644    
5645          //BUG: For some reason this method only works with this additional          //BUG: For some reason this method only works with this additional
5646          //     Save() call in between here.          //     Save() call in between here.
5647          //          //
# Line 4924  namespace { Line 5726  namespace {
5726          if (!_3crc) return;          if (!_3crc) return;
5727    
5728          // get the index of the sample          // get the index of the sample
5729          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;  
             }  
         }  
5730          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");
5731    
5732          // write the CRC-32 checksum to disk          // write the CRC-32 checksum to disk
5733          _3crc->SetPos(iWaveIndex * 8);          _3crc->SetPos(iWaveIndex * 8);
5734          uint32_t tmp = 1;          uint32_t one = 1;
5735          _3crc->WriteUint32(&tmp); // unknown, always 1?          _3crc->WriteUint32(&one); // always 1
5736          _3crc->WriteUint32(&crc);          _3crc->WriteUint32(&crc);
5737      }      }
5738    
5739        uint32_t File::GetSampleChecksum(Sample* pSample) {
5740            // get the index of the sample
5741            int iWaveIndex = GetWaveTableIndexOf(pSample);
5742            if (iWaveIndex < 0) throw gig::Exception("Could not retrieve reference crc of sample, could not resolve sample's wave table index");
5743    
5744            return GetSampleChecksumByIndex(iWaveIndex);
5745        }
5746    
5747        uint32_t File::GetSampleChecksumByIndex(int index) {
5748            if (index < 0) throw gig::Exception("Could not retrieve reference crc of sample, invalid wave pool index of sample");
5749    
5750            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5751            if (!_3crc) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5752            uint8_t* pData = (uint8_t*) _3crc->LoadChunkData();
5753            if (!pData) throw gig::Exception("Could not retrieve reference crc of sample, no checksums stored for this file yet");
5754    
5755            // read the CRC-32 checksum directly from disk
5756            size_t pos = index * 8;
5757            if (pos + 8 > _3crc->GetNewSize())
5758                throw gig::Exception("Could not retrieve reference crc of sample, could not seek to required position in crc chunk");
5759    
5760            uint32_t one = load32(&pData[pos]); // always 1
5761            if (one != 1)
5762                throw gig::Exception("Could not retrieve reference crc of sample, because reference checksum table is damaged");
5763    
5764            return load32(&pData[pos+4]);
5765        }
5766    
5767        int File::GetWaveTableIndexOf(gig::Sample* pSample) {
5768            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5769            File::SampleList::iterator iter = pSamples->begin();
5770            File::SampleList::iterator end  = pSamples->end();
5771            for (int index = 0; iter != end; ++iter, ++index)
5772                if (*iter == pSample)
5773                    return index;
5774            return -1;
5775        }
5776    
5777        /**
5778         * Checks whether the file's "3CRC" chunk was damaged. This chunk contains
5779         * the CRC32 check sums of all samples' raw wave data.
5780         *
5781         * @return true if 3CRC chunk is OK, or false if 3CRC chunk is damaged
5782         */
5783        bool File::VerifySampleChecksumTable() {
5784            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5785            if (!_3crc) return false;
5786            if (_3crc->GetNewSize() <= 0) return false;
5787            if (_3crc->GetNewSize() % 8) return false;
5788            if (!pSamples) GetFirstSample(); // make sure sample chunks were scanned
5789            if (_3crc->GetNewSize() != pSamples->size() * 8) return false;
5790    
5791            const file_offset_t n = _3crc->GetNewSize() / 8;
5792    
5793            uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5794            if (!pData) return false;
5795    
5796            for (file_offset_t i = 0; i < n; ++i) {
5797                uint32_t one = pData[i*2];
5798                if (one != 1) return false;
5799            }
5800    
5801            return true;
5802        }
5803    
5804        /**
5805         * Recalculates CRC32 checksums for all samples and rebuilds this gig
5806         * file's checksum table with those new checksums. This might usually
5807         * just be necessary if the checksum table was damaged.
5808         *
5809         * @e IMPORTANT: The current implementation of this method only works
5810         * with files that have not been modified since it was loaded, because
5811         * it expects that no externally caused file structure changes are
5812         * required!
5813         *
5814         * Due to the expectation above, this method is currently protected
5815         * and actually only used by the command line tool "gigdump" yet.
5816         *
5817         * @returns true if Save() is required to be called after this call,
5818         *          false if no further action is required
5819         */
5820        bool File::RebuildSampleChecksumTable() {
5821            // make sure sample chunks were scanned
5822            if (!pSamples) GetFirstSample();
5823    
5824            bool bRequiresSave = false;
5825    
5826            // make sure "3CRC" chunk exists with required size
5827            RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
5828            if (!_3crc) {
5829                _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
5830                // the order of einf and 3crc is not the same in v2 and v3
5831                RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
5832                if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
5833                bRequiresSave = true;
5834            } else if (_3crc->GetNewSize() != pSamples->size() * 8) {
5835                _3crc->Resize(pSamples->size() * 8);
5836                bRequiresSave = true;
5837            }
5838    
5839            if (bRequiresSave) { // refill CRC table for all samples in RAM ...
5840                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
5841                {
5842                    File::SampleList::iterator iter = pSamples->begin();
5843                    File::SampleList::iterator end  = pSamples->end();
5844                    for (; iter != end; ++iter) {
5845                        gig::Sample* pSample = (gig::Sample*) *iter;
5846                        int index = GetWaveTableIndexOf(pSample);
5847                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5848                        pData[index*2]   = 1; // always 1
5849                        pData[index*2+1] = pSample->CalculateWaveDataChecksum();
5850                    }
5851                }
5852            } else { // no file structure changes necessary, so directly write to disk and we are done ...
5853                // make sure file is in write mode
5854                pRIFF->SetMode(RIFF::stream_mode_read_write);
5855                {
5856                    File::SampleList::iterator iter = pSamples->begin();
5857                    File::SampleList::iterator end  = pSamples->end();
5858                    for (; iter != end; ++iter) {
5859                        gig::Sample* pSample = (gig::Sample*) *iter;
5860                        int index = GetWaveTableIndexOf(pSample);
5861                        if (index < 0) throw gig::Exception("Could not rebuild crc table for samples, wave table index of a sample could not be resolved");
5862                        pSample->crc  = pSample->CalculateWaveDataChecksum();
5863                        SetSampleChecksum(pSample, pSample->crc);
5864                    }
5865                }
5866            }
5867    
5868            return bRequiresSave;
5869        }
5870    
5871      Group* File::GetFirstGroup() {      Group* File::GetFirstGroup() {
5872          if (!pGroups) LoadGroups();          if (!pGroups) LoadGroups();
5873          // there must always be at least one group          // there must always be at least one group
# Line 5069  namespace { Line 5995  namespace {
5995          }          }
5996      }      }
5997    
5998        /** @brief Get instrument script group (by index).
5999         *
6000         * Returns the real-time instrument script group with the given index.
6001         *
6002         * @param index - number of the sought group (0..n)
6003         * @returns sought script group or NULL if there's no such group
6004         */
6005        ScriptGroup* File::GetScriptGroup(uint index) {
6006            if (!pScriptGroups) LoadScriptGroups();
6007            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6008            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6009                if (i == index) return *it;
6010            return NULL;
6011        }
6012    
6013        /** @brief Get instrument script group (by name).
6014         *
6015         * Returns the first real-time instrument script group found with the given
6016         * group name. Note that group names may not necessarily be unique.
6017         *
6018         * @param name - name of the sought script group
6019         * @returns sought script group or NULL if there's no such group
6020         */
6021        ScriptGroup* File::GetScriptGroup(const String& name) {
6022            if (!pScriptGroups) LoadScriptGroups();
6023            std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6024            for (uint i = 0; it != pScriptGroups->end(); ++i, ++it)
6025                if ((*it)->Name == name) return *it;
6026            return NULL;
6027        }
6028    
6029        /** @brief Add new instrument script group.
6030         *
6031         * Adds a new, empty real-time instrument script group to the file.
6032         *
6033         * You have to call Save() to make this persistent to the file.
6034         *
6035         * @return new empty script group
6036         */
6037        ScriptGroup* File::AddScriptGroup() {
6038            if (!pScriptGroups) LoadScriptGroups();
6039            ScriptGroup* pScriptGroup = new ScriptGroup(this, NULL);
6040            pScriptGroups->push_back(pScriptGroup);
6041            return pScriptGroup;
6042        }
6043    
6044        /** @brief Delete an instrument script group.
6045         *
6046         * This will delete the given real-time instrument script group and all its
6047         * instrument scripts it contains. References inside instruments that are
6048         * using the deleted scripts will be removed from the respective instruments
6049         * accordingly.
6050         *
6051         * You have to call Save() to make this persistent to the file.
6052         *
6053         * @param pScriptGroup - script group to delete
6054         * @throws gig::Exception if given script group could not be found
6055         */
6056        void File::DeleteScriptGroup(ScriptGroup* pScriptGroup) {
6057            if (!pScriptGroups) LoadScriptGroups();
6058            std::list<ScriptGroup*>::iterator iter =
6059                find(pScriptGroups->begin(), pScriptGroups->end(), pScriptGroup);
6060            if (iter == pScriptGroups->end())
6061                throw gig::Exception("Could not delete script group, could not find given script group");
6062            pScriptGroups->erase(iter);
6063            for (int i = 0; pScriptGroup->GetScript(i); ++i)
6064                pScriptGroup->DeleteScript(pScriptGroup->GetScript(i));
6065            if (pScriptGroup->pList)
6066                pScriptGroup->pList->GetParent()->DeleteSubChunk(pScriptGroup->pList);
6067            delete pScriptGroup;
6068        }
6069    
6070        void File::LoadScriptGroups() {
6071            if (pScriptGroups) return;
6072            pScriptGroups = new std::list<ScriptGroup*>;
6073            RIFF::List* lstLS = pRIFF->GetSubList(LIST_TYPE_3LS);
6074            if (lstLS) {
6075                for (RIFF::List* lst = lstLS->GetFirstSubList(); lst;
6076                     lst = lstLS->GetNextSubList())
6077                {
6078                    if (lst->GetListType() == LIST_TYPE_RTIS) {
6079                        pScriptGroups->push_back(new ScriptGroup(this, lst));
6080                    }
6081                }
6082            }
6083        }
6084    
6085      /**      /**
6086       * Apply all the gig file's current instruments, samples, groups and settings       * Apply all the gig file's current instruments, samples, groups and settings
6087       * 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 6090  namespace {
6090       * Usually there is absolutely no need to call this method explicitly.       * Usually there is absolutely no need to call this method explicitly.
6091       * It will be called automatically when File::Save() was called.       * It will be called automatically when File::Save() was called.
6092       *       *
6093         * @param pProgress - callback function for progress notification
6094       * @throws Exception - on errors       * @throws Exception - on errors
6095       */       */
6096      void File::UpdateChunks() {      void File::UpdateChunks(progress_t* pProgress) {
6097          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;          bool newFile = pRIFF->GetSubList(LIST_TYPE_INFO) == NULL;
6098    
6099          b64BitWavePoolOffsets = pVersion && pVersion->major == 3;          // update own gig format extension chunks
6100            // (not part of the GigaStudio 4 format)
6101            RIFF::List* lst3LS = pRIFF->GetSubList(LIST_TYPE_3LS);
6102            if (!lst3LS) {
6103                lst3LS = pRIFF->AddSubList(LIST_TYPE_3LS);
6104            }
6105            // Make sure <3LS > chunk is placed before <ptbl> chunk. The precise
6106            // location of <3LS > is irrelevant, however it should be located
6107            // before  the actual wave data
6108            RIFF::Chunk* ckPTBL = pRIFF->GetSubChunk(CHUNK_ID_PTBL);
6109            pRIFF->MoveSubChunk(lst3LS, ckPTBL);
6110    
6111            // This must be performed before writing the chunks for instruments,
6112            // because the instruments' script slots will write the file offsets
6113            // of the respective instrument script chunk as reference.
6114            if (pScriptGroups) {
6115                // Update instrument script (group) chunks.
6116                for (std::list<ScriptGroup*>::iterator it = pScriptGroups->begin();
6117                     it != pScriptGroups->end(); ++it)
6118                {
6119                    (*it)->UpdateChunks(pProgress);
6120                }
6121            }
6122    
6123            // in case no libgig custom format data was added, then remove the
6124            // custom "3LS " chunk again
6125            if (!lst3LS->CountSubChunks()) {
6126                pRIFF->DeleteSubChunk(lst3LS);
6127                lst3LS = NULL;
6128            }
6129    
6130          // first update base class's chunks          // first update base class's chunks
6131          DLS::File::UpdateChunks();          DLS::File::UpdateChunks(pProgress);
6132    
6133          if (newFile) {          if (newFile) {
6134              // INFO was added by Resource::UpdateChunks - make sure it              // INFO was added by Resource::UpdateChunks - make sure it
# Line 5122  namespace { Line 6165  namespace {
6165              std::list<Group*>::iterator iter = pGroups->begin();              std::list<Group*>::iterator iter = pGroups->begin();
6166              std::list<Group*>::iterator end  = pGroups->end();              std::list<Group*>::iterator end  = pGroups->end();
6167              for (; iter != end; ++iter) {              for (; iter != end; ++iter) {
6168                  (*iter)->UpdateChunks();                  (*iter)->UpdateChunks(pProgress);
6169              }              }
6170          }          }
6171    
# Line 5142  namespace { Line 6185  namespace {
6185          // Note that there are several fields with unknown use. These          // Note that there are several fields with unknown use. These
6186          // are set to zero.          // are set to zero.
6187    
6188          int sublen = pSamples->size() / 8 + 49;          int sublen = int(pSamples->size() / 8 + 49);
6189          int einfSize = (Instruments + 1) * sublen;          int einfSize = (Instruments + 1) * sublen;
6190    
6191          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);          RIFF::Chunk* einf = pRIFF->GetSubChunk(CHUNK_ID_EINF);
# Line 5215  namespace { Line 6258  namespace {
6258                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);                  store32(&pData[(instrumentIdx + 1) * sublen + 24], nbloops);
6259                  // next 8 bytes unknown                  // next 8 bytes unknown
6260                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);                  store32(&pData[(instrumentIdx + 1) * sublen + 36], instrumentIdx);
6261                  store32(&pData[(instrumentIdx + 1) * sublen + 40], pSamples->size());                  store32(&pData[(instrumentIdx + 1) * sublen + 40], (uint32_t) pSamples->size());
6262                  // next 4 bytes unknown                  // next 4 bytes unknown
6263    
6264                  totnbregions += instrument->Regions;                  totnbregions += instrument->Regions;
# Line 5233  namespace { Line 6276  namespace {
6276              store32(&pData[24], totnbloops);              store32(&pData[24], totnbloops);
6277              // next 8 bytes unknown              // next 8 bytes unknown
6278              // next 4 bytes unknown, not always 0              // next 4 bytes unknown, not always 0
6279              store32(&pData[40], pSamples->size());              store32(&pData[40], (uint32_t) pSamples->size());
6280              // next 4 bytes unknown              // next 4 bytes unknown
6281          }          }
6282    
6283          // update 3crc chunk          // update 3crc chunk
6284    
6285          // The 3crc chunk contains CRC-32 checksums for the          // The 3crc chunk contains CRC-32 checksums for the
6286          // samples. The actual checksum values will be filled in          // samples. When saving a gig file to disk, we first update the 3CRC
6287          // later, by Sample::Write.          // chunk here (in RAM) with the old crc values which we read from the
6288            // 3CRC chunk when we opened the file (available with gig::Sample::crc
6289            // member variable). This step is required, because samples might have
6290            // been deleted by the user since the file was opened, which in turn
6291            // changes the order of the (i.e. old) checksums within the 3crc chunk.
6292            // If a sample was conciously modified by the user (that is if
6293            // Sample::Write() was called later on) then Sample::Write() will just
6294            // update the respective individual checksum(s) directly on disk and
6295            // leaves all other sample checksums untouched.
6296    
6297          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);          RIFF::Chunk* _3crc = pRIFF->GetSubChunk(CHUNK_ID_3CRC);
6298          if (_3crc) {          if (_3crc) {
6299              _3crc->Resize(pSamples->size() * 8);              _3crc->Resize(pSamples->size() * 8);
6300          } else if (newFile) {          } else /*if (newFile)*/ {
6301              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);              _3crc = pRIFF->AddSubChunk(CHUNK_ID_3CRC, pSamples->size() * 8);
             _3crc->LoadChunkData();  
   
6302              // the order of einf and 3crc is not the same in v2 and v3              // the order of einf and 3crc is not the same in v2 and v3
6303              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);              if (einf && pVersion && pVersion->major == 3) pRIFF->MoveSubChunk(_3crc, einf);
6304          }          }
6305            { // must be performed in RAM here ...
6306                uint32_t* pData = (uint32_t*) _3crc->LoadChunkData();
6307                if (pData) {
6308                    File::SampleList::iterator iter = pSamples->begin();
6309                    File::SampleList::iterator end  = pSamples->end();
6310                    for (int index = 0; iter != end; ++iter, ++index) {
6311                        gig::Sample* pSample = (gig::Sample*) *iter;
6312                        pData[index*2]   = 1; // always 1
6313                        pData[index*2+1] = pSample->crc;
6314                    }
6315                }
6316            }
6317        }
6318        
6319        void File::UpdateFileOffsets() {
6320            DLS::File::UpdateFileOffsets();
6321    
6322            for (Instrument* instrument = GetFirstInstrument(); instrument;
6323                 instrument = GetNextInstrument())
6324            {
6325                instrument->UpdateScriptFileOffsets();
6326            }
6327      }      }
6328    
6329      /**      /**

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

  ViewVC Help
Powered by ViewVC